Commit 7ffe7ac4 authored by Sky's avatar Sky

~

parent 93ab5b42
...@@ -13,7 +13,7 @@ ohos { ...@@ -13,7 +13,7 @@ ohos {
signAlg 'SHA256withECDSA' signAlg 'SHA256withECDSA'
} }
} }
compileSdkVersion 3 compileSdkVersion 4
defaultConfig { defaultConfig {
compatibleSdkVersion 3 compatibleSdkVersion 3
} }
...@@ -30,7 +30,7 @@ buildscript { ...@@ -30,7 +30,7 @@ buildscript {
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'com.huawei.ohos:hap:2.0.0.6' classpath 'com.huawei.ohos:hap:2.4.1.4'
} }
} }
......
...@@ -6,9 +6,9 @@ ohos { ...@@ -6,9 +6,9 @@ ohos {
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/com.company.fit.proDebug.p7b')
signAlg 'SHA256withECDSA' signAlg 'SHA256withECDSA'
keyPassword '0000001B9E576AD11A22A05641A642CA17ED844BB71D8027C1ACF79F928F7C1EA950008D8C70ADDF7E8429' keyPassword '0000001B17F8F53E0CF14D52675968C4FD60AA48E6580B4EEEE4AE8348FA556850E01CC92EEA6DE834CA36'
keyAlias 'huawei_watch_overseas Release' keyAlias 'huawei_watch_overseas Release'
storePassword '0000001B3F89F001102D6FF1A0BB38E371027272283910D107D7F11A763F26295938F1A4E704A7F054C552' storePassword '0000001B16A4C8B18003852BF6E890B38F6D624C8314D7E55CE2FD87CBC3F2C9E2DA9403C977F0C988ABAE'
storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12') storeFile file('D:/HuaweiWatchClient/huawei_watch_overseas.p12')
} }
release { release {
...@@ -21,7 +21,8 @@ ohos { ...@@ -21,7 +21,8 @@ ohos {
certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_release.cer') certpath file('D:/HuaweiWatchClient/com.company.fit.overseas_release.cer')
} }
} }
compileSdkVersion 3 mergeJsSrc true
compileSdkVersion 4
defaultConfig { defaultConfig {
compatibleSdkVersion 3 compatibleSdkVersion 3
} }
......
...@@ -2,18 +2,19 @@ ...@@ -2,18 +2,19 @@
"app": { "app": {
"bundleName": "com.company.fit", "bundleName": "com.company.fit",
"version": { "version": {
"code": 15, "code": 20,
"name": "1.0.1" "name": "1.0.2"
}, },
"apiVersion": { "apiVersion": {
"compatible": 3, "compatible": 3,
"target": 3 "target": 4
} }
}, },
"deviceConfig": {}, "deviceConfig": {},
"module": { "module": {
"deviceType": [ "deviceType": [
"liteWearable" "liteWearable",
"wearable"
], ],
"abilities": [ "abilities": [
{ {
......
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Version: 5.0.1.301
* Description: wearEngine SDK
*/
import wearengine from "@system.wearengine";
var P2pClient = (function () {
var peerPkgName;
var peerFingerPrint;
var version;
function P2pClient(context) {
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: "2",
});
} catch(error) {
jsSdk.version = 0;
console.log("service sdk version is too low" + error.message);
}
}
/**
* 设置手机应用的packageName
* peerPkgName: string
*/
P2pClient.prototype.setPeerPkgName = function (peerPkgName) {
this.peerPkgName = peerPkgName;
};
/**
* 设置手机侧指纹信息
* 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: 208,
};
return obj;
}
this.peerFingerPrint = fingerPrint;
var successCallBack = function () {
console.log("fingerPrint setup succeeded");
};
var failCallBack = function () {
console.log("fingerPrint setup 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_EXIT",
code: 205,
};
var successCallBack = function () {
pingCallback.onSuccess();
pingCallback.onPingResult(successCode);
};
var notInstallCode = {
data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIT",
code: 204,
};
var failCode = {
data: "ERROR_CODE_P2P_OTHER_ERROR",
code: 203,
};
var failCallBack = function (data, code) {
if (!data && !code) {
pingCallback.onFailure();
pingCallback.onPingResult(notInstallCode);
} else {
pingCallback.onFailure();
pingCallback.onPingResult(failCode);
}
};
FeatureAbility.detect({
bundleName: this.peerPkgName,
success: successCallBack,
fail: failCallBack,
});
};
/**
* 注册消息监听接口
* receiver:object:onSuccess(),onFailure(),onReceiveMessage(message)
*/
P2pClient.prototype.registerReceiver = function (receiver) {
if (!receiver) {
return;
}
var successCallBack = function (data) {
receiver.onSuccess();
if (data) {
if (data.isFileType) {
var fileObj = {
isFileType: true,
name: data.file,
mode: "",
mode2: "",
};
receiver.onReceiveMessage(fileObj);
} else {
receiver.onReceiveMessage(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: 207,
};
sendCallback.onSuccess();
sendCallback.onSendResult(successCode);
sendCallback.onSendProgress(100 + "%");
};
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) {
var failCode = {
data: errorMessage,
code: 206,
};
sendCallback.onFailure();
sendCallback.onSendResult(failCode);
};
var progressCallBack = function (data) {
sendCallback.onSendProgress(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();
};
return P2pClient;
})();
/**
* 文件格式
* name: file name with path
* mode: 'text' or 'binary'
* mode2: 'R', 'W', 'RW'
*/
var File = (function () {
var name;
var mode;
var mode2;
function File() {}
})();
var Builder = (function () {
var messageInfo;
function Builder(context) {}
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;
})();
var Message = (function () {
var builder = new Builder();
function Message(context) {}
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 == 1) {
return JSON.parse(this.builder.messageInfo);
}
return null;
};
/**
* 获取传输数据类型
* 0 string
* 1 File
*/
Message.prototype.getType = function () {
return this.builder.messageType;
};
return Message;
})();
export {
P2pClient,
Message,
Builder
};
import brightness from '@system.brightness' //保持屏幕常亮 import brightness from '@system.brightness' //保持屏幕常亮
import app from '@system.app' //右滑退出 import app from '@system.app' //右滑退出
import router from '@system.router' //页面跳转 import router from '@system.router' //页面跳转
import {P2pClient} from '../wearengine'
// 步骤1:创建点对点通信对象
var p2pClient = new P2pClient();
export default { export default {
data: { data: {
...@@ -31,7 +35,10 @@ export default { ...@@ -31,7 +35,10 @@ export default {
}, },
onDestroy() { onDestroy() {
//取消接收手机侧第三方应用发过来的消息 //取消接收手机侧第三方应用发过来的消息
FeatureAbility.unsubscribeMsg(); p2pClient.unregisterReceiver({
onSuccess: function () {
},
});
}, },
start(msg) { start(msg) {
let _this = this; let _this = this;
...@@ -52,13 +59,19 @@ export default { ...@@ -52,13 +59,19 @@ export default {
*/ */
getMsg() { getMsg() {
let _this = this; let _this = this;
FeatureAbility.subscribeMsg({ // 步骤4:接收手机侧第三方应用发过来的简短消息或文件
success: function (data) { var receiver = {
_this.start(JSON.parse(data.message)); onSuccess: function () {
// 处理注册接收手机侧简短消息或文件成功的回调函数
}, },
fail: function (data, code) { onFailure: function () {
} // 处理注册接收手机侧简短消息或文件失败的回调函数
}); },
onReceiveMessage: function (data) {
_this.start(JSON.parse(data));
},
}
p2pClient.registerReceiver(receiver);
}, },
/** /**
......
...@@ -4,8 +4,13 @@ import brightness from '@system.brightness' //保持屏幕常亮 ...@@ -4,8 +4,13 @@ import brightness from '@system.brightness' //保持屏幕常亮
import app from '@system.app' //右滑退出 import app from '@system.app' //右滑退出
import router from '@system.router' //页面跳转 import router from '@system.router' //页面跳转
import storage from '@system.storage' //本地数据 import storage from '@system.storage' //本地数据
import {P2pClient, Message, Builder} from '../wearengine'
var timer; var timer;
// 步骤1:创建点对点通信对象
var p2pClient = new P2pClient();
var builderClient = new Builder();
var sendMessage = new Message();
export default { export default {
data: { data: {
...@@ -31,6 +36,9 @@ export default { ...@@ -31,6 +36,9 @@ export default {
isFirstInit: true, //是否是第一次初始化事件 isFirstInit: true, //是否是第一次初始化事件
showPrivacy: true, //显示隐私权限页面 showPrivacy: true, //显示隐私权限页面
}, },
onInit() {
p2pClient.setPeerPkgName("com.sportq.fit");
},
onReady() { onReady() {
let _this = this; let _this = this;
//获取本地隐私权限标识 //获取本地隐私权限标识
...@@ -102,7 +110,10 @@ export default { ...@@ -102,7 +110,10 @@ export default {
}); });
this.quit(); this.quit();
//取消接收手机侧第三方应用发过来的消息 //取消接收手机侧第三方应用发过来的消息
FeatureAbility.unsubscribeMsg(); p2pClient.unregisterReceiver({
onSuccess: function () {
},
});
}, },
start(msg) { start(msg) {
let _this = this; let _this = this;
...@@ -323,16 +334,16 @@ export default { ...@@ -323,16 +334,16 @@ export default {
*/ */
checkInstall() { checkInstall() {
let _this = this; let _this = this;
FeatureAbility.detect({ p2pClient.ping({
bundleName: 'com.sportq.fit', onSuccess: function () {
success: function () { console.log('ping success.');
//已安装
}, },
fail: function (data, code) { onFailure: function () {
if (!data && !code) { //未安装 _this.page = "99";
_this.page = "99"; _this.isJumpLoginPage = false;
_this.isJumpLoginPage = false; },
} onPingResult: function (resultCode) {
console.log(resultCode.data + resultCode.code);
}, },
}); });
}, },
...@@ -344,19 +355,26 @@ export default { ...@@ -344,19 +355,26 @@ export default {
sendMsg(obj) { sendMsg(obj) {
let _this = this; let _this = this;
_this.sendFlg = true; _this.sendFlg = true;
FeatureAbility.sendMsg({ // 步骤4:发送简短消息到手机侧对应的第三方应用
deviceId: 'remote', builderClient.setDescription(JSON.stringify(obj));
bundleName: 'com.sportq.fit', sendMessage.builder = builderClient;
message: JSON.stringify(obj), // 定义回调函数
success: function () { var sendCallback = {
onSuccess: function () {
_this.sendFlg = false; _this.sendFlg = false;
console.log('sendMsg success.');
}, },
fail: function (data, code) { onFailure: function () {
_this.sendFlg = false; _this.sendFlg = false;
console.log('handing fail, message: ' + data + ', code: ' + code); },
} onSendResult: function (resultCode) {
}); // send任务执行结束后返回的错误码和信息进行处理
console.log(resultCode.data + resultCode.code);
},
}
if (sendMessage != null && sendCallback != null) {
p2pClient.send(sendMessage, sendCallback);
}
;
}, },
/** /**
...@@ -364,15 +382,23 @@ export default { ...@@ -364,15 +382,23 @@ export default {
*/ */
sendHeartRateMsg(obj) { sendHeartRateMsg(obj) {
let _this = this; let _this = this;
FeatureAbility.sendMsg({ // 步骤4:发送简短消息到手机侧对应的第三方应用
deviceId: 'remote', builderClient.setDescription(JSON.stringify(obj));
bundleName: 'com.sportq.fit', sendMessage.builder = builderClient;
message: JSON.stringify(obj), // 定义回调函数
success: function () { var sendCallback = {
onSuccess: function () {
}, },
fail: function (data, code) { onFailure: function () {
} },
}); onSendResult: function (resultCode) {
console.log(resultCode.data + resultCode.code);
},
}
if (sendMessage != null && sendCallback != null) {
p2pClient.send(sendMessage, sendCallback);
}
;
}, },
/** /**
...@@ -394,13 +420,19 @@ export default { ...@@ -394,13 +420,19 @@ export default {
*/ */
getMsg() { getMsg() {
let _this = this; let _this = this;
FeatureAbility.subscribeMsg({ // 步骤4:接收手机侧第三方应用发过来的简短消息或文件
success: function (data) { var receiver = {
_this.start(JSON.parse(data.message)); onSuccess: function () {
// 处理注册接收手机侧简短消息或文件成功的回调函数
}, },
fail: function (data, code) { onFailure: function () {
} // 处理注册接收手机侧简短消息或文件失败的回调函数
}); },
onReceiveMessage: function (data) {
_this.start(JSON.parse(data));
},
}
p2pClient.registerReceiver(receiver);
} }
, ,
...@@ -523,7 +555,10 @@ export default { ...@@ -523,7 +555,10 @@ export default {
this.progress = "", //进度条 this.progress = "", //进度条
this.countdownT = "", // 倒计时 this.countdownT = "", // 倒计时
//取消接收手机侧第三方应用发过来的消息 //取消接收手机侧第三方应用发过来的消息
FeatureAbility.unsubscribeMsg(); p2pClient.unregisterReceiver({
onSuccess: function () {
},
});
sensor.unsubscribeHeartRate() //取消监听心率 sensor.unsubscribeHeartRate() //取消监听心率
}, },
......
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
*/
import wearengine from "@system.wearengine";
var P2pClient;
var Builder;
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 = {
BUNDLE_NAME: "com.huawei.watch.kit.hiwearability", // 设置AA侧服务应用包名称
ABILITY_NAME: "com.huawei.watch.kit.hiwearability.HiWearServiceAbility", // 设置AA侧指定service名称
ABILITY_TYPE: 0, // 设置AA侧指定请求服务类型, abilityType: 0-Ability; 1-Internal Ability
SYNCOPTION_TYPE: 0 // 设置AA侧请求方式(Ace框架,目前Ability方式,只支持Sync同步方式), 0-Sync; 1-Async
};
var RequestCode = {
INIT_CODEVALUE: 1000, // 初始化请求码
REGISTER_RECEIVER_CODEVALUE: 1001, // 注册接收请求码
UNREGISTER_RECEIVER_CODEVALUE: 1002, // 取消注册接收请求码
PING_CODEVALUE: 1003, // PING探测请求码
SENDMESSAGE_CODEVALUE: 1004, // 发文本消息请求码
SENDFILE_CODEVALUE: 1005, // 发文件消息请求码
SUBSCRIBE_ABILITY_CODEVALUE: 1006, // 通道消息订阅
UNSUBSCRIBE_ABILITY_CODEVALUE: 1007 // 通道消息取消订阅
};
var WearEngineConst = {
DELAY_INIT_TIME_VALUE: 500, // 初始化延时默认值
DELAY_TIME_VALUE: 1000, // 消息发送延时默认值
DELAY_FILEAPP_VALUE: "internal://app/", // 三方应用默认文件存储路径
DEFAULT_EMPTY_VALUE: "", // 默认空字符串
MAX_TRANSFER_SIZE: 1024, // 分段发送文件时,每段的大小
FILE_TO_BE_CONTINUED: 1 // 需要继续发送文件的返回码
};
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 // 文件消息
};
var isFunction = obj => {
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
var WEARENGINE_SERVICE_VISION_303 = 303;
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 peerFingerPrint;
var allMessage = "";
// 包名 -> 对应的消息接收回调
var messageCallbackMap = {};
// 包名 -> 对应的消息接收回调 (对应registerReceiver2接口)
var messageCallbackMap2 = {};
// 包名 -> 对应的进度接收回调
var progressCallbackMap = {};
var initSuccess = false;
function P2pClient() {
this.setPeerFingerPrint(WearEngineConst.DEFAULT_EMPTY_VALUE, true);
this.subscribeAbilityEvent();
}
/**
* 建立消息通道
*/
P2pClient.prototype.subscribeAbilityEvent = async function() {
var action = this.getRequestHeader(RequestCode.SUBSCRIBE_ABILITY_CODEVALUE);
var that = this;
await FeatureAbility.subscribeAbilityEvent(action, function(callbackData) {
var callbackJson = JSON.parse(callbackData);
var receivedMessage = JSON.parse(JSON.stringify(callbackJson.data));
// 接收消息或文件
if (receivedMessage.messageType != "progress") {
var msgOrFileObj = handleReceivedMessage(receivedMessage, that);
if (!msgOrFileObj) {
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]) {
var progressCallback = progressCallbackMap[receivedMessage.peerPackageName];
progressCallback(JSON.stringify(receivedMessage.abilityResult));
}
}
});
};
/**
* 设置手机应用的packageName
*
* @param peerPkgName 目标应用包名称
*/
P2pClient.prototype.setPeerPkgName = async function(peerPkgName) {
if (!peerPkgName) {
return;
}
this.peerPkgName = peerPkgName;
};
/**
* 设置手机侧指纹信息并初始化
*
* @param fingerPrint 目前应用指纹参数
*/
P2pClient.prototype.setPeerFingerPrint = async function(fingerPrint, isInit) {
var initInterval = globalThis.setInterval(() => {
if (!isInit && !initSuccess) {
return;
}
globalThis.clearInterval(initInterval);
this.peerFingerPrint = fingerPrint;
var actionData = {
dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint
};
var action = this.getRequestHeader(RequestCode.INIT_CODEVALUE, actionData);
if (!fingerPrint) {
FeatureAbility.callAbility(action).then(resultStr => {
var resultObj = JSON.parse(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);
if (resultObj.abilityResult == 1) {
console.info("setPeerFingerPrint success.");
} else {
console.error("setPeerFingerPrint failed.");
}
},
() => {
console.error("setPeerFingerPrint failed.");
}
);
}, WearEngineConst.DELAY_INIT_TIME_VALUE);
}
}, WearEngineConst.DELAY_INIT_TIME_VALUE);
};
/**
* 检测对端设备侧是否已经安装指定应用
*
* @param pingCallback object:onSuccess(),onFailure(),onPingResult(resultCode)
*/
P2pClient.prototype.ping = async function(pingCallback) {
var successCode = {
data: "ERROR_CODE_P2P_PHONE_APP_EXIST",
code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING
};
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
};
var successCallBack = function() {
isFunction(pingCallback.onSuccess) && pingCallback.onSuccess();
isFunction(pingCallback.onPingResult) && pingCallback.onPingResult(successCode);
};
var failCallBack = function(code) {
if (code == ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST) {
isFunction(pingCallback.onFailure) && pingCallback.onFailure();
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 {
failCallBack(resultObj.abilityResult);
console.error("ping failed.");
}
};
/**
* 注册消息监听接口
*
* @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message)
*/
P2pClient.prototype.registerReceiver = async function(receiver) {
if (!receiver) {
return;
}
var successCallBack = function() {
isFunction(receiver.onSuccess) && receiver.onSuccess();
};
var failCallBack = function() {
isFunction(receiver.onFailure) && receiver.onFailure();
};
var messageCallBack = function(data) {
isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data);
};
messageCallbackMap[this.peerPkgName] = messageCallBack;
var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) {
successCallBack();
console.info("registerReceiver success.");
} else {
failCallBack();
console.error("registerReceiver failed.");
}
};
/**
* 注册消息监听接口
*
* @param receiver object:onSuccess(),onFailure(),onReceiveMessage(message)
*/
P2pClient.prototype.registerReceiver2 = async function(receiver) {
if (!receiver) {
return;
}
var successCallBack = function() {
isFunction(receiver.onSuccess) && receiver.onSuccess();
};
var failCallBack = function() {
isFunction(receiver.onFailure) && receiver.onFailure();
};
var messageCallBack = function(data) {
isFunction(receiver.onReceiveMessage) && receiver.onReceiveMessage(data);
};
messageCallbackMap2[this.peerPkgName] = messageCallBack;
var action = this.getRequestHeader(RequestCode.REGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) {
successCallBack();
console.info("registerReceiver2 success.");
} else {
failCallBack();
console.error("registerReceiver2 failed.");
}
};
/**
* 保存消息处理
* 为了和运动表保持一致,如果是收到消息,返回消息;如果是收到文件,返回fileObj
*
* @param message 返回结果
*/
function handleReceivedMessage(message, that) {
if (!message) {
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({
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;
}
}
/**
* 将文件内容写入文件
* @param {*} fileName 文件名
* @param {*} fileContent 文件内容
*/
function writeFile(fileName, fileContent) {
file.writeArrayBuffer({
uri: WearEngineConst.DELAY_FILEAPP_VALUE + fileName,
buffer: fileContent,
success: function() {
console.info("write Text to file success.");
},
fail: function(data, code) {
console.error("write Text to file failed. code: " + code + ", data: " + data);
}
});
}
/**
* 发送消息接口
*
* @param message Message
* @param sendCallback object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count)
*/
P2pClient.prototype.send = async function(message, sendCallback) {
if (!message || !sendCallback) {
return;
}
var successCallBack = function() {
var successCode = {
data: "ERROR_CODE_COMM_SUCCESS",
code: ErrorCode.MSG_ERROR_SEND_SUCCESS
};
isFunction(sendCallback.onSuccess) && sendCallback.onSuccess();
isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(successCode);
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("100%");
};
var failCallBack = function() {
var failCode = {
data: "ERROR_CODE_COMM_FAILED",
code: ErrorCode.MSG_ERROR_SEND_FAIL
};
isFunction(sendCallback.onFailure) && sendCallback.onFailure();
isFunction(sendCallback.onSendResult) && sendCallback.onSendResult(failCode);
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress("0%");
};
var progressCallBack = function(data) {
isFunction(sendCallback.onSendProgress) && sendCallback.onSendProgress(data + "%");
};
// 0 代表文本消息类型
if (message.getType() == MessageType.MESSAGE_TYPE_DATA) {
var actionData = {
messageContent: message.getData()
};
var action = this.getRequestHeader(RequestCode.SENDMESSAGE_CODEVALUE, actionData);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
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;
}
if (!message.getFile() || !message.getFile().fileName) {
return;
}
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);
progressCallbackMap[this.peerPkgName] = progressCallBack;
}, WearEngineConst.DELAY_TIME_VALUE);
}
};
/**
* 递归分段发送文件
* @param {*} index 文件内容分段索引
* @param {*} cnt 总分段数
* @param {*} fileContent 所有的文件内容
* @param {*} fileName 文件名
* @param {*} successCallBack 成功后的回调
* @param {*} failCallBack 失败后的回调
* @param {*} that this指代
*/
function sendFilePart(index, cnt, fileContent, fileName, successCallBack, failCallBack, that) {
var actionData = {
messageContent: fileContent.substring(
WearEngineConst.MAX_TRANSFER_SIZE * index,
Math.min(WearEngineConst.MAX_TRANSFER_SIZE * (index + 1), fileContent.length)
),
seqId: index + 1,
fileName,
cnt
};
var action = that.getRequestHeader(RequestCode.SENDFILE_CODEVALUE, actionData);
FeatureAbility.callAbility(action).then(
resultStr => {
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == WearEngineConst.FILE_TO_BE_CONTINUED) {
sendFilePart(index + 1, cnt, fileContent, fileName, successCallBack, failCallBack, that);
} else if (resultObj.abilityResult != ErrorCode.MSG_ERROR_SEND_SUCCESS) {
console.error("error:" + resultStr);
failCallBack();
console.error("send file failed.");
} else if (index == cnt - 1) {
successCallBack();
console.info("send file success.");
}
},
() => {
failCallBack();
console.error("send file failed.");
}
);
}
/**
* 注销监听接口
*
* @param receiver onSuccess() onFailure()
*/
P2pClient.prototype.unregisterReceiver = async function(receiver) {
var action = this.getRequestHeader(RequestCode.UNREGISTER_RECEIVER_CODEVALUE);
var resultStr = await FeatureAbility.callAbility(action);
var resultObj = JSON.parse(resultStr);
if (resultObj.abilityResult == 1) {
isFunction(receiver.onSuccess) && receiver.onSuccess();
console.info("unregisterReceiver success.");
} else {
isFunction(receiver.onFailure) && receiver.onFailure();
console.error("unregisterReceiver failed.");
}
};
/**
* 请求消息头参数
*
* @param code 请求码
* @param actionData 请求参数
* @return action 对象
*/
P2pClient.prototype.getRequestHeader = function(code, actionData) {
var destInfo = {
dstPackageName: this.peerPkgName,
dstFingerPrint: this.peerFingerPrint
};
return {
bundleName: FeatureAbilityOption.BUNDLE_NAME,
abilityName: FeatureAbilityOption.ABILITY_NAME,
abilityType: FeatureAbilityOption.ABILITY_TYPE,
syncOption: FeatureAbilityOption.SYNCOPTION_TYPE,
messageCode: code,
data: Object.assign({}, destInfo, actionData)
};
};
return P2pClient;
})();
Builder = (function() {
var messageInfo;
function Builder() {}
Builder.prototype.setDescription = function(description) {
this.messageInfo = description;
this.messageType = MessageType.MESSAGE_TYPE_DATA;
};
/**
* 设置messge信息(两种格式任选其一 0 string,1 File)
*
* @param data ArrayBuffer File(暂时不支持)
*/
Builder.prototype.setPayload = function(data) {
if (!data) {
return;
}
if (typeof data == "object" && data.name) {
this.messageType = MessageType.MESSAGE_TYPE_FILE;
return this.setFilePlayload(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.setFilePlayload = function(data) {
var that = this;
if (isEmpty(data)) {
return;
}
var fileInfoArray = data.name.split("/");
var fileName = fileInfoArray[fileInfoArray.length - 1];
if (isEmpty(fileName)) {
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);
}
});
};
Builder.prototype.setReceivedInfo = function(type, data) {
this.messageType = type;
this.messageInfo = data;
};
/**
* 判断参数是否为空
*
* @param obj obj parameter
*/
function isEmpty(obj) {
return typeof obj == "undefined" || obj == null || obj == "" || obj == " ";
}
return Builder;
})();
}
/**
* 文件格式类型
* name: file name with path
* mode: 'text' or 'binary'
* mode2: 'R', 'W', 'RW'
*/
var File = (function() {
var name;
var mode;
var mode2;
function File() {}
return File;
})();
var Message = (function() {
var builder = new Builder();
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;
};
/**
* 获取传输数据类型 0 string,1 File
*/
Message.prototype.getType = function() {
return this.builder.messageType;
};
return Message;
})();
export { P2pClient, Message, Builder };
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
File added
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