Commit d8691416 authored by Sky's avatar Sky

~

parent 7ffe7ac4
...@@ -5,11 +5,11 @@ ohos { ...@@ -5,11 +5,11 @@ ohos {
signingConfigs { signingConfigs {
release { release {
storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12') storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12')
storePassword '0000001B37FBF75B69C866355CBEFC208DDF92764DE954F1C754CBD53E1B481433E2DBB6E2C3132D049A89' storePassword '0000001BFDB36C87CF75CE5C9C35B4EB247F0B973A3CEBFCE636F022CE70CBF7EA5D483CB9896BA93C3146'
keyAlias 'huawei_watch_overseas Release' keyAlias 'huawei_watch_overseas Release'
keyPassword '0000001BE894FABE766383262AD346CB8151121BA00764539557B67C6917C8C4B031ADCF67E1384F5FE120' keyPassword '0000001B32D22EDA409673EBC987E06A1784506F044E7486B4A2590B645408BBD960C712D03072C22FE304'
profile file('D:/HuaweiWatchClient/com.company.fit.provisionRelease.p7b') profile file('D:\\HuaweiWatchClient\\com.company.fit.provisionRelease.p7b')
certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_release.cer') certpath file('D:\\HuaweiWatchClient\\com.company.fit.overseas_release.cer')
signAlg 'SHA256withECDSA' signAlg 'SHA256withECDSA'
} }
} }
...@@ -30,7 +30,7 @@ buildscript { ...@@ -30,7 +30,7 @@ buildscript {
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'com.huawei.ohos:hap:2.4.1.4' classpath 'com.huawei.ohos:hap:2.4.2.5'
} }
} }
......
...@@ -4,20 +4,20 @@ ohos { ...@@ -4,20 +4,20 @@ ohos {
signingConfigs { signingConfigs {
debug { debug {
certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_debug.cer') certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_debug.cer')
profile file('D:/HuaweiWatchClient/com.company.fit.proDebug.p7b') profile file('D:/HuaweiWatchClient/FitSmartWatch.p7b')
signAlg 'SHA256withECDSA' signAlg 'SHA256withECDSA'
keyPassword '0000001B17F8F53E0CF14D52675968C4FD60AA48E6580B4EEEE4AE8348FA556850E01CC92EEA6DE834CA36' keyPassword '0000001B329C15F1A79D6DE1A35FC33EAC9D748ED2C9769503449638BCD341685E783C445341B6EF7252A0'
keyAlias 'huawei_watch_overseas Release' keyAlias 'huawei_watch_overseas Release'
storePassword '0000001B16A4C8B18003852BF6E890B38F6D624C8314D7E55CE2FD87CBC3F2C9E2DA9403C977F0C988ABAE' storePassword '0000001BED3DA1157AED6BA705ACB0E5A74DF33AB09917EF841F6048AA1D583907E32B547CE23E3D6415F8'
storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12') storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12')
} }
release { release {
storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12') storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12')
storePassword '0000001B76038D1DF78CD8E9F7D8F4E133ECE3FABA895EE4FEE9DDC4225267E3D2176904B14F7BF71AF47D' storePassword '0000001BE711A291624105B6065E58CF3582A64BD480021F7FA44D831AF7F47D3BAA28EE72E1ED5200671F'
keyAlias 'huawei_watch_overseas Release' keyAlias 'huawei_watch_overseas Release'
keyPassword '0000001B4BECAFAB52D2A2F0F1D06B36F5343980B0FD548D1BB1A84211DB54738785744DD4DF2640AAD1B5' keyPassword '0000001B9650C5F04495DB8963B0EA3435C222F7566D397075C0BCA00938DC2AC4A57E46138E9C0F70324C'
signAlg 'SHA256withECDSA' signAlg 'SHA256withECDSA'
profile file('D:/HuaweiWatchClient/com.company.fit.provisionRelease.p7b') profile file('D:\\HuaweiWatchClient\\com.company.fit.provisionRelease.p7b')
certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_release.cer') certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_release.cer')
} }
} }
...@@ -27,14 +27,14 @@ ohos { ...@@ -27,14 +27,14 @@ ohos {
compatibleSdkVersion 3 compatibleSdkVersion 3
} }
} }
sourceSets{ sourceSets {
main{ main {
java{ java {
srcDir 'build\\generated\\source\\r\\debug' srcDir 'build\\generated\\source\\r\\debug'
} }
} }
} }
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
testCompile'junit:junit:4.12' testCompile 'junit:junit:4.12'
} }
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
"app": { "app": {
"bundleName": "com.company.fit", "bundleName": "com.company.fit",
"version": { "version": {
"code": 20, "code": 25,
"name": "1.0.2" "name": "1.0.3"
}, },
"apiVersion": { "apiVersion": {
"compatible": 3, "compatible": 3,
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
{ {
"name": "default", "name": "default",
"icon": "$media:icon", "icon": "$media:icon",
"label": "Fit健身", "label": "$string:app_name",
"type": "page" "type": "page"
} }
], ],
...@@ -35,6 +35,11 @@ ...@@ -35,6 +35,11 @@
"extra": "", "extra": "",
"name": "supportLists", "name": "supportLists",
"value": "com.sportq.fit:B1B788A1BBD5F459BC641DA8CE690EA065C96957F58E883764982B5C46E53E06" "value": "com.sportq.fit:B1B788A1BBD5F459BC641DA8CE690EA065C96957F58E883764982B5C46E53E06"
},
{
"extra": "",
"name": "hwc-theme",
"value": "androidhwext:style/Theme.Emui.Dark.NoActionBar"
} }
] ]
}, },
...@@ -57,7 +62,7 @@ ...@@ -57,7 +62,7 @@
], ],
"when": "always" "when": "always"
}, },
"name": "harmonyos.permission.READ_HEALTH_DATA" "name": "ohos.permission.READ_HEALTH_DATA"
} }
] ]
} }
......
/* /*
* Copyright (c) 2020 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
...@@ -11,318 +11,434 @@ ...@@ -11,318 +11,434 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* Version: 5.0.1.301 * Version: 5.0.2.300
* Description: wearEngine SDK * Description: wearEngine SDK
*/ */
import wearengine from "@system.wearengine"; import wearengine from "@system.wearengine";
var P2pClient = (function () { var WearEngineConst = {
var peerPkgName; DELAY_FILEAPP_VALUE: "internal://app/", // 三方应用默认文件存储路径
var peerFingerPrint; DEFAULT_EMPTY_VALUE: "", // 默认空字符串
var version; };
var ErrorCode = {
MSG_ERROR_PING_WATCH_APP_NOT_EXIST: 200, // 手表应用未安装。
MSG_ERROR_PING_WATCH_APP_NOT_RUNNING: 201, // 手表应用已安装未启动。
MSG_ERROR_PING_WATCH_APP_EXIST_RUNNING: 202, // 手表应用已安装已启动。
MSG_ERROR_PING_OTHER: 203, // 其他错误。
MSG_ERROR_PING_PHONE_APP_NOT_EXIST: 204, //手机应用未安装。
MSG_ERROR_PING_PHONE_APP_NOT_RUNNING: 205, // 手机应用已安装。
MSG_ERROR_SEND_FAIL: 206, // 发送消息失败。
MSG_ERROR_SEND_SUCCESS: 207, // 发送消息成功。
MSG_ERROR_CODE_VERSION_TOO_LOW: 208 // 手表wearEngine版本太低。
};
var MessageType = {
MESSAGE_TYPE_DATA: 0, // 文本消息
MESSAGE_TYPE_FILE: 1 // 文件消息
};
function P2pClient(context) { var WEARENGINE_SERVICE_VISION_302 = 302;
try { var WEARENGINE_SERVICE_VISION_303 = 303;
var jsSdk = this; var WEARENGINE_SDK_VERSION = "3";
var getVersionCallBack = function (data) { var FILE_PUNLIC_PATH_INTERCETPED = 15;
if (data) { var DEFAULT_EMPTY_FINGERPRINT = " ";
var versionArray = data.split(".");
jsSdk.version = versionArray[versionArray.length-1];
console.log("service sdk version is: " + data);
}else{
jsSdk.version = 0;
console.log("get service sdk version failed");
}
};
wearengine.getWearEngineVersion({
complete: getVersionCallBack,
sdkVersion: "2",
});
} catch(error) { var P2pClient = (function() {
jsSdk.version = 0; var peerPkgName;
console.log("service sdk version is too low" + error.message); var peerFingerPrint;
var version;
function P2pClient() {
try {
var jsSdk = this;
var getVersionCallBack = function(data) {
if (data) {
var versionArray = data.split(".");
jsSdk.version = versionArray[versionArray.length - 1];
console.info("service sdk version is: " + data);
} else {
jsSdk.version = 0;
console.info("get service sdk version failed");
} }
};
wearengine.getWearEngineVersion({
complete: getVersionCallBack,
sdkVersion: WEARENGINE_SDK_VERSION
});
} catch (error) {
jsSdk.version = 0;
console.info("service sdk version is too low" + error.message);
}
}
/**
* 设置手机应用的packageName
* peerPkgName: string
*/
P2pClient.prototype.setPeerPkgName = function(peerPkgName) {
var successCallBack = function() {
console.info("setPeerPkgName success.");
};
var failCallBack = function() {
console.info("setPeerPkgName fail.");
};
this.peerPkgName = peerPkgName;
if (this.version < WEARENGINE_SERVICE_VISION_303) {
console.info("ERROR_CODE_VERSION_TOO_LOW setPackageName is invalid");
return;
}
wearengine.setPackageName({
appName: peerPkgName,
complete: successCallBack,
fail: failCallBack
});
};
/**
* 设置手机侧指纹信息
* fingerPrint: string
*/
P2pClient.prototype.setPeerFingerPrint = function(fingerPrint) {
if (this.version < WEARENGINE_SERVICE_VISION_302) {
console.info("setPeerFingerPrint interface invalid");
var obj = {
data: "ERROR_CODE_VERSION_TOO_LOW",
code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW
};
return obj;
}
if (isEmpty(fingerPrint)) {
fingerPrint = DEFAULT_EMPTY_FINGERPRINT;
}
this.peerFingerPrint = fingerPrint;
var successCallBack = function() {
console.info("setPeerFingerPrint success.");
};
var failCallBack = function() {
console.error("setPeerFingerPrint failed.");
};
wearengine.setFingerprint({
appName: this.peerPkgName,
appCert: fingerPrint,
complete: successCallBack,
fail: failCallBack
});
};
/**
* 检测对端设备侧是否已经安装指定应用
* pingCallback: object:onSuccess(),onFailure(),onPingResult(resultCode)
*/
P2pClient.prototype.ping = function(pingCallback) {
var successCode = {
data: " ERROR_CODE_P2P_PHONE_APP_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING
};
var successCallBack = function() {
pingCallback.onSuccess();
pingCallback.onPingResult(successCode);
console.info("ping success.");
};
var notInstallCode = {
data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST
};
var failCode = {
data: "ERROR_CODE_P2P_OTHER_ERROR",
code: ErrorCode.MSG_ERROR_PING_OTHER
};
if (isEmpty(this.peerPkgName)) {
pingCallback.onFailure();
pingCallback.onPingResult(notInstallCode);
return;
} }
/** var failCallBack = function(data, code) {
* 设置手机应用的packageName if (!data && !code) {
* peerPkgName: string pingCallback.onFailure();
*/ pingCallback.onPingResult(notInstallCode);
P2pClient.prototype.setPeerPkgName = function (peerPkgName) { } else {
this.peerPkgName = peerPkgName; pingCallback.onFailure();
pingCallback.onPingResult(failCode);
}
console.error("ping failed.");
}; };
/** FeatureAbility.detect({
* 设置手机侧指纹信息 bundleName: this.peerPkgName,
* fingerPrint: string success: successCallBack,
*/ fail: failCallBack
P2pClient.prototype.setPeerFingerPrint = function (fingerPrint) { });
if (this.version < 302) { };
console.log("setPeerFingerPrint interface invalid"); /**
var obj = { * 注册消息监听接口
data: "ERROR_CODE_VERSION_TOO_LOW", * receiver:object:onSuccess(),onFailure(),onReceiveMessage(message)
code: 208, */
}; P2pClient.prototype.registerReceiver = function(receiver) {
return obj; if (!receiver) {
return;
}
if (this.version > WEARENGINE_SERVICE_VISION_302) {
if (isEmpty(this.peerPkgName)) {
console.error("peerPkgName cannot be empty");
receiver.onFailure();
return;
}
var setPeerPkgNameSuccessCallBack = function() {
console.info("registerReceiver setPeerPkgName success.");
};
var setPeerPkgNameFailCallBack = function() {
console.info("registerReceiver setPeerPkgName fail.");
return;
};
wearengine.setPackageName({
appName: this.peerPkgName,
complete: setPeerPkgNameSuccessCallBack,
fail: setPeerPkgNameFailCallBack
});
}
if (isEmpty(this.peerFingerPrint)) {
console.error("peerFingerPrint cannot be empty");
receiver.onFailure();
return;
}
var successCallBack = function(data) {
if (data) {
if (data.isRegister) {
receiver.onSuccess();
} else if (data.isFileType){
var fileObj = {
isFileType: true,
name: data.file,
mode: "",
mode2: ""
};
receiver.onReceiveMessage(fileObj);
console.info("receive file name:" + fileObj.name);
} else {
receiver.onReceiveMessage(data.message);
console.info("receive message:" + data.message);
} }
this.peerFingerPrint = fingerPrint; } else {
var successCallBack = function () { receiver.onSuccess();
console.log("fingerPrint setup succeeded"); }
};
var failCallBack = function () {
console.log("fingerPrint setup failed");
};
wearengine.setFingerprint({
appName: this.peerPkgName,
appCert: fingerPrint,
complete: successCallBack,
fail: failCallBack,
});
}; };
/**
* 检测对端设备侧是否已经安装指定应用 FeatureAbility.subscribeMsg({
* pingCallback: object:onSuccess(),onFailure(),onPingResult(resultCode) success: successCallBack,
*/ fail: receiver.onFailure
P2pClient.prototype.ping = function (pingCallback) { });
};
/**
* 发送消息接口
* message: Message
* sendCallback: object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count)
* resultCode: SUCCESS 207, FAILURE 206
*/
P2pClient.prototype.send = function(message, sendCallback) {
if (!message || !sendCallback) {
return;
}
var failCode = {
data: "peerPkgName or peerFingerPrint empty",
code: ErrorCode.MSG_ERROR_SEND_FAIL
};
if (isEmpty(this.peerPkgName) || isEmpty(this.peerFingerPrint)) {
console.error("peerPkgName or peerFingerPrint cannot be empty");
sendCallback.onFailure();
sendCallback.onSendResult(failCode);
return;
}
if (message.getType() == MessageType.MESSAGE_TYPE_DATA) {
var successCallBack = function() {
var successCode = { var successCode = {
data: "ERROR_CODE_P2P_PHONE_APP_EXIT", data: "ERROR_CODE_COMM_SUCCESS",
code: 205, code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
var successCallBack = function () {
pingCallback.onSuccess();
pingCallback.onPingResult(successCode);
};
var notInstallCode = {
data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIT",
code: 204,
}; };
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
sendCallback.onSendProgress(100 + "%");
console.info("send message success.");
};
var failCallBack = function(errorMessage, code) {
var failCode = { var failCode = {
data: "ERROR_CODE_P2P_OTHER_ERROR", data: errorMessage,
code: 203, code: ErrorCode.MSG_ERROR_SEND_FAIL
};
var failCallBack = function (data, code) {
if (!data && !code) {
pingCallback.onFailure();
pingCallback.onPingResult(notInstallCode);
} else {
pingCallback.onFailure();
pingCallback.onPingResult(failCode);
}
}; };
FeatureAbility.detect({ sendCallback.onFailure();
bundleName: this.peerPkgName, sendCallback.onSendResult(failCode);
success: successCallBack, sendCallback.onSendProgress(0 + "%");
fail: failCallBack, console.error("send message failed.");
}); };
}; FeatureAbility.sendMsg({
/** deviceId: "remote",
* 注册消息监听接口 bundleName: this.peerPkgName,
* receiver:object:onSuccess(),onFailure(),onReceiveMessage(message) abilityName: "",
*/ message: message.getData(),
P2pClient.prototype.registerReceiver = function (receiver) { success: successCallBack,
if (!receiver) { fail: failCallBack
return; });
} } else {
var successCallBack = function (data) { if (this.version < WEARENGINE_SERVICE_VISION_302) {
receiver.onSuccess(); console.info("not support send file");
if (data) { var obj = {
if (data.isFileType) { data: "ERROR_CODE_VERSION_TOO_LOW",
var fileObj = { code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW
isFileType: true,
name: data.file,
mode: "",
mode2: "",
};
receiver.onReceiveMessage(fileObj);
} else {
receiver.onReceiveMessage(data.message);
}
} else {
receiver.onReceiveMessage(data);
}
}; };
sendCallback.onFailure();
sendCallback.onSendResult(obj);
return;
}
FeatureAbility.subscribeMsg({ var fileName = message.getFile().name;
success: successCallBack, // service 版本 303以下不支持 "internal://app/" 路径
fail: receiver.onFailure, if (this.version < WEARENGINE_SERVICE_VISION_303) {
}); var TempPath = fileName.substring(0, FILE_PUNLIC_PATH_INTERCETPED);
}; if (TempPath == WearEngineConst.DELAY_FILEAPP_VALUE) {
/** var obj = {
* 发送消息接口 data: "ERROR_CODE_VERSION_TOO_LOW",
* message: Message code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW
* sendCallback: object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count) };
* resultCode: SUCCESS 207, FAILURE 206 sendCallback.onFailure();
*/ sendCallback.onSendResult(obj);
P2pClient.prototype.send = function (message, sendCallback) { console.info("wearEngine service version too low, file path not support");
if (!message || !sendCallback) { return;
return;
} }
}
var successCallBack = function() {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
};
if (message.getType() == 0) { var failCallBack = function(errorMessage, code) {
var successCallBack = function () { var failCode = {
var successCode = { data: errorMessage,
data: "ERROR_CODE_COMM_SUCCESS", code: ErrorCode.MSG_ERROR_SEND_FAIL
code: 207, };
}; sendCallback.onFailure();
sendCallback.onSuccess(); sendCallback.onSendResult(failCode);
sendCallback.onSendResult(successCode); };
sendCallback.onSendProgress(100 + "%"); var progressCallBack = function(data) {
}; sendCallback.onSendProgress(data.progressNum + "%");
console.info("progress of sending file: " + data.progressNum + "%");
var failCallBack = function (errorMessage, code) { };
var failCode = {
data: errorMessage,
code: 206,
};
sendCallback.onFailure();
sendCallback.onSendResult(failCode);
sendCallback.onSendProgress(0 + "%");
};
FeatureAbility.sendMsg({
deviceId: "remote",
bundleName: this.peerPkgName,
abilityName: "",
message: message.getData(),
success: successCallBack,
fail: failCallBack,
});
} else {
if (this.version < 302) {
console.log("not support send file");
var obj = {
data: "ERROR_CODE_VERSION_TOO_LOW",
code: 208,
};
sendCallback.onFailure();
sendCallback.onSendResult(obj);
return;
}
var successCallBack = function () {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: 207,
};
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
};
var failCallBack = function (errorMessage, code) { wearengine.uploadFile({
var failCode = { fileName: fileName,
data: errorMessage, filePath: this.peerPkgName,
code: 206, peerPackageName: this.peerPkgName,
}; success: successCallBack,
sendCallback.onFailure(); fail: failCallBack,
sendCallback.onSendResult(failCode); progress: progressCallBack
}; });
var progressCallBack = function (data) { }
sendCallback.onSendProgress(data.progressNum + "%"); };
}; /**
var fileName = message.getFile().name; * 注销监听接口
wearengine.uploadFile({ * receiver: onSuccess()
fileName: fileName, */
filePath: this.peerPkgName, P2pClient.prototype.unregisterReceiver = function(receiver) {
peerPackageName: this.peerPkgName, FeatureAbility.unsubscribeMsg();
success: successCallBack, receiver.onSuccess();
fail: failCallBack, };
progress: progressCallBack, /**
}); * 判断参数是否为空
} * parameter: string
}; */
/** function isEmpty(parameter) {
* 注销监听接口 return parameter == "undefined" || parameter == null || parameter == "" || parameter == " ";
* receiver: onSuccess() }
*/ return P2pClient;
P2pClient.prototype.unregisterReceiver = function (receiver) {
FeatureAbility.unsubscribeMsg();
receiver.onSuccess();
};
return P2pClient;
})(); })();
/** /**
* 文件格式 * 文件格式类型
* name: file name with path * name: file name with path
* mode: 'text' or 'binary' * mode: 'text' or 'binary'
* mode2: 'R', 'W', 'RW' * mode2: 'R', 'W', 'RW'
*/ */
var File = (function () { var File = (function() {
var name; var name;
var mode; var mode;
var mode2; var mode2;
function File() {} function File() {}
return File;
})(); })();
var Builder = (function () {
var messageInfo;
function Builder(context) {} var Builder = (function() {
var messageInfo;
Builder.prototype.setDescription = function (description) { function Builder() {}
this.messageInfo = description;
this.messageType = 0; Builder.prototype.setDescription = function(description) {
}; this.messageInfo = description;
/** this.messageType = MessageType.MESSAGE_TYPE_DATA;
* 设置messge信息(两种格式任选其一) };
* data: ArrayBuffer /**
* data: File(暂时不支持) * 设置messge信息(两种格式任选其一)
*/ * data: ArrayBuffer
Builder.prototype.setPayload = function (data) { * data: File(暂时不支持)
if (!data) { */
return; Builder.prototype.setPayload = function(data) {
} if (!data) {
if (typeof data == "object" && data.name) { return;
this.messageType = 1; }
return this.setFilePlayload(data); if (typeof data == "object" && data.name) {
} else { this.messageType = MessageType.MESSAGE_TYPE_FILE;
this.messageType = 0; return this.setFilePlayload(data);
return this.setBufferPlayload(data); } else {
} this.messageType = MessageType.MESSAGE_TYPE_DATA;
}; return this.setBufferPlayload(data);
Builder.prototype.setBufferPlayload = function (data) { }
this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data)); };
}; Builder.prototype.setBufferPlayload = function(data) {
Builder.prototype.setFilePlayload = function (data) { this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data));
this.messageInfo = JSON.stringify(data); };
}; Builder.prototype.setFilePlayload = function(data) {
return Builder; this.messageInfo = JSON.stringify(data);
};
return Builder;
})(); })();
var Message = (function () {
var builder = new Builder();
function Message(context) {} var Message = (function() {
Message.prototype.describeContents = function () { var builder = new Builder();
return this.builder.messageInfo;
}; function Message() {}
/**
* 获取传送时的信息 Message.prototype.describeContents = function() {
*/ return this.builder.messageInfo;
Message.prototype.getData = function () { };
return this.builder.messageInfo; /**
}; * 获取传送时的信息
Message.prototype.getDescription = function () { */
return this.builder.messageInfo; Message.prototype.getData = function() {
}; return this.builder.messageInfo;
/** };
* 获取文件信息 Message.prototype.getDescription = function() {
*/ return this.builder.messageInfo;
Message.prototype.getFile = function () { };
if (this.builder.messageType == 1) { /**
return JSON.parse(this.builder.messageInfo); * 获取文件信息
} */
return null; Message.prototype.getFile = function() {
}; if (this.builder.messageType == MessageType.MESSAGE_TYPE_FILE) {
/** return JSON.parse(this.builder.messageInfo);
* 获取传输数据类型 }
* 0 string return null;
* 1 File };
*/ /**
Message.prototype.getType = function () { * 获取传输数据类型
return this.builder.messageType; * 0 string
}; * 1 File
return Message; */
Message.prototype.getType = function() {
return this.builder.messageType;
};
return Message;
})(); })();
export { export { P2pClient, Message, Builder };
P2pClient,
Message,
Builder
};
...@@ -17,13 +17,14 @@ export default { ...@@ -17,13 +17,14 @@ export default {
let _this = this; let _this = this;
//获取客户端信息 //获取客户端信息
_this.getMsg(); _this.getMsg();
},
onShow() {
let _this = this;
//更新页面数据 //更新页面数据
_this.acCalorie = _this.endCalorie; _this.acCalorie = _this.endCalorie;
_this.fitTotalDuration = _this.endTotalTime; _this.fitTotalDuration = _this.endTotalTime;
_this.averHeartRate = _this.endAverHeartRate; _this.averHeartRate = _this.endAverHeartRate;
_this.maxHeartRate = _this.endMaxHeartRate; _this.maxHeartRate = _this.endMaxHeartRate;
},
onShow() {
//取消常亮 //取消常亮
brightness.setKeepScreenOn({ brightness.setKeepScreenOn({
keepScreenOn: false, keepScreenOn: false,
...@@ -35,6 +36,7 @@ export default { ...@@ -35,6 +36,7 @@ export default {
}, },
onDestroy() { onDestroy() {
//取消接收手机侧第三方应用发过来的消息 //取消接收手机侧第三方应用发过来的消息
console.error("end--onDestroy:unregisterReceiver")
p2pClient.unregisterReceiver({ p2pClient.unregisterReceiver({
onSuccess: function () { onSuccess: function () {
}, },
......
...@@ -193,11 +193,12 @@ ...@@ -193,11 +193,12 @@
/**已训练**/ /**已训练**/
.train-new-title { .train-new-title {
font-size: 38px; font-size: 38px;
height: 38px; height: 40px;
margin-top: 60px; margin-top: 60px;
width: 350px; width: 350px;
color: #FFFFFF; color: #FFFFFF;
text-align: center; text-align: center;
line-hight: 40px;
} }
.train-time { .train-time {
justify-content: center; justify-content: center;
......
...@@ -38,6 +38,7 @@ export default { ...@@ -38,6 +38,7 @@ export default {
}, },
onInit() { onInit() {
p2pClient.setPeerPkgName("com.sportq.fit"); p2pClient.setPeerPkgName("com.sportq.fit");
p2pClient.setPeerFingerPrint("B1B788A1BBD5F459BC641DA8CE690EA065C96957F58E883764982B5C46E53E06");
}, },
onReady() { onReady() {
let _this = this; let _this = this;
...@@ -129,7 +130,7 @@ export default { ...@@ -129,7 +130,7 @@ export default {
},2 * 60 * 1000); },2 * 60 * 1000);
} }
//数据重置 //数据重置
_this.init(); _this.initData();
_this.canReceiveMessage = true; _this.canReceiveMessage = true;
if (_this.isFirstInit) { if (_this.isFirstInit) {
_this.isFirstInit = false; _this.isFirstInit = false;
...@@ -368,7 +369,7 @@ export default { ...@@ -368,7 +369,7 @@ export default {
}, },
onSendResult: function (resultCode) { onSendResult: function (resultCode) {
// send任务执行结束后返回的错误码和信息进行处理 // send任务执行结束后返回的错误码和信息进行处理
console.log(resultCode.data + resultCode.code); console.log("sendMsg:" + resultCode.data + resultCode.code);
}, },
} }
if (sendMessage != null && sendCallback != null) { if (sendMessage != null && sendCallback != null) {
...@@ -424,9 +425,11 @@ export default { ...@@ -424,9 +425,11 @@ export default {
var receiver = { var receiver = {
onSuccess: function () { onSuccess: function () {
// 处理注册接收手机侧简短消息或文件成功的回调函数 // 处理注册接收手机侧简短消息或文件成功的回调函数
console.error("index--getMsg:registerReceiver:onSuccess")
}, },
onFailure: function () { onFailure: function () {
// 处理注册接收手机侧简短消息或文件失败的回调函数 // 处理注册接收手机侧简短消息或文件失败的回调函数
console.error("index--getMsg:registerReceiver:onFailure")
}, },
onReceiveMessage: function (data) { onReceiveMessage: function (data) {
_this.start(JSON.parse(data)); _this.start(JSON.parse(data));
...@@ -554,11 +557,6 @@ export default { ...@@ -554,11 +557,6 @@ export default {
this.fitDuration = "00:00"; this.fitDuration = "00:00";
this.progress = "", //进度条 this.progress = "", //进度条
this.countdownT = "", // 倒计时 this.countdownT = "", // 倒计时
//取消接收手机侧第三方应用发过来的消息
p2pClient.unregisterReceiver({
onSuccess: function () {
},
});
sensor.unsubscribeHeartRate() //取消监听心率 sensor.unsubscribeHeartRate() //取消监听心率
}, },
...@@ -566,7 +564,7 @@ export default { ...@@ -566,7 +564,7 @@ export default {
/** /**
*数据重置 *数据重置
*/ */
init() { initData() {
this.isStop = false; this.isStop = false;
this.sendFlg = false; this.sendFlg = false;
this.stopFlg = false; this.stopFlg = false;
......
/* /*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. * Wear Engine Library For wearable device v5.0.1.301
*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
*
* Date: 2021-04-06
*/ */
import wearengine from "@system.wearengine"; import file from "@system.file";
var P2pClient; const injectRef = Object.getPrototypeOf(global) || global;
var Builder;
injectRef.regeneratorRuntime = require("@babel/runtime/regenerator");
try {
const device = require("@system.device");
device.getInfo({
success: function(data) {
globalThis.isLite = !(data.product.includes("GLL") || data.product.includes("Galileo"));
},
fail: function(data) {
globalThis.isLite = !(data.product.includes("GLL") || data.product.includes("Galileo"));
}
});
} catch (error) {
console.error("not support system.device, service sdk version is too low" + error.message);
}
var FeatureAbilityOption = { var FeatureAbilityOption = {
BUNDLE_NAME: "com.huawei.watch.kit.hiwearability", // 设置AA侧服务应用包名称 BUNDLE_NAME: "com.huawei.watch.kit.hiwearability", // 设置AA侧服务应用包名称
ABILITY_NAME: "com.huawei.watch.kit.hiwearability.HiWearServiceAbility", // 设置AA侧指定service名称 ABILITY_NAME: "com.huawei.watch.kit.hiwearability.HiWearServiceAbility", // 设置AA侧指定service名称
ABILITY_TYPE: 0, // 设置AA侧指定请求服务类型, abilityType: 0-Ability; 1-Internal Ability ABILITY_TYPE: 0, // 设置AA侧指定请求服务类型, abilityType: 0-Ability; 1-Internal Ability
SYNCOPTION_TYPE: 0 // 设置AA侧请求方式(Ace框架,目前Ability方式,只支持Sync同步方式), 0-Sync; 1-Async SYNCOPTION_TYPE: 0 // 设置AA侧请求方式(Ace框架,目前Ability方式,只支持Sync同步方式), 0-Sync; 1-Async
}; };
var RequestCode = { var RequestCode = {
INIT_CODEVALUE: 1000, // 初始化请求码 INIT_CODEVALUE: 1000, // 初始化请求码
REGISTER_RECEIVER_CODEVALUE: 1001, // 注册接收请求码 REGISTER_RECEIVER_CODEVALUE: 1001, // 注册接收请求码
UNREGISTER_RECEIVER_CODEVALUE: 1002, // 取消注册接收请求码 UNREGISTER_RECEIVER_CODEVALUE: 1002, // 取消注册接收请求码
PING_CODEVALUE: 1003, // PING探测请求码 PING_CODEVALUE: 1003, // PING探测请求码
SENDMESSAGE_CODEVALUE: 1004, // 发文本消息请求码 SENDMESSAGE_CODEVALUE: 1004, // 发文本消息请求码
SENDFILE_CODEVALUE: 1005, // 发文件消息请求码 SENDFILE_CODEVALUE: 1005, // 发文件消息请求码
SUBSCRIBE_ABILITY_CODEVALUE: 1006, // 通道消息订阅 SUBSCRIBE_ABILITY_CODEVALUE: 1006, // 通道消息订阅
UNSUBSCRIBE_ABILITY_CODEVALUE: 1007 // 通道消息取消订阅 UNSUBSCRIBE_ABILITY_CODEVALUE: 1007 // 通道消息取消订阅
}; };
var WearEngineConst = { var WearEngineConst = {
DELAY_INIT_TIME_VALUE: 500, // 初始化延时默认值 DELAY_INIT_TIME_VALUE: 500, // 初始化延时默认值
DELAY_TIME_VALUE: 1000, // 消息发送延时默认值 DELAY_TIME_VALUE: 1000, // 消息发送延时默认值
DELAY_FILEAPP_VALUE: "internal://app/", // 三方应用默认文件存储路径 DELAY_FILEAPP_VALUE: "internal://app/", // 三方应用默认文件存储路径
DEFAULT_EMPTY_VALUE: "", // 默认空字符串 DEFAULT_EMPTY_VALUE: "", // 默认空字符串
MAX_TRANSFER_SIZE: 1024, // 分段发送文件时,每段的大小 MAX_TRANSFER_SIZE: 1024 * 50, // 分段发送文件时,每段的大小
FILE_TO_BE_CONTINUED: 1 // 需要继续发送文件的返回码 FILE_TO_BE_CONTINUED: 1, // 需要继续发送文件的返回码
END_FLAG: 1 // 手机给手表发送文件已经结束的标志
}; };
var ErrorCode = { var ErrorCode = {
MSG_ERROR_PING_WATCH_APP_NOT_EXIST: 200, // 手表应用未安装。 MSG_ERROR_PING_WATCH_APP_NOT_EXIST: 200, // 手表应用未安装。
MSG_ERROR_PING_WATCH_APP_NOT_RUNNING: 201, // 手表应用已安装未启动。 MSG_ERROR_PING_WATCH_APP_NOT_RUNNING: 201, // 手表应用已安装未启动。
MSG_ERROR_PING_WATCH_APP_EXIST_RUNNING: 202, // 手表应用已安装已启动。 MSG_ERROR_PING_WATCH_APP_EXIST_RUNNING: 202, // 手表应用已安装已启动。
MSG_ERROR_PING_OTHER: 203, // 其他错误。 MSG_ERROR_PING_OTHER: 203, // 其他错误。
MSG_ERROR_PING_PHONE_APP_NOT_EXIST: 204, //手机应用未安装。 MSG_ERROR_PING_PHONE_APP_NOT_EXIST: 204, //手机应用未安装。
MSG_ERROR_PING_PHONE_APP_NOT_RUNNING: 205, // 手机应用已安装。 MSG_ERROR_PING_PHONE_APP_NOT_RUNNING: 205, // 手机应用已安装。
MSG_ERROR_SEND_FAIL: 206, // 发送消息失败。 MSG_ERROR_SEND_FAIL: 206, // 发送消息失败。
MSG_ERROR_SEND_SUCCESS: 207, // 发送消息成功。 MSG_ERROR_SEND_SUCCESS: 207, // 发送消息成功。
MSG_ERROR_CODE_VERSION_TOO_LOW: 208 // 手表wearEngine版本太低。 MSG_ERROR_CODE_VERSION_TOO_LOW: 208 // 手表wearEngine版本太低。
}; };
var MessageType = { var MessageType = {
MESSAGE_TYPE_DATA: 0, // 文本消息 MESSAGE_TYPE_DATA: 0, // 文本消息
MESSAGE_TYPE_FILE: 1 // 文件消息 MESSAGE_TYPE_FILE: 1 // 文件消息
}; };
var isFunction = obj => { var isFunction = obj => {
return typeof obj === "function" && typeof obj.nodeType !== "number"; return typeof obj === "function" && typeof obj.nodeType !== "number";
}; };
var WEARENGINE_SERVICE_VISION_303 = 303; var P2pClient = (function () {
var WEARENGINE_SDK_VERSION = "3";
if (typeof globalThis == "undefined" || globalThis.isLite) {
P2pClient = (function() {
var peerPkgName;
var peerFingerPrint;
var version;
function P2pClient() {
try {
var jsSdk = this;
var getVersionCallBack = function(data) {
if (data) {
var versionArray = data.split(".");
jsSdk.version = versionArray[versionArray.length - 1];
console.log("service sdk version is: " + data);
} else {
jsSdk.version = 0;
console.log("get service sdk version failed");
}
};
wearengine.getWearEngineVersion({
complete: getVersionCallBack,
sdkVersion: WEARENGINE_SDK_VERSION
});
} catch (error) {
jsSdk.version = 0;
console.log("service sdk version is too low" + error.message);
}
}
/**
* 设置手机应用的packageName
* peerPkgName: string
*/
P2pClient.prototype.setPeerPkgName = function(peerPkgName) {
var successCallBack = function() {
console.info("setPeerPkgName success.");
};
var failCallBack = function() {
console.info("setPeerPkgName fail.");
};
this.peerPkgName = peerPkgName;
if (this.version < WEARENGINE_SERVICE_VISION_303) {
console.log("ERROR_CODE_VERSION_TOO_LOW setPackageName is invalid");
return;
}
wearengine.setPackageName({
appName: peerPkgName,
complete: successCallBack,
fail: failCallBack
});
};
/**
* 设置手机侧指纹信息
* fingerPrint: string
*/
P2pClient.prototype.setPeerFingerPrint = function(fingerPrint) {
if (this.version < 302) {
console.log("setPeerFingerPrint interface invalid");
var obj = {
data: "ERROR_CODE_VERSION_TOO_LOW",
code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW
};
return obj;
}
this.peerFingerPrint = fingerPrint;
var successCallBack = function() {
console.info("setPeerFingerPrint success.");
};
var failCallBack = function() {
console.error("setPeerFingerPrint failed.");
};
wearengine.setFingerprint({
appName: this.peerPkgName,
appCert: fingerPrint,
complete: successCallBack,
fail: failCallBack
});
};
/**
* 检测对端设备侧是否已经安装指定应用
* pingCallback: object:onSuccess(),onFailure(),onPingResult(resultCode)
*/
P2pClient.prototype.ping = function(pingCallback) {
var successCode = {
data: " ERROR_CODE_P2P_PHONE_APP_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING
};
var successCallBack = function() {
pingCallback.onSuccess();
pingCallback.onPingResult(successCode);
console.info("ping success.");
};
var notInstallCode = {
data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST
};
var failCode = {
data: "ERROR_CODE_P2P_OTHER_ERROR",
code: ErrorCode.MSG_ERROR_PING_OTHER
};
if (isEmpty(this.peerPkgName)) {
pingCallback.onFailure();
pingCallback.onPingResult(notInstallCode);
return;
}
var failCallBack = function(data, code) {
if (!data && !code) {
pingCallback.onFailure();
pingCallback.onPingResult(notInstallCode);
} else {
pingCallback.onFailure();
pingCallback.onPingResult(failCode);
}
console.error("ping failed.");
};
FeatureAbility.detect({
bundleName: this.peerPkgName,
success: successCallBack,
fail: failCallBack
});
};
/**
* 注册消息监听接口
* receiver:object:onSuccess(),onFailure(),onReceiveMessage(message)
*/
P2pClient.prototype.registerReceiver = function(receiver) {
if (!receiver) {
return;
}
if (isEmpty(this.peerPkgName)) {
console.error("registerReceiver faile because of peerPkgName");
receiver.onFailure();
return;
}
var successCallBack = function(data) {
receiver.onSuccess();
if (data) {
if (data.isFileType) {
var fileObj = {
isFileType: true,
name: data.file,
mode: "",
mode2: ""
};
receiver.onReceiveMessage(fileObj);
console.info("receive message or file name:" + fileObj.name);
} else {
receiver.onReceiveMessage(data.message);
console.info("receive message or file name:" + data.message);
}
} else {
receiver.onReceiveMessage(data);
}
};
FeatureAbility.subscribeMsg({
success: successCallBack,
fail: receiver.onFailure
});
};
/**
* 发送消息接口
* message: Message
* sendCallback: object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count)
* resultCode: SUCCESS 207, FAILURE 206
*/
P2pClient.prototype.send = function(message, sendCallback) {
if (!message || !sendCallback) {
return;
}
if (message.getType() == 0) {
var successCallBack = function() {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
sendCallback.onSendProgress(100 + "%");
console.info("send message success.");
};
var failCallBack = function(errorMessage, code) {
var failCode = {
data: errorMessage,
code: ErrorCode.MSG_ERROR_SEND_FAIL
};
sendCallback.onFailure();
sendCallback.onSendResult(failCode);
sendCallback.onSendProgress(0 + "%");
console.error("send message failed.");
};
FeatureAbility.sendMsg({
deviceId: "remote",
bundleName: this.peerPkgName,
abilityName: "",
message: message.getData(),
success: successCallBack,
fail: failCallBack
});
} else {
if (this.version < 302) {
console.log("not support send file");
var obj = {
data: "ERROR_CODE_VERSION_TOO_LOW",
code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW
};
sendCallback.onFailure();
sendCallback.onSendResult(obj);
return;
}
var successCallBack = function() {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
console.info("send file success.");
};
var failCallBack = function(errorMessage, code) {
var failCode = {
data: errorMessage,
code: ErrorCode.MSG_ERROR_SEND_FAIL
};
sendCallback.onFailure();
sendCallback.onSendResult(failCode);
console.error("send file failed.");
};
var progressCallBack = function(data) {
sendCallback.onSendProgress(data.progressNum + "%");
console.info("progress of sending file: " + data.progressNum + "%");
};
var fileName = message.getFile().name;
wearengine.uploadFile({
fileName: fileName,
filePath: this.peerPkgName,
peerPackageName: this.peerPkgName,
success: successCallBack,
fail: failCallBack,
progress: progressCallBack
});
}
};
/**
* 注销监听接口
* receiver: onSuccess()
*/
P2pClient.prototype.unregisterReceiver = function(receiver) {
FeatureAbility.unsubscribeMsg();
receiver.onSuccess();
};
/**
* 判断参数是否为空
*
* @param parameter
*/
function isEmpty(parameter) {
return parameter == "undefined" || parameter == null || parameter == "" || parameter == " ";
}
return P2pClient;
})();
Builder = (function() {
var messageInfo;
function Builder() {}
Builder.prototype.setDescription = function(description) {
this.messageInfo = description;
this.messageType = 0;
};
/**
* 设置messge信息(两种格式任选其一)
* data: ArrayBuffer
* data: File(暂时不支持)
*/
Builder.prototype.setPayload = function(data) {
if (!data) {
return;
}
if (typeof data == "object" && data.name) {
this.messageType = 1;
return this.setFilePlayload(data);
} else {
this.messageType = 0;
return this.setBufferPlayload(data);
}
};
Builder.prototype.setBufferPlayload = function(data) {
this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data));
};
Builder.prototype.setFilePlayload = function(data) {
this.messageInfo = JSON.stringify(data);
};
return Builder;
})();
} else {
const file = require("@system.file");
P2pClient = (function() {
const injectRef = Object.getPrototypeOf(global) || global;
injectRef.regeneratorRuntime = require("@babel/runtime/regenerator");
var peerPkgName; var peerPkgName;
var peerFingerPrint; var peerFingerPrint;
...@@ -387,62 +73,61 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -387,62 +73,61 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
var initSuccess = false; var initSuccess = false;
function P2pClient() { function P2pClient() {
this.setPeerFingerPrint(WearEngineConst.DEFAULT_EMPTY_VALUE, true); this.subscribeAbilityEvent();
this.subscribeAbilityEvent();
} }
/** /**
* 建立消息通道 * 建立消息通道
*/ */
P2pClient.prototype.subscribeAbilityEvent = async function() { P2pClient.prototype.subscribeAbilityEvent = async function() {
var action = this.getRequestHeader(RequestCode.SUBSCRIBE_ABILITY_CODEVALUE); var action = this.getRequestHeader(RequestCode.SUBSCRIBE_ABILITY_CODEVALUE);
var that = this; var that = this;
await FeatureAbility.subscribeAbilityEvent(action, function(callbackData) { await FeatureAbility.subscribeAbilityEvent(action, function (callbackData) {
var callbackJson = JSON.parse(callbackData); var callbackJson = JSON.parse(callbackData);
var receivedMessage = JSON.parse(JSON.stringify(callbackJson.data)); var receivedMessage = JSON.parse(JSON.stringify(callbackJson.data));
// 接收消息或文件 // 接收消息或文件
if (receivedMessage.messageType != "progress") { if (receivedMessage.messageType != "progress") {
var msgOrFileObj = handleReceivedMessage(receivedMessage, that); var msgOrFileObj = handleReceivedMessage(receivedMessage, that);
if (!msgOrFileObj) { if (!msgOrFileObj) {
return; return;
} }
if (messageCallbackMap[receivedMessage.peerPackageName]) {
console.info(
"receive message or file name: " + (typeof msgOrFileObj == "object" ? msgOrFileObj.name : msgOrFileObj)
);
var messageCallback = messageCallbackMap[receivedMessage.peerPackageName];
messageCallback(msgOrFileObj);
}
if (messageCallbackMap2[receivedMessage.peerPackageName]) {
var dataOrFileName = typeof msgOrFileObj == "object" ? msgOrFileObj.name : msgOrFileObj;
var messageType =
typeof msgOrFileObj == "object" ? MessageType.MESSAGE_TYPE_FILE : MessageType.MESSAGE_TYPE_DATA;
console.info("receive2 message or file name: " + dataOrFileName);
var receivedMessageObj = new Message();
var receivedMessageObjBuilder = new Builder();
receivedMessageObjBuilder.setReceivedInfo(messageType, dataOrFileName);
receivedMessageObj.builder = receivedMessageObjBuilder;
var messageCallback = messageCallbackMap2[receivedMessage.peerPackageName];
messageCallback(receivedMessageObj);
}
} else {
// 接受进度消息
console.info("progress of sending file: " + JSON.stringify(receivedMessage.abilityResult) + "%");
if (progressCallbackMap[receivedMessage.peerPackageName]) { if (messageCallbackMap[receivedMessage.peerPackageName]) {
var progressCallback = progressCallbackMap[receivedMessage.peerPackageName]; console.info(
progressCallback(JSON.stringify(receivedMessage.abilityResult)); "receive message or file name: " + (typeof msgOrFileObj == "object" ? msgOrFileObj.name : msgOrFileObj)
} );
} var messageCallback = messageCallbackMap[receivedMessage.peerPackageName];
}); messageCallback(msgOrFileObj);
}
if (messageCallbackMap2[receivedMessage.peerPackageName]) {
var dataOrFileName = typeof msgOrFileObj == "object" ? msgOrFileObj.name : msgOrFileObj;
var messageType =
typeof msgOrFileObj == "object" ? MessageType.MESSAGE_TYPE_FILE : MessageType.MESSAGE_TYPE_DATA;
console.info("receive2 message or file name: " + dataOrFileName);
var receivedMessageObj = new Message();
var receivedMessageObjBuilder = new Builder();
receivedMessageObjBuilder.setReceivedInfo(messageType, dataOrFileName);
receivedMessageObj.builder = receivedMessageObjBuilder;
var messageCallback = messageCallbackMap2[receivedMessage.peerPackageName];
messageCallback(receivedMessageObj);
}
} else {
// 接受进度消息
console.info("progress of sending file: " + JSON.stringify(receivedMessage.abilityResult) + "%");
if (progressCallbackMap[receivedMessage.peerPackageName]) {
var progressCallback = progressCallbackMap[receivedMessage.peerPackageName];
progressCallback(JSON.stringify(receivedMessage.abilityResult));
}
}
});
}; };
/** /**
...@@ -451,10 +136,7 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -451,10 +136,7 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param peerPkgName 目标应用包名称 * @param peerPkgName 目标应用包名称
*/ */
P2pClient.prototype.setPeerPkgName = async function(peerPkgName) { P2pClient.prototype.setPeerPkgName = async function(peerPkgName) {
if (!peerPkgName) { this.peerPkgName = peerPkgName;
return;
}
this.peerPkgName = peerPkgName;
}; };
/** /**
...@@ -462,50 +144,29 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -462,50 +144,29 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* *
* @param fingerPrint 目前应用指纹参数 * @param fingerPrint 目前应用指纹参数
*/ */
P2pClient.prototype.setPeerFingerPrint = async function(fingerPrint, isInit) { P2pClient.prototype.setPeerFingerPrint = async function(fingerPrint) {
var initInterval = globalThis.setInterval(() => {
if (!isInit && !initSuccess) {
return;
}
globalThis.clearInterval(initInterval);
this.peerFingerPrint = fingerPrint; this.peerFingerPrint = fingerPrint;
var actionData = { var actionData = {
dstPackageName: this.peerPkgName, dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint dstFingerPrint: fingerPrint
}; };
var action = this.getRequestHeader(RequestCode.INIT_CODEVALUE, actionData); var action = this.getRequestHeader(RequestCode.INIT_CODEVALUE, actionData);
if (!fingerPrint) {
FeatureAbility.callAbility(action).then(resultStr => { FeatureAbility.callAbility(action).then(
var resultObj = JSON.parse(resultStr); resultStr => {
if (resultObj.abilityResult == 1) {
console.info("remove p2pClient object success.");
initSuccess = true;
} else {
console.error("remove p2pClient object fail.");
}
});
} else {
globalThis.setTimeout(() => {
FeatureAbility.callAbility(action).then(
resultStr => {
var resultObj = JSON.parse(resultStr); var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) { if (resultObj.abilityResult == 1) {
console.info("setPeerFingerPrint success."); console.info("setPeerFingerPrint success.");
} else { } else {
console.error("setPeerFingerPrint failed."); console.error("setPeerFingerPrint failed.");
} }
}, },
() => { () => {
console.error("setPeerFingerPrint failed."); console.error("setPeerFingerPrint failed.");
} }
); );
}, WearEngineConst.DELAY_INIT_TIME_VALUE);
}
}, WearEngineConst.DELAY_INIT_TIME_VALUE);
}; };
/** /**
...@@ -514,50 +175,50 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -514,50 +175,50 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param pingCallback object:onSuccess(),onFailure(),onPingResult(resultCode) * @param pingCallback object:onSuccess(),onFailure(),onPingResult(resultCode)
*/ */
P2pClient.prototype.ping = async function(pingCallback) { P2pClient.prototype.ping = async function(pingCallback) {
var successCode = { var successCode = {
data: "ERROR_CODE_P2P_PHONE_APP_EXIST", data: "ERROR_CODE_P2P_PHONE_APP_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING
}; };
var notInstallCode = { var notInstallCode = {
data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIST", data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST
}; };
var failCode = { var failCode = {
data: "ERROR_CODE_P2P_OTHER_ERROR", data: "ERROR_CODE_P2P_OTHER_ERROR",
code: ErrorCode.MSG_ERROR_PING_OTHER code: ErrorCode.MSG_ERROR_PING_OTHER
}; };
var successCallBack = function() { var successCallBack = function () {
isFunction(pingCallback.onSuccess) && pingCallback.onSuccess(); isFunction(pingCallback.onSuccess) && pingCallback.onSuccess();
isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(successCode); isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(successCode);
}; };
var failCallBack = function(code) { var failCallBack = function (code) {
if (code == ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST) { if (code == ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST) {
isFunction(pingCallback.onFailure) && pingCallback.onFailure(); isFunction(pingCallback.onFailure) && pingCallback.onFailure();
isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(notInstallCode); isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(notInstallCode);
} else {
isFunction(pingCallback.onFailure) && pingCallback.onFailure();
isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(failCode);
}
};
var actionData = {
dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint
};
var action = this.getRequestHeader(RequestCode.PING_CODEVALUE, actionData);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING) {
successCallBack();
console.info("ping success.");
} else { } else {
isFunction(pingCallback.onFailure) && pingCallback.onFailure(); failCallBack(resultObj.abilityResult);
isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(failCode); console.error("ping failed.");
} }
};
var actionData = {
dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint
};
var action = this.getRequestHeader(RequestCode.PING_CODEVALUE, actionData);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING) {
successCallBack();
console.info("ping success.");
} else {
failCallBack(resultObj.abilityResult);
console.error("ping failed.");
}
}; };
/** /**
...@@ -566,36 +227,36 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -566,36 +227,36 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message) * @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message)
*/ */
P2pClient.prototype.registerReceiver = async function(receiver) { P2pClient.prototype.registerReceiver = async function(receiver) {
if (!receiver) { if (!receiver) {
return; return;
} }
var successCallBack = function() { var successCallBack = function () {
isFunction(receiver.onSuccess) && receiver.onSuccess(); isFunction(receiver.onSuccess) && receiver.onSuccess();
}; };
var failCallBack = function() { var failCallBack = function () {
isFunction(receiver.onFailure) && receiver.onFailure(); isFunction(receiver.onFailure) && receiver.onFailure();
}; };
var messageCallBack = function(data) { var messageCallBack = function (data) {
isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data); isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data);
}; };
messageCallbackMap[this.peerPkgName] = messageCallBack; messageCallbackMap[this.peerPkgName] = messageCallBack;
var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE); var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action); var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr); var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) { if (resultObj.abilityResult == 1) {
successCallBack(); successCallBack();
console.info("registerReceiver success."); console.info("registerReceiver success.");
} else { } else {
failCallBack(); failCallBack();
console.error("registerReceiver failed."); console.error("registerReceiver failed.");
} }
}; };
/** /**
...@@ -604,36 +265,36 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -604,36 +265,36 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message) * @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message)
*/ */
P2pClient.prototype.registerReceiver2 = async function(receiver) { P2pClient.prototype.registerReceiver2 = async function(receiver) {
if (!receiver) { if (!receiver) {
return; return;
} }
var successCallBack = function() { var successCallBack = function () {
isFunction(receiver.onSuccess) && receiver.onSuccess(); isFunction(receiver.onSuccess) && receiver.onSuccess();
}; };
var failCallBack = function() { var failCallBack = function () {
isFunction(receiver.onFailure) && receiver.onFailure(); isFunction(receiver.onFailure) && receiver.onFailure();
}; };
var messageCallBack = function(data) { var messageCallBack = function (data) {
isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data); isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data);
}; };
messageCallbackMap2[this.peerPkgName] = messageCallBack; messageCallbackMap2[this.peerPkgName] = messageCallBack;
var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE); var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action); var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr); var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) { if (resultObj.abilityResult == 1) {
successCallBack(); successCallBack();
console.info("registerReceiver2 success."); console.info("registerReceiver2 success.");
} else { } else {
failCallBack(); failCallBack();
console.error("registerReceiver2 failed."); console.error("registerReceiver2 failed.");
} }
}; };
/** /**
...@@ -643,44 +304,44 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -643,44 +304,44 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param message 返回结果 * @param message 返回结果
*/ */
function handleReceivedMessage(message, that) { function handleReceivedMessage(message, that) {
if (!message) { if (!message) {
return; return;
}
if (message.messageType == "text") {
return message.abilityResult;
}
//返回文件内容,并保存至本地
if (message.messageType == "file") {
var fileName = message.fileName;
that.allMessage =
that.allMessage == undefined ? message.abilityResult : that.allMessage + message.abilityResult;
if (message.seqId && message.seqId != message.cnt) {
return;
} }
file.delete({ if (message.messageType == "text") {
uri: WearEngineConst.DELAY_FILEAPP_VALUE + fileName, return message.abilityResult;
success: function() { }
writeFile(fileName, that.allMessage);
that.allMessage = "";
},
fail: function(data, code) {
writeFile(fileName, that.allMessage);
that.allMessage = "";
}
});
var fileObj = { //返回文件内容,并保存至本地
isFileType: true, if (message.messageType == "file") {
name: WearEngineConst.DELAY_FILEAPP_VALUE + fileName, var fileName = message.fileName;
mode: "",
mode2: "" that.allMessage =
}; that.allMessage == undefined ? message.abilityResult : that.allMessage + message.abilityResult;
return fileObj; if (message.end != WearEngineConst.END_FLAG) {
} return;
}
file.delete({
uri: WearEngineConst.DELAY_FILEAPP_VALUE + fileName,
success: function () {
writeFile(fileName, that.allMessage);
that.allMessage = "";
},
fail: function (data, code) {
writeFile(fileName, that.allMessage);
that.allMessage = "";
}
});
var fileObj = {
isFileType: true,
name: WearEngineConst.DELAY_FILEAPP_VALUE + fileName,
mode: "",
mode2: ""
};
return fileObj;
}
} }
/** /**
...@@ -689,16 +350,16 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -689,16 +350,16 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param {*} fileContent 文件内容 * @param {*} fileContent 文件内容
*/ */
function writeFile(fileName, fileContent) { function writeFile(fileName, fileContent) {
file.writeArrayBuffer({ file.writeArrayBuffer({
uri: WearEngineConst.DELAY_FILEAPP_VALUE + fileName, uri: WearEngineConst.DELAY_FILEAPP_VALUE + fileName,
buffer: fileContent, buffer: fileContent,
success: function() { success: function () {
console.info("write Text to file success."); console.info("write Text to file success.");
}, },
fail: function(data, code) { fail: function (data, code) {
console.error("write Text to file failed. code: " + code + ", data: " + data); console.error("write Text to file failed. code: " + code + ", data: " + data);
} }
}); });
} }
/** /**
* 发送消息接口 * 发送消息接口
...@@ -707,117 +368,147 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -707,117 +368,147 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param sendCallback object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count) * @param sendCallback object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count)
*/ */
P2pClient.prototype.send = async function(message, sendCallback) { P2pClient.prototype.send = async function(message, sendCallback) {
if (!message || !sendCallback) { if (!message || !sendCallback) {
return; return;
} }
var successCallBack = function() {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
isFunction(sendCallback.onSuccess) && sendCallback.onSuccess(); var successCallBack = function () {
isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(successCode); var successCode = {
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("100%"); data: "ERROR_CODE_COMM_SUCCESS",
}; code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
var failCallBack = function() { isFunction(sendCallback.onSuccess) && sendCallback.onSuccess();
var failCode = { isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(successCode);
data: "ERROR_CODE_COMM_FAILED", isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("100%");
code: ErrorCode.MSG_ERROR_SEND_FAIL
}; };
isFunction(sendCallback.onFailure) && sendCallback.onFailure(); var failCallBack = function () {
isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(failCode); var failCode = {
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("0%"); data: "ERROR_CODE_COMM_FAILED",
}; code: ErrorCode.MSG_ERROR_SEND_FAIL
};
var progressCallBack = function(data) {
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress(data + "%");
};
// 0 代表文本消息类型 isFunction(sendCallback.onFailure) && sendCallback.onFailure();
if (message.getType() == MessageType.MESSAGE_TYPE_DATA) { isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(failCode);
var actionData = { isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("0%");
messageContent: message.getData()
}; };
var action = this.getRequestHeader(RequestCode.SENDMESSAGE_CODEVALUE, actionData); var progressCallBack = function (data) {
var resultStr = await FeatureAbility.callAbility(action); isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress(data + "%");
var resultObj = JSON.parse(resultStr); };
if (resultObj.abilityResult == ErrorCode.MSG_ERROR_SEND_SUCCESS) { // 0 代表文本消息类型
successCallBack(); if (message.getType() == MessageType.MESSAGE_TYPE_DATA) {
console.info("send message success."); var actionData = {
} else { messageContent: message.getData()
failCallBack(); };
console.error("send message failed.");
}
} else {
var sendFileInterval = globalThis.setInterval(() => {
if (message.getFile() && message.getFile().errorCode) {
globalThis.clearInterval(sendFileInterval);
failCallBack();
console.error("send file failed.");
return;
}
if (!message.getFile() || !message.getFile().fileName) { var action = this.getRequestHeader(RequestCode.SENDMESSAGE_CODEVALUE, actionData);
return; var resultStr = await FeatureAbility.callAbility(action);
} var resultObj = JSON.parse(resultStr);
globalThis.clearInterval(sendFileInterval);
var fileContent = message.getFile().fileContent;
var cnt = Math.floor(fileContent.length / WearEngineConst.MAX_TRANSFER_SIZE) + 1;
sendFilePart(0, cnt, fileContent, message.getFile().fileName, successCallBack, failCallBack, this); if (resultObj.abilityResult == ErrorCode.MSG_ERROR_SEND_SUCCESS) {
successCallBack();
console.info("send message success.");
} else {
failCallBack();
console.error("send message failed.");
}
} else {
var sendFileInterval = globalThis.setInterval(() => {
if (message.getFile() && message.getFile().errorCode) {
globalThis.clearInterval(sendFileInterval);
failCallBack();
console.error("send file failed.");
return;
}
progressCallbackMap[this.peerPkgName] = progressCallBack; if (!message.getFile() || !message.getFile().fileName) {
}, WearEngineConst.DELAY_TIME_VALUE); return;
} }
globalThis.clearInterval(sendFileInterval);
var fileContent = message.getFile().fileContent;
var cnt = Math.floor(fileContent.length / WearEngineConst.MAX_TRANSFER_SIZE) + 1;
sendFilePart(
0,
fileContent,
message.getFile().fileName,
successCallBack,
failCallBack,
0,
WearEngineConst.MAX_TRANSFER_SIZE,
this
);
progressCallbackMap[this.peerPkgName] = progressCallBack;
}, WearEngineConst.DELAY_TIME_VALUE);
}
}; };
/** /**
* 递归分段发送文件 * 递归分段发送文件
* @param {*} index 文件内容分段索引 * @param {*} index 文件内容分段索引
* @param {*} cnt 总分段数
* @param {*} fileContent 所有的文件内容 * @param {*} fileContent 所有的文件内容
* @param {*} fileName 文件名 * @param {*} fileName 文件名
* @param {*} successCallBack 成功后的回调 * @param {*} successCallBack 成功后的回调
* @param {*} failCallBack 失败后的回调 * @param {*} failCallBack 失败后的回调
* @param {*} hasSent 已经发送的文件大小
* @param {*} transferSize 分段大小
* @param {*} that this指代 * @param {*} that this指代
*/ */
function sendFilePart(index, cnt, fileContent, fileName, successCallBack, failCallBack, that) { function sendFilePart(index, fileContent, fileName, successCallBack, failCallBack, hasSent, transferSize, that) {
var actionData = { var actionData = {
messageContent: fileContent.substring( messageContent: fileContent.substring(hasSent, Math.min(hasSent + transferSize, fileContent.length)),
WearEngineConst.MAX_TRANSFER_SIZE * index, seqId: hasSent,
Math.min(WearEngineConst.MAX_TRANSFER_SIZE * (index + 1), fileContent.length) fileName,
), cnt: fileContent.length
seqId: index + 1, };
fileName,
cnt var action = that.getRequestHeader(RequestCode.SENDFILE_CODEVALUE, actionData);
}; FeatureAbility.callAbility(action).then(
resultStr => {
var action = that.getRequestHeader(RequestCode.SENDFILE_CODEVALUE, actionData); var resultObj = JSON.parse(resultStr);
FeatureAbility.callAbility(action).then( if (resultObj.abilityResult == WearEngineConst.FILE_TO_BE_CONTINUED) {
resultStr => { var newTransferSize = Math.min(WearEngineConst.MAX_TRANSFER_SIZE, transferSize * 2);
var resultObj = JSON.parse(resultStr); sendFilePart(
if (resultObj.abilityResult == WearEngineConst.FILE_TO_BE_CONTINUED) { index + 1,
sendFilePart(index + 1, cnt, fileContent, fileName, successCallBack, failCallBack, that); fileContent,
} else if (resultObj.abilityResult != ErrorCode.MSG_ERROR_SEND_SUCCESS) { fileName,
console.error("error:" + resultStr); successCallBack,
failCallBack(); failCallBack,
console.error("send file failed."); Math.min(hasSent + transferSize, fileContent.length),
} else if (index == cnt - 1) { newTransferSize,
successCallBack(); that
console.info("send file success."); );
} } else if (resultObj.abilityResult != ErrorCode.MSG_ERROR_SEND_SUCCESS) {
}, console.error("error:" + resultStr);
() => { if (resultObj.code == 2) {
failCallBack(); sendFilePart(
console.error("send file failed."); index,
} fileContent,
); fileName,
successCallBack,
failCallBack,
hasSent,
Math.floor(transferSize / 2),
that
);
} else {
failCallBack();
console.error("send file failed.");
}
} else if (hasSent == fileContent.length) {
successCallBack();
console.info("send file success.");
}
},
() => {
failCallBack();
console.error("send file failed.");
}
);
} }
/** /**
...@@ -826,17 +517,17 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -826,17 +517,17 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param receiver onSuccess() onFailure() * @param receiver onSuccess() onFailure()
*/ */
P2pClient.prototype.unregisterReceiver = async function(receiver) { P2pClient.prototype.unregisterReceiver = async function(receiver) {
var action = this.getRequestHeader(RequestCode.UNREGISTER_RECEIVER_CODEVALUE); var action = this.getRequestHeader(RequestCode.UNREGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action); var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr); var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) { if (resultObj.abilityResult == 1) {
isFunction(receiver.onSuccess) && receiver.onSuccess(); isFunction(receiver.onSuccess) && receiver.onSuccess();
console.info("unregisterReceiver success."); console.info("unregisterReceiver success.");
} else { } else {
isFunction(receiver.onFailure) && receiver.onFailure(); isFunction(receiver.onFailure) && receiver.onFailure();
console.error("unregisterReceiver failed."); console.error("unregisterReceiver failed.");
} }
}; };
/** /**
...@@ -846,32 +537,32 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -846,32 +537,32 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param actionData 请求参数 * @param actionData 请求参数
* @return action 对象 * @return action 对象
*/ */
P2pClient.prototype.getRequestHeader = function(code, actionData) { P2pClient.prototype.getRequestHeader = function (code, actionData) {
var destInfo = { var destInfo = {
dstPackageName: this.peerPkgName, dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint dstFingerPrint: this.peerFingerPrint
}; };
return { return {
bundleName: FeatureAbilityOption.BUNDLE_NAME, bundleName: FeatureAbilityOption.BUNDLE_NAME,
abilityName: FeatureAbilityOption.ABILITY_NAME, abilityName: FeatureAbilityOption.ABILITY_NAME,
abilityType: FeatureAbilityOption.ABILITY_TYPE, abilityType: FeatureAbilityOption.ABILITY_TYPE,
syncOption: FeatureAbilityOption.SYNCOPTION_TYPE, syncOption: FeatureAbilityOption.SYNCOPTION_TYPE,
messageCode: code, messageCode: code,
data: Object.assign({}, destInfo, actionData) data: Object.assign({}, destInfo, actionData)
}; };
}; };
return P2pClient; return P2pClient;
})(); })();
var Builder = (function () {
Builder = (function() {
var messageInfo; var messageInfo;
function Builder() {} function Builder() {
}
Builder.prototype.setDescription = function(description) { Builder.prototype.setDescription = function (description) {
this.messageInfo = description; this.messageInfo = description;
this.messageType = MessageType.MESSAGE_TYPE_DATA; this.messageType = MessageType.MESSAGE_TYPE_DATA;
}; };
/** /**
...@@ -879,59 +570,59 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -879,59 +570,59 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* *
* @param data ArrayBuffer File(暂时不支持) * @param data ArrayBuffer File(暂时不支持)
*/ */
Builder.prototype.setPayload = function(data) { Builder.prototype.setPayload = function (data) {
if (!data) { if (!data) {
return; return;
} }
if (typeof data == "object" && data.name) { if (typeof data == "object" && data.name) {
this.messageType = MessageType.MESSAGE_TYPE_FILE; this.messageType = MessageType.MESSAGE_TYPE_FILE;
return this.setFilePlayload(data); return this.setFilePlayload(data);
} else { } else {
this.messageType = MessageType.MESSAGE_TYPE_DATA; this.messageType = MessageType.MESSAGE_TYPE_DATA;
return this.setBufferPlayload(data); return this.setBufferPlayload(data);
} }
}; };
Builder.prototype.setBufferPlayload = function(data) { Builder.prototype.setBufferPlayload = function (data) {
this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data)); this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data));
}; };
Builder.prototype.setFilePlayload = function(data) { Builder.prototype.setFilePlayload = function (data) {
var that = this; var that = this;
if (isEmpty(data)) { if (isEmpty(data)) {
return; return;
} }
var fileInfoArray = data.name.split("/"); var fileInfoArray = data.name.split("/");
var fileName = fileInfoArray[fileInfoArray.length - 1]; var fileName = fileInfoArray[fileInfoArray.length - 1];
if (isEmpty(fileName)) { if (isEmpty(fileName)) {
return; return;
}
file.readArrayBuffer({
uri: data.name,
success: function(data) {
var fileInfo = {
fileContent: data.buffer,
fileName: fileName
};
that.messageInfo = fileInfo;
console.info("read text from file success.");
},
fail: function(data, code) {
var errorInfo = {
errorCode: code,
data
};
that.messageInfo = errorInfo;
console.info("read text from file failed, code: " + code + ", data: " + data);
} }
});
file.readArrayBuffer({
uri: data.name,
success: function (data) {
var fileInfo = {
fileContent: data.buffer,
fileName: fileName
};
that.messageInfo = fileInfo;
console.info("read text from file success.");
},
fail: function (data, code) {
var errorInfo = {
errorCode: code,
data
};
that.messageInfo = errorInfo;
console.info("read text from file failed, code: " + code + ", data: " + data);
}
});
}; };
Builder.prototype.setReceivedInfo = function(type, data) { Builder.prototype.setReceivedInfo = function (type, data) {
this.messageType = type; this.messageType = type;
this.messageInfo = data; this.messageInfo = data;
}; };
/** /**
...@@ -940,12 +631,12 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -940,12 +631,12 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* @param obj obj parameter * @param obj obj parameter
*/ */
function isEmpty(obj) { function isEmpty(obj) {
return typeof obj == "undefined" || obj == null || obj == "" || obj == " "; return typeof obj == "undefined" || obj == null || obj == "" || obj == " ";
} }
return Builder; return Builder;
})(); })();
}
/** /**
* 文件格式类型 * 文件格式类型
...@@ -953,48 +644,50 @@ if (typeof globalThis == "undefined" || globalThis.isLite) { ...@@ -953,48 +644,50 @@ if (typeof globalThis == "undefined" || globalThis.isLite) {
* mode: 'text' or 'binary' * mode: 'text' or 'binary'
* mode2: 'R', 'W', 'RW' * mode2: 'R', 'W', 'RW'
*/ */
var File = (function() { var File = (function () {
var name; var name;
var mode; var mode;
var mode2; var mode2;
function File() {} function File() {
}
return File; return File;
})(); })();
var Message = (function() { var Message = (function () {
var builder = new Builder(); var builder = new Builder();
function Message() {} function Message() {
Message.prototype.describeContents = function() {
return this.builder.messageInfo;
};
/**
* 获取传送时的信息
*/
Message.prototype.getData = function() {
return this.builder.messageInfo;
};
Message.prototype.getDescription = function() {
return this.builder.messageInfo;
};
/**
* 获取文件信息
*/
Message.prototype.getFile = function() {
if (this.builder.messageType == MessageType.MESSAGE_TYPE_FILE) {
return globalThis.isLite ? JSON.parse(this.builder.messageInfo) : this.builder.messageInfo;
} }
return null;
}; Message.prototype.describeContents = function () {
/** return this.builder.messageInfo;
* 获取传输数据类型 0 string,1 File };
*/ /**
Message.prototype.getType = function() { * 获取传送时的信息
return this.builder.messageType; */
}; Message.prototype.getData = function () {
return Message; return this.builder.messageInfo;
};
Message.prototype.getDescription = function () {
return this.builder.messageInfo;
};
/**
* 获取文件信息
*/
Message.prototype.getFile = function () {
if (this.builder.messageType == MessageType.MESSAGE_TYPE_FILE) {
return this.builder.messageInfo;
}
return null;
};
/**
* 获取传输数据类型 0 string,1 File
*/
Message.prototype.getType = function () {
return this.builder.messageType;
};
return Message;
})(); })();
export { P2pClient, Message, Builder }; export {P2pClient, Message, Builder};
{
"string": [
{
"name": "app_name",
"value": "Fit健身"
}
]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment