diff --git a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.d.ts b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.d.ts index 635ab7dae4c334917f3c2dbab09a6c9303f47ed7..349d4581d249923164a4698614cb7ff7ea12fa28 100644 --- a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.d.ts +++ b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.d.ts @@ -13,6 +13,10 @@ * limitations under the License. */ +declare enum BleNotifyType { + NOTIFICATION = "NOTIFICATION", + INDICATION = "INDICATION" +} interface BaseRequest { success?: (any?: any) => void; fail?: (code: number, error: Error) => void; @@ -44,6 +48,7 @@ interface DeviceInfo { interface StartBleDeviceDiscoveryData { uuidServices?: string[]; reportInterval?: number; + timeoutInMillis?: number; isAllowDuplicatesKey?: boolean; } interface DiscoveredBleDevice { @@ -104,7 +109,7 @@ interface BleBaseOperation { characteristicId: string; } interface NotifyBleCharacteristicValueInfo extends BleBaseOperation { - enableNotify: boolean; + notifyType: BleNotifyType; } interface WifiStatusInfo { isConnected: boolean; @@ -137,6 +142,12 @@ interface HttpRequestData { interface HttpResponseData { responseData: string; errorMessage: string; + message: string; + httpCode: number; + headers: string; +} +interface HttpRequestRequest extends BaseRequest, HttpRequestData { + success: (info?: HttpResponseData) => void; } interface StartBleDiscoveryRequest extends BaseRequest, StartBleDeviceDiscoveryData { } @@ -181,35 +192,36 @@ interface HttpRequestRequest extends BaseRequest, HttpRequestData { declare class HealthEcologyOperator { private static getRequestAction; private static processOperation; - static openBluetoothAdapter(object?: BaseRequest): Promise; - static closeBluetoothAdapter(object?: BaseRequest): Promise; - static startBleDevicesDiscovery(object?: StartBleDiscoveryRequest): Promise; - static stopBleDevicesDiscovery(object?: BaseRequest): Promise; + static openBluetoothAdapter(request?: BaseRequest): Promise; + static closeBluetoothAdapter(request?: BaseRequest): Promise; + static startBleDevicesDiscovery(request?: StartBleDiscoveryRequest): Promise; + static stopBleDevicesDiscovery(request?: BaseRequest): Promise; static onBleDevicesFound(callback: (dataObj: DiscoveredBleDevice[]) => void): Promise; static onBluetoothAdapterStateChange(callback: (adapterState: BluetoothAdapterStateInfo) => void): Promise; - static getBluetoothAdapterState(object: GetBluetoothAdapterStateRequest): Promise; - static createBleConnection(object?: CreateBleConnectionRequest): Promise; - static closeBleConnection(object?: CloseBleConnectionRequest): Promise; + static getBluetoothAdapterState(request: GetBluetoothAdapterStateRequest): Promise; + static createBleConnection(request?: CreateBleConnectionRequest): Promise; + static closeBleConnection(request?: CloseBleConnectionRequest): Promise; static onBleConnectionStateChange(callback: (dataObj: BleConnectionStateInfo) => void): Promise; static onBleServiceDiscovered(callback: (dataObj: DiscoveredBleDeviceService) => void): Promise; static onBleMtuUpdated(callback: (dataObj: MtuUpdateData) => void): Promise; - static readBleCharacteristicValue(object?: BleCharacteristicValueRequest): Promise; + static readBleCharacteristicValue(request?: BleCharacteristicValueRequest): Promise; static onBleCharacteristicValueRead(callback: (characteristicValueRead: BleCharacteristicValueInfo) => void): Promise; - static writeBleCharacteristicValue(object?: BleCharacteristicValueRequest): Promise; + static writeBleCharacteristicValue(request?: BleCharacteristicValueRequest): Promise; static onBleCharacteristicValueWrite(callback: (characteristicValueWrite: BleCharacteristicValueInfo) => void): Promise; - static notifyBleCharacteristicValueChange(object?: NotifyBleCharacteristicValueRequest): Promise; + static notifyBleCharacteristicValueChange(request?: NotifyBleCharacteristicValueRequest): Promise; static onBleCharacteristicValueChange(callback: (characteristicValueChange: BleCharacteristicValueInfo) => void): Promise; - static setBleMTU(object?: SetBleMTURequest): Promise; - static setConnectionPriority(object: SetPriorityRequest): Promise; - static getBleDeviceServices(object: DeviceServiceRequest): Promise; - static getBleDeviceCharacteristics(object: BleDeviceCharacteristicRequest): Promise; - static getCurrentConnectedDevices(object?: GetConnectedDevicesRequest): Promise; - static getWifiStatus(object?: WifiStatusInfoRequest): Promise; - static startWifiScan(object?: BaseRequest): Promise; - static getConnectedWifiInformation(object?: ConnectedWifiInfoRequest): Promise; - static getScannedWifiInformation(object?: ScannedWifiInfoRequest): Promise; - static pairDevice(object: PairDeviceRequest): Promise; + static setBleMTU(request?: SetBleMTURequest): Promise; + static setConnectionPriority(request: SetPriorityRequest): Promise; + static getBleDeviceServices(request: DeviceServiceRequest): Promise; + static getBleDeviceCharacteristics(request: BleDeviceCharacteristicRequest): Promise; + static getCurrentConnectedDevices(request?: GetConnectedDevicesRequest): Promise; + static getWifiStatus(request?: WifiStatusInfoRequest): Promise; + static startWifiScan(request?: BaseRequest): Promise; + static getConnectedWifiInformation(request?: ConnectedWifiInfoRequest): Promise; + static getScannedWifiInformation(request?: ScannedWifiInfoRequest): Promise; + static pairDevice(request: PairDeviceRequest): Promise; static onHttpResponse(callback: (responseData: HttpResponseData) => void): Promise; - static processHttpRequest(object: HttpRequestRequest): Promise; + static processHttpRequest(request: HttpRequestRequest): Promise; + static syncProcessHttpRequest(request: HttpRequestRequest): Promise; } -export default HealthEcologyOperator; +export { HealthEcologyOperator, BleNotifyType }; diff --git a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.js b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.js index 1db7c5e414a179bc0f31b89c2b32da3dc0db7727..7160a227d27c85c726dbed1f88d66f5c45eb3277 100644 --- a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.js +++ b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/HealthEcologyOperator.js @@ -24,6 +24,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", { value: true }); +exports.BleNotifyType = exports.HealthEcologyOperator = void 0; //For Java const BUNDLE_NAME = 'com.huawei.healthecology'; const ABILITY_NAME = 'com.huawei.healthecology.client.JsFaClient'; @@ -63,6 +64,7 @@ var RequestCode; RequestCode[RequestCode["GET_SCANNED_WIFI_INFORMATION"] = 1033] = "GET_SCANNED_WIFI_INFORMATION"; RequestCode[RequestCode["HTTP_NETWORK_REQUEST"] = 2001] = "HTTP_NETWORK_REQUEST"; RequestCode[RequestCode["HTTP_NETWORK_ON_RESPONSE"] = 2002] = "HTTP_NETWORK_ON_RESPONSE"; + RequestCode[RequestCode["HTTP_SYNC_REQUEST"] = 2003] = "HTTP_SYNC_REQUEST"; })(RequestCode || (RequestCode = {})); var ResponseCode; (function (ResponseCode) { @@ -86,6 +88,12 @@ var ResponseCode; ResponseCode[ResponseCode["BLUETOOTH_DEVICE_NOT_FOUND"] = 12006] = "BLUETOOTH_DEVICE_NOT_FOUND"; ResponseCode[ResponseCode["WIFI_NOT_INITIALIZED"] = 13004] = "WIFI_NOT_INITIALIZED"; })(ResponseCode || (ResponseCode = {})); +var BleNotifyType; +(function (BleNotifyType) { + BleNotifyType["NOTIFICATION"] = "NOTIFICATION"; + BleNotifyType["INDICATION"] = "INDICATION"; +})(BleNotifyType || (BleNotifyType = {})); +exports.BleNotifyType = BleNotifyType; class HealthEcologyOperator { static getRequestAction(requestCode) { let requestAction = { @@ -108,7 +116,7 @@ class HealthEcologyOperator { } else { let error = { - name: "Operation[" + action.messageCode + ']: Falied', + name: "Operation[" + action.messageCode + ']: Failed', message: ResponseCode[response.code] === undefined ? "Unknown Error." : ResponseCode[response.code], }; request.fail(response.code, error); @@ -119,34 +127,35 @@ class HealthEcologyOperator { } }); } - static openBluetoothAdapter(object) { + static openBluetoothAdapter(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.OPEN_BLUETOOTH_ADAPTER); - this.processOperation(object, action); + this.processOperation(request, action); }); } - static closeBluetoothAdapter(object) { + static closeBluetoothAdapter(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.CLOSE_BLUETOOTH_ADAPTER); - this.processOperation(object, action); + this.processOperation(request, action); }); } - static startBleDevicesDiscovery(object) { + static startBleDevicesDiscovery(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.START_BLE_DEVICES_DISCOVERY); let actionData = { - uuidServices: object.uuidServices != undefined ? object.uuidServices : [], - reportInterval: object.reportInterval != undefined ? object.reportInterval : 0, - isAllowDuplicatesKey: object.isAllowDuplicatesKey != undefined ? object.isAllowDuplicatesKey : false, + uuidServices: request.uuidServices != undefined ? request.uuidServices : [], + reportInterval: request.reportInterval != undefined ? request.reportInterval : 0, + timeoutInMillis: request.timeoutInMillis != undefined ? request.timeoutInMillis : 10000, + isAllowDuplicatesKey: request.isAllowDuplicatesKey != undefined ? request.isAllowDuplicatesKey : false, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } - static stopBleDevicesDiscovery(object) { + static stopBleDevicesDiscovery(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.STOP_BLE_DEVICES_DISCOVERY); - this.processOperation(object, action); + this.processOperation(request, action); }); } static onBleDevicesFound(callback) { @@ -171,49 +180,49 @@ class HealthEcologyOperator { console.debug(TAG + resultStr); }); } - static getBluetoothAdapterState(object) { + static getBluetoothAdapterState(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_BLUETOOTH_ADAPTER_STATE); let resultStr = yield FeatureAbility.callAbility(action); let resultObj = JSON.parse(resultStr); - console.debug("Bluetooth adapter state result is :" + resultObj.code); + console.error("Bluetooth adapter state result is :" + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "Get bluetoothAdapterState Error", message: ResponseCode[resultObj.code] === undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static createBleConnection(object) { + static createBleConnection(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.CREATE_BLE_CONNECTION); let actionData = { - deviceId: object.deviceId.toUpperCase(), - isAutoConnect: object.isAutoConnect != undefined ? object.isAutoConnect : false, + deviceId: request.deviceId, + isAutoConnect: request.isAutoConnect != undefined ? request.isAutoConnect : false, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } - static closeBleConnection(object) { + static closeBleConnection(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.CLOSE_BLE_CONNECTION); let actionData = { - deviceId: object.deviceId.toUpperCase(), + deviceId: request.deviceId, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } static onBleConnectionStateChange(callback) { @@ -245,16 +254,16 @@ class HealthEcologyOperator { }); }); } - static readBleCharacteristicValue(object) { + static readBleCharacteristicValue(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.READ_BLE_CHARACTERISTIC_VALUE); let actionData = { - deviceId: object.deviceId.toUpperCase(), - serviceId: object.serviceId, - characteristicId: object.characteristicId + deviceId: request.deviceId, + serviceId: request.serviceId, + characteristicId: request.characteristicId }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } static onBleCharacteristicValueRead(callback) { @@ -268,17 +277,17 @@ class HealthEcologyOperator { console.debug(TAG + 'Read Ble characteristic value result is:' + resultStr); }); } - static writeBleCharacteristicValue(object) { + static writeBleCharacteristicValue(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.WRITE_BLE_CHARACTERISTIC_VALUE); let actionData = { - deviceId: object.deviceId, - serviceId: object.serviceId, - characteristicId: object.characteristicId, - characteristicData: object.characteristicData, + deviceId: request.deviceId, + serviceId: request.serviceId, + characteristicId: request.characteristicId, + characteristicData: request.characteristicData, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } static onBleCharacteristicValueWrite(callback) { @@ -292,17 +301,17 @@ class HealthEcologyOperator { console.debug(TAG + 'Write Ble characteristic value result is:' + resultStr); }); } - static notifyBleCharacteristicValueChange(object) { + static notifyBleCharacteristicValueChange(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE); let actionData = { - deviceId: object.deviceId, - serviceId: object.serviceId, - characteristicId: object.characteristicId, - enableNotify: object.enableNotify, + deviceId: request.deviceId, + serviceId: request.serviceId, + characteristicId: request.characteristicId, + notifyType: request.notifyType, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } static onBleCharacteristicValueChange(callback) { @@ -316,24 +325,24 @@ class HealthEcologyOperator { console.debug(TAG + resultStr); }); } - static setBleMTU(object) { + static setBleMTU(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.SET_BLE_MTU); let actionData = { - deviceId: object.deviceId, - mtuValue: object.mtuValue, + deviceId: request.deviceId, + mtuValue: request.mtuValue, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } - static setConnectionPriority(object) { + static setConnectionPriority(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.SET_BLE_CONNECTION_PRIORITY); let actionData = { - deviceId: object.deviceId, - connectionPriority: object.connectionPriority, + deviceId: request.deviceId, + connectionPriority: request.connectionPriority, }; action.data = actionData; let resultString = yield FeatureAbility.callAbility(action); @@ -341,53 +350,53 @@ class HealthEcologyOperator { console.debug(TAG + "Connection priority result is : " + resultResponse.code); if (resultResponse.code == ResponseCode.OPERATION_SUCCESS) { let response = JSON.parse(resultResponse.data); - object.success(response); + request.success(response); } else { let error = { name: "SET CONNECTION PRIORITY ERROR", message: RequestCode[resultResponse.code] == undefined ? "Unknown Error." : RequestCode[resultResponse.code] }; - object.fail(resultResponse.code, error); + request.fail(resultResponse.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getBleDeviceServices(object) { + static getBleDeviceServices(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_DEVICE_SERVICES); - action.data = object.deviceId; + action.data = request.deviceId; let resultStr = yield FeatureAbility.callAbility(action); let resultObj = JSON.parse(resultStr); console.debug(TAG + "Ble device services result is : " + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET DEVICE SERVICES ERROR", message: RequestCode[resultObj.code] == undefined ? "Unknown Error." : RequestCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getBleDeviceCharacteristics(object) { + static getBleDeviceCharacteristics(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_DEVICE_CHARACTERISTICS); let actionData = { - deviceId: object.deviceId, - serviceId: object.serviceId, + deviceId: request.deviceId, + serviceId: request.serviceId, }; action.data = actionData; let resultStr = yield FeatureAbility.callAbility(action); @@ -395,22 +404,22 @@ class HealthEcologyOperator { console.debug(TAG + "Ble device characteristics result is : " + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET DEVICE CHARACTERISTICS ERROR", message: RequestCode[resultObj.code] == undefined ? "Unknown Error." : RequestCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getCurrentConnectedDevices(object) { + static getCurrentConnectedDevices(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_CONNECTED_BLE_DEVICES); @@ -419,22 +428,22 @@ class HealthEcologyOperator { console.debug(TAG + 'Current connected devices result is: ' + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET CONNECTED DEVICES Error", message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getWifiStatus(object) { + static getWifiStatus(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_WIFI_STATUS); @@ -443,22 +452,22 @@ class HealthEcologyOperator { console.debug(TAG + 'Wifi status result is: ' + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET WIFI STATUS Error", message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static startWifiScan(object) { + static startWifiScan(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.START_WIFI_SCAN); @@ -466,22 +475,22 @@ class HealthEcologyOperator { let resultObj = JSON.parse(resultStr); console.debug(TAG + 'Wifi scan result is:' + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { - object.success(); + request.success(); } else { let error = { name: "START WIFI SCAN Error", message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getConnectedWifiInformation(object) { + static getConnectedWifiInformation(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_CONNECTED_WIFI_INFORMATION); @@ -490,22 +499,22 @@ class HealthEcologyOperator { console.debug(TAG + 'Connected Wifi information result is: ' + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET CONNECTED WIFI INFORMATION Error", message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static getScannedWifiInformation(object) { + static getScannedWifiInformation(request) { return __awaiter(this, void 0, void 0, function* () { try { let action = this.getRequestAction(RequestCode.GET_SCANNED_WIFI_INFORMATION); @@ -514,26 +523,26 @@ class HealthEcologyOperator { console.debug(TAG + 'Scanned Wifi information result is:' + resultObj.code); if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { let stateObj = JSON.parse(resultObj.data); - object.success(stateObj); + request.success(stateObj); } else { let error = { name: "GET SCANNED WIFI INFORMATION Error", message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] }; - object.fail(resultObj.code, error); + request.fail(resultObj.code, error); } } catch (error) { - object.fail(undefined, error); + request.fail(undefined, error); } }); } - static pairDevice(object) { + static pairDevice(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.PAIR_BLUETOOTH_DEVICE); - action.data = object.deviceId; - this.processOperation(object, action); + action.data = request.deviceId; + this.processOperation(request, action); }); } static onHttpResponse(callback) { @@ -547,18 +556,49 @@ class HealthEcologyOperator { console.debug(TAG + resultStr); }); } - static processHttpRequest(object) { + static processHttpRequest(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.HTTP_NETWORK_REQUEST); let actionData = { - httpUrl: object.httpUrl, - requestData: object.requestData, - requestHeaders: object.requestHeaders, - requestType: object.requestType + httpUrl: request.httpUrl, + requestData: request.requestData, + requestHeaders: request.requestHeaders, + requestType: request.requestType }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); + }); + } + static syncProcessHttpRequest(request) { + return __awaiter(this, void 0, void 0, function* () { + try { + let action = this.getRequestAction(RequestCode.HTTP_SYNC_REQUEST); + let actionData = { + httpUrl: request.httpUrl, + requestData: request.requestData, + requestHeaders: request.requestHeaders, + requestType: request.requestType + }; + action.data = actionData; + let resultStr = yield FeatureAbility.callAbility(action); + let resultObj = JSON.parse(resultStr); + console.debug(TAG + 'Http request result is:' + resultObj.code); + if (resultObj.code == ResponseCode.OPERATION_SUCCESS) { + let stateObj = JSON.parse(resultObj.data); + request.success(stateObj); + } + else { + let error = { + name: "Http Error", + message: ResponseCode[resultObj.code] == undefined ? "Unknown Error." : ResponseCode[resultObj.code] + }; + request.fail(resultObj.code, error); + } + } + catch (error) { + request.fail(undefined, error); + } }); } } -exports.default = HealthEcologyOperator; +exports.HealthEcologyOperator = HealthEcologyOperator; diff --git a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/package.json b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/package.json index a3af3cfe7518369dc2a9c27b88272ee10cb29464..e4ae187a136bf8ed5ca0dc08ba8ccf01a8d9a2ce 100644 --- a/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/package.json +++ b/OpenHealthEcologyFA/@health-ecology-kit/hek-operator/package.json @@ -1,36 +1,44 @@ { - "_from": "@health-ecology-kit/hek-operator@1.2.1", - "_id": "@health-ecology-kit/hek-operator@1.2.1", + "_args": [ + [ + "@health-ecology-kit/hek-operator@1.4.0-alpha", + "D:\\fa-demo\\fa-master\\HealthEcologyFaCentral\\entry" + ] + ], + "_from": "@health-ecology-kit/hek-operator@1.4.0-alpha", + "_id": "@health-ecology-kit/hek-operator@1.4.0-alpha", "_inBundle": false, - "_integrity": "sha512-KBYIiJfN4crIm7dh+36o/qeSKeoLv5gEgdequATj88yo/kYPJf1rKjyqvDok1+n1uVNOEEYjz7lnr6y/r7hihw==", + "_integrity": "sha512-dB2HiVdkPAqiUUFzdr9sTVxvvHuIfh0TcHHQqfn3oESgafygmrM2E1hoXl0oVLddOCCWoAAr58+VxBIu7OK08Q==", "_location": "/@health-ecology-kit/hek-operator", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, - "raw": "@health-ecology-kit/hek-operator@1.2.1", + "raw": "@health-ecology-kit/hek-operator@1.4.0-alpha", "name": "@health-ecology-kit/hek-operator", "escapedName": "@health-ecology-kit%2fhek-operator", "scope": "@health-ecology-kit", - "rawSpec": "1.2.1", + "rawSpec": "1.4.0-alpha", "saveSpec": null, - "fetchSpec": "1.2.1" + "fetchSpec": "1.4.0-alpha" }, "_requiredBy": [ - "#USER", "/" ], - "_shasum": "0c67ad9eba97eb27b317b064d1479bd7fee25407", - "_spec": "@health-ecology-kit/hek-operator@1.2.1", + "_resolved": "http://npm.cloudartifact.dgg.dragon.tools.huawei.com/artifactory/api/npm/npm-WearEcology/@health-ecology-kit/hek-operator/-/@health-ecology-kit/hek-operator-1.4.0-alpha.tgz", + "_spec": "1.4.0-alpha", + "_where": "D:\\fa-demo\\fa-master\\HealthEcologyFaCentral\\entry", "author": "", - "bundleDependencies": false, - "deprecated": false, - "description": "To have multi devices support", + "description": "Health Ecology Operator", "license": "ISC", "main": "HealthEcologyOperator.js", "name": "@health-ecology-kit/hek-operator", + "publishConfig": { + "registry": "http://npm.cloudartifact.dgg.dragon.tools.huawei.com/artifactory/api/npm/npm-WearEcology/", + "_auth": "d2VhcmVjb2xvZ3ljaTpXZWFyRWNvbG9neUNJQDIwMjE=" + }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, - "version": "1.2.1" + "version": "1.4.0-alpha" } diff --git a/OpenHealthEcologyFA/OhosKit/build.gradle b/OpenHealthEcologyFA/OhosKit/build.gradle index 013ba7ca27d7e3e6005138940c40b58e2ad8c851..8cc8a7a11fbf56571b1f2f3e381a9b5d1456e539 100644 --- a/OpenHealthEcologyFA/OhosKit/build.gradle +++ b/OpenHealthEcologyFA/OhosKit/build.gradle @@ -13,7 +13,7 @@ dependencies { } ohosTestImplementation 'org.hamcrest:hamcrest-core:2.2' - api 'org.projectlombok:lombok:1.18.12' + compileOnly 'org.projectlombok:lombok:1.18.12' annotationProcessor 'org.projectlombok:lombok:1.18.12' implementation 'org.jetbrains:annotations:17.0.0' diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/api/HttpClient.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/api/HttpClient.java index 2404fed1bc4751916e774820ad3937a6e8f56d11..2cfeaa490a30e61b33cd2b1635f76b60914270f7 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/api/HttpClient.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/api/HttpClient.java @@ -18,6 +18,8 @@ package com.huawei.healthecology.api; import com.huawei.healthecology.data.http.HttpResponseCallback; import com.huawei.healthecology.data.http.HttpResponseCode; import com.huawei.healthecology.data.http.KitHttpRequest; +import com.huawei.healthecology.data.http.response.HttpRequestResponseData; + import org.jetbrains.annotations.NotNull; /** @@ -39,4 +41,12 @@ public interface HttpClient { * @return A response code presents the operation result */ HttpResponseCode processHttpRequest(@NotNull KitHttpRequest httpRequest); + + /** + * To process the httpRequest sync + * + * @param httpRequest The request action + * @return A response data presents the operation result + */ + HttpRequestResponseData syncProcessHttpRequest(@NotNull KitHttpRequest httpRequest); } diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/constants.js b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/data/BleNotifyType.java similarity index 81% rename from OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/constants.js rename to OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/data/BleNotifyType.java index fd4be44cce8fc77c9a4bd259dc177d67df4d64a8..7d73938369b03784e20da46f0220fc07f14c6fd9 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/constants.js +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/data/BleNotifyType.java @@ -13,9 +13,14 @@ * limitations under the License. */ -const data = { - FLAG_ABILITY_NEW_MISSION: 268435456, - FLAG_NOT_OHOS_COMPONENT: 16, -} -export default data; \ No newline at end of file +package com.huawei.healthecology.data.ble.data; + +/** + * Ble notify type + */ +public enum BleNotifyType { + NOTIFICATION, + + INDICATION, +} diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/request/CharacteristicNotifyRequest.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/request/CharacteristicNotifyRequest.java index da49f6097c9457cb56979509720d5dff6e0bde7f..8bdb2456e12128ec393640c50e83d82b7c5c7185 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/request/CharacteristicNotifyRequest.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/ble/request/CharacteristicNotifyRequest.java @@ -15,6 +15,8 @@ package com.huawei.healthecology.data.ble.request; +import com.huawei.healthecology.data.ble.data.BleNotifyType; + import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; @@ -32,5 +34,5 @@ public class CharacteristicNotifyRequest { private final String characteristicId; - private final boolean enableNotify; + private final BleNotifyType notifyType; } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpRequestType.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpRequestType.java index 0a633a52f31780eb34f61c83fa3ee6cfffb24f59..a5b224d133ae554e89a0016c1008fa74507202cb 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpRequestType.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpRequestType.java @@ -19,6 +19,7 @@ import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Optional; @@ -32,7 +33,7 @@ public enum HttpRequestType { */ REQUEST_GET { @Override - public Optional buildRequest(@Nullable String requestBody, Request.Builder requestBuilder) { + public Optional buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) { return Optional.of(requestBuilder.get().build()); } }, @@ -42,7 +43,7 @@ public enum HttpRequestType { */ REQUEST_POST { @Override - public Optional buildRequest(@Nullable String requestBody, Request.Builder requestBuilder) { + public Optional buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) { return Optional.ofNullable(requestBody) .map(data -> RequestBody.create(data, JSON)) .map(body -> requestBuilder.post(body).build()); @@ -54,7 +55,7 @@ public enum HttpRequestType { */ REQUEST_PUT { @Override - public Optional buildRequest(@Nullable String requestBody, Request.Builder requestBuilder) { + public Optional buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) { return Optional.ofNullable(requestBody) .map(data -> RequestBody.create(data, JSON)) .map(body -> requestBuilder.put(body).build()); @@ -66,7 +67,7 @@ public enum HttpRequestType { */ REQUEST_DELETE { @Override - public Optional buildRequest(@Nullable String requestBody, Request.Builder requestBuilder) { + public Optional buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) { return Optional.of(Optional.ofNullable(requestBody) .map(data -> RequestBody.create(data, JSON)) .map(body -> requestBuilder.delete(body).build()) @@ -84,5 +85,6 @@ public enum HttpRequestType { * @param requestBuilder The builder with url value inserted * @return A Request */ - public abstract Optional buildRequest(@Nullable String requestBody, Request.Builder requestBuilder); + public abstract Optional buildRequest( + @Nullable String requestBody, @NotNull Request.Builder requestBuilder); } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpResponseData.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpResponseData.java index faf25d6adb78f2482140fd09e9ec12a067e34a44..41b286f6a88d7bb34cca82965a5f1646f5aaf165 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpResponseData.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/HttpResponseData.java @@ -15,11 +15,11 @@ package com.huawei.healthecology.data.http; +import org.jetbrains.annotations.Nullable; + import lombok.Builder; import lombok.Getter; -import org.jetbrains.annotations.Nullable; - /** * Http response data */ @@ -31,4 +31,10 @@ public class HttpResponseData { @Nullable private final String errorMessage; + + private final String httpMessage; + + private final int httpCode; + + private final String httpHeaders; } diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/response/QueryUniqueIdResponse.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/response/HttpRequestResponseData.java similarity index 51% rename from OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/response/QueryUniqueIdResponse.java rename to OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/response/HttpRequestResponseData.java index 5f8f4af0ffb500857f287a9286e37ab7d2695027..07d392ddb79c4a156c201cac66230b6480f04339 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/response/QueryUniqueIdResponse.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/data/http/response/HttpRequestResponseData.java @@ -13,26 +13,35 @@ * limitations under the License. */ -package com.huawei.health.ecology.fa.central.response; +package com.huawei.healthecology.data.http.response; import com.huawei.healthecology.data.HealthEcologyResponse; +import com.huawei.healthecology.data.http.HttpResponseCode; +import com.huawei.healthecology.data.http.HttpResponseData; + import lombok.Builder; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; /** - * The response code for uniqueId query operations + * Http request response */ -public class QueryUniqueIdResponse extends HealthEcologyResponse { - private final String uniqueId; +@Setter +@Getter +@ToString +public class HttpRequestResponseData extends HealthEcologyResponse { + private final HttpResponseData httpResponseData; /** - * Query uniqueId response + * Http request response * - * @param responseCode Query response code - * @param uniqueId The uniqueId + * @param responseCode http operate response code + * @param httpResponseData http response data */ @Builder - public QueryUniqueIdResponse(CentralResponseCode responseCode, String uniqueId) { + public HttpRequestResponseData(HttpResponseCode responseCode, HttpResponseData httpResponseData) { super(responseCode); - this.uniqueId = uniqueId; + this.httpResponseData = httpResponseData; } } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/H5RemoteOperator.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/H5RemoteOperator.java index 366cefe77e47d808aac77618a1404aaabca1f433..d7fe35f6d17828cfc49741160ea571e40636fcbf 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/H5RemoteOperator.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/H5RemoteOperator.java @@ -22,6 +22,8 @@ import com.huawei.healthecology.log.LogUtil; import lombok.Builder; import ohos.agp.components.webengine.WebView; +import java.util.Optional; + /** * The remote operator for H5/Web view */ @@ -38,11 +40,12 @@ public class H5RemoteOperator implements PlatformCallback { @Override public void onResponse(String response) { OptionalX.ofNullable(webViewInstance) - .ifPresent(webView -> webView.getContext() - .getUITaskDispatcher() - .asyncDispatch(() -> webView.executeJs( - buildResponse(response), - message -> LogUtil.debug(TAG, message)))) + .ifPresent(webView -> Optional.ofNullable(webView.getContext()) + .ifPresent(context -> context + .getUITaskDispatcher() + .asyncDispatch(() -> webView.executeJs( + buildResponse(response), + message -> LogUtil.debug(TAG, message))))) .ifNotPresent(() -> LogUtil.debug(TAG, buildResponse(response))); } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/JsRemoteOperator.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/JsRemoteOperator.java index 6888fadf401e1d4d30a21c8c7f17c3a9ae78e293..e04a35f96267709c124affa00acd1be0d3734409 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/JsRemoteOperator.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/JsRemoteOperator.java @@ -64,10 +64,13 @@ public class JsRemoteOperator implements PlatformCallback { public void onResponse(String response) { if (!Optional.ofNullable(remoteObject).isPresent()) { LogUtil.error(TAG, "Fail to send back the data, empty remote object"); + return; } MessageParcel replyData = MessageParcel.obtain(); MessageOption replyOption = new MessageOption(); MessageParcel replyParcel = MessageParcel.obtain(); + replyData.setCapacity(Integer.MAX_VALUE); + replyParcel.setCapacity(Integer.MAX_VALUE); try { replyData.writeString(response); remoteObject.sendRequest(BleResponseCode.OPERATION_SUCCESS.getValue(), replyData, replyParcel, replyOption); diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/PlatformOperationCode.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/PlatformOperationCode.java index 36571de06efb9a2a68946b07a382d824bea78b96..a04d076d2fa73418ec74836008569cae39172b75 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/PlatformOperationCode.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/operator/PlatformOperationCode.java @@ -519,6 +519,23 @@ public enum PlatformOperationCode { .responseCode(BleResponseCode.OPERATION_SUCCESS) .build()); } + }, + + HTTP_SYNC_REQUEST(2_003) { + @Override + Optional toProcessRequest(PlatformOperation operation) { + return ClientModule.getHttpProcessor() + .map(processor -> operation.getRawRequest() + .flatMap(rawRequest -> ClientModule.getParser() + .flatMap(parser -> parser.mapTo(rawRequest, KitHttpRequest.class))) + .map(processor::syncProcessHttpRequest) + .map(response -> PlatformResponse.builder() + .responseValue(response) + .build()) + .orElse(PlatformResponse.builder() + .responseCode(HttpResponseCode.OPERATION_FAILED) + .build())); + } }; private final int operationValue; diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleCentralProcessor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleCentralProcessor.java index 9f1b32f588e5d8e6852bb0c0bb2229e6b81958b2..950460b6b8045025fdc6381e513f4f77064e6d65 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleCentralProcessor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleCentralProcessor.java @@ -20,6 +20,7 @@ import com.huawei.healthecology.data.ble.callback.AdapterStateChangeCallback; import com.huawei.healthecology.data.ble.callback.BleDeviceFoundCallback; import com.huawei.healthecology.data.ble.data.BleConnectionState; import com.huawei.healthecology.data.ble.data.DiscoveredDeviceData; +import com.huawei.healthecology.data.ble.data.ScanFoundDevice; import com.huawei.healthecology.data.ble.request.BleDeviceDiscoverRequest; import com.huawei.healthecology.data.ble.response.BleResponseCode; import com.huawei.healthecology.data.ble.response.ConnectedDeviceResponse; @@ -30,7 +31,6 @@ import com.huawei.healthecology.data.utils.BluetoothProfileByteUtil; import com.huawei.healthecology.data.utils.CallbackProvider; import com.huawei.healthecology.data.utils.ConditionOperation; import com.huawei.healthecology.data.utils.StringUtils; -import com.huawei.healthecology.data.ble.data.ScanFoundDevice; import com.huawei.healthecology.log.LogUtil; import com.huawei.healthecology.subscriber.BluetoothAdapterStateSubscriber; @@ -103,6 +103,8 @@ public class BleCentralProcessor implements BleCentral, HealthEcologyProcessor { private Revocable deviceDiscoverRevocable; + private boolean isBleDiscovering = false; + @Builder(builderMethodName = "hiddenBuilder") private BleCentralProcessor(@NonNull Context context) { this.contextInstance = context; @@ -229,22 +231,30 @@ public class BleCentralProcessor implements BleCentral, HealthEcologyProcessor { dispatchDiscoverTimer(discoverTimeout); manager.startScan(Collections.emptyList()); repeatReportTask(reportInterval); + isBleDiscovering = true; return BleResponseCode.OPERATION_SUCCESS; }) .orElse(BleResponseCode.OPERATION_FAILED); } @Override - public BleResponseCode stopBleDevicesDiscovery() { - LogUtil.debug(TAG, "stopBleDevicesDiscovery..."); - Optional.ofNullable(scheduledTaskFuture).ifPresent(future -> future.cancel(true)); - this.reportScannedDevicesQueue.clear(); - return Optional.ofNullable(centralManager) - .map(manager -> { + public synchronized BleResponseCode stopBleDevicesDiscovery() { + if (isBleDiscovering) { + LogUtil.debug(TAG, "StopBleDevicesDiscovery..."); + Optional.ofNullable(deviceDiscoverRevocable).ifPresent(Revocable::revoke); + Optional.ofNullable(scheduledTaskFuture).ifPresent(future -> future.cancel(true)); + this.reportScannedDevicesQueue.clear(); + return Optional.ofNullable(centralManager) + .map(manager -> { manager.stopScan(); + isBleDiscovering = false; return BleResponseCode.OPERATION_SUCCESS; }) - .orElse(BleResponseCode.OPERATION_FAILED); + .orElse(BleResponseCode.OPERATION_FAILED); + } else { + LogUtil.debug(TAG, "Is not discovering."); + return BleResponseCode.OPERATION_SUCCESS; + } } @Override @@ -323,11 +333,10 @@ public class BleCentralProcessor implements BleCentral, HealthEcologyProcessor { } private void storeScannedDevices(BlePeripheralDevice device, List uuids, String serviceData, String rawData) { - long validUuids = uuids.stream() - .filter(uuid -> (dummyUuidFilterList.isEmpty() || dummyUuidFilterList.contains(uuid))) - .count(); - boolean isValidScanResult = (validUuids > 0) - && (device != null) + boolean isUuidValid = dummyUuidFilterList.isEmpty() || uuids.stream().anyMatch(dummyUuidFilterList::contains); + + boolean isValidScanResult = isUuidValid + && (Optional.ofNullable(device).map(BlePeripheralDevice::getDeviceAddr).isPresent()) && (isDuplicateReportEnabled || !totalScannedDevicesMap.containsKey(device.getDeviceAddr())); ConditionOperation.of(isValidScanResult) .ifExist(reportDevices -> { @@ -384,7 +393,6 @@ public class BleCentralProcessor implements BleCentral, HealthEcologyProcessor { Optional.ofNullable(deviceDiscoverRevocable).ifPresent(Revocable::revoke); deviceDiscoverRevocable = globalTaskDispatcher.delayDispatch(() -> Optional.ofNullable(deviceFoundCallbackProvider) - .filter(provide -> totalScannedDevicesMap.isEmpty()) .ifPresent(provider -> { provider.getAll().forEach(callback -> callback.onDeviceFound(Collections.emptyList())); this.stopBleDevicesDiscovery(); diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleGattProcessor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleGattProcessor.java index ac3e400f6b677009932cd39dd73b53cbb9a1b2d1..51a260eb9a7b75a0e9469601e4ed5767857feb75 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleGattProcessor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BleGattProcessor.java @@ -26,6 +26,7 @@ import com.huawei.healthecology.data.ble.data.BleCharacteristicData; import com.huawei.healthecology.data.ble.data.BleCharacteristicProperty; import com.huawei.healthecology.data.ble.data.BleConnectionPriority; import com.huawei.healthecology.data.ble.data.BleDescriptorData; +import com.huawei.healthecology.data.ble.data.BleNotifyType; import com.huawei.healthecology.data.ble.data.BleProfileUuid; import com.huawei.healthecology.data.ble.data.BleServiceData; import com.huawei.healthecology.data.ble.data.CharacteristicConstant; @@ -195,7 +196,7 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { @Override public BleResponseCode notifyBleCharacteristicValueChange(CharacteristicNotifyRequest request) { LogUtil.info(TAG, "notifyBleCharacteristicValueChange."); - int propertyFlag = request.isEnableNotify() + int propertyFlag = BleNotifyType.NOTIFICATION.equals(request.getNotifyType()) ? CharacteristicConstant.NOTIFY_PROPERTY.getValue() : CharacteristicConstant.INDICATE_PROPERTY.getValue(); Optional gattCharacteristic = getConnectedDeviceById(request.getDeviceId()) @@ -203,7 +204,7 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { return getConnectedDeviceById(request.getDeviceId()) .map(device -> gattCharacteristic .filter(characteristic -> (characteristic.getProperties() & propertyFlag) != 0) - .map(characteristic -> toEnableCharacteristicNotify(device, characteristic, request.isEnableNotify())) + .map(characteristic -> toEnableCharacteristicNotify(device, characteristic, request.getNotifyType())) .map(result -> result ? BleResponseCode.OPERATION_SUCCESS : BleResponseCode.SYSTEM_ERROR) .orElse(BleResponseCode.INVALID_SERVICE_OR_CHARACTERISTIC)) .orElse(BleResponseCode.NOT_INITIALIZED); @@ -272,7 +273,9 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { return getConnectedDeviceById(deviceId) .map(device -> device.getServices().stream()) .map(gattServiceStream -> gattServiceStream - .map(gattService -> BleServiceData.of(gattService.getUuid().toString(), gattService.isPrimary())) + .map(gattService -> Optional.ofNullable(gattService.getUuid()) + .map(uuid -> BleServiceData.of(uuid.toString(), gattService.isPrimary())) + .orElse(BleServiceData.of("", gattService.isPrimary()))) .collect(Collectors.toList())) .map(dataList -> DeviceServiceGetResponse.builder() .deviceId(deviceId) @@ -292,10 +295,12 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { .flatMap(device -> device.getService(UUID.fromString(request.getServiceId()))) .map(gattService -> gattService.getCharacteristics().stream()) .map(characteristicStream -> characteristicStream + .filter(characteristic -> Optional.ofNullable(characteristic.getUuid()).isPresent()) .map(characteristic -> BleCharacteristicData.builder() .characteristicId(characteristic.getUuid().toString()) .characteristicProperty(getProperty(characteristic)) - .build()).collect(Collectors.toList())) + .build()) + .collect(Collectors.toList())) .map(dataList -> DeviceCharacteristicGetResponse.builder() .dataList(dataList) .deviceId(request.getDeviceId()) @@ -326,7 +331,7 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { private Optional getConnectedDeviceById(@NonNull String deviceId) { return connectedDevices.stream() - .filter(item -> item.getDeviceAddr().equalsIgnoreCase(deviceId)) + .filter(item -> deviceId.equalsIgnoreCase(item.getDeviceAddr())) .findAny(); } @@ -358,9 +363,9 @@ public class BleGattProcessor implements BleGatt, HealthEcologyProcessor { } private boolean toEnableCharacteristicNotify(BlePeripheralDevice peripheralDevice, - GattCharacteristic gattCharacteristic, boolean isEnableNotify) { - LogUtil.info(TAG, "enableCharacteristicNotifyOrIndicate: isEnable = " + isEnableNotify); - byte[] descriptorValue = isEnableNotify + GattCharacteristic gattCharacteristic, BleNotifyType notifyType) { + LogUtil.info(TAG, "enableCharacteristicNotifyOrIndicate: notifyTpe = " + notifyType); + byte[] descriptorValue = BleNotifyType.NOTIFICATION.equals(notifyType) ? GattDescriptorConstants.getEnableNotificationValue() : GattDescriptorConstants.getEnableIndicationValue(); return Optional.ofNullable(peripheralDevice) diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BluetoothCentralProcessor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BluetoothCentralProcessor.java index 6e7e5f870c1c0a051d032e74882e2137627db9c3..99e8fc3dedc4be67a92af9aa8328aa5bb9a1d4aa 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BluetoothCentralProcessor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/BluetoothCentralProcessor.java @@ -124,6 +124,7 @@ public class BluetoothCentralProcessor implements BluetoothCentral getPairedDevices() { return Optional.ofNullable(bluetoothHost) + .filter(host -> Optional.ofNullable(host.getPairedDevices()).isPresent()) .map(host -> host.getPairedDevices().stream()) .orElse(Stream.empty()); } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/GattEventMonitor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/GattEventMonitor.java index 640dcb04292ec7a2ec5e1e740b6c235874a46cd8..c6ca4b8bbb8a69b7b1c2f7c78d2f7d7749daeaeb 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/GattEventMonitor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/GattEventMonitor.java @@ -42,6 +42,8 @@ import ohos.bluetooth.ble.BlePeripheralCallback; import ohos.bluetooth.ble.BlePeripheralDevice; import ohos.bluetooth.ble.GattCharacteristic; import ohos.bluetooth.ble.GattDescriptor; +import ohos.bluetooth.ble.GattService; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Optional; @@ -159,14 +161,13 @@ public class GattEventMonitor { private void onConnectionStateChangeEvent(@NonNull BlePeripheralDevice blePeripheralDevice, int connectionState) { boolean isConnected = (connectionState == BluetoothProfileByteUtil.STATE_CONNECTED); LogUtil.info(TAG, "connectionStateChangeEvent isConnected = " + isConnected); + Optional.of(blePeripheralDevice) + .filter(device -> isConnected) + .map(BlePeripheralDevice::discoverServices); BleConnectionChangeCallback connectionChangeCallback = Optional.ofNullable(connectionChangeProvider) .flatMap(CallbackProvider::getLast) .orElse(null); - BleServiceDiscoveredCallback discoveredCallback = Optional.ofNullable(serviceDiscoveredProvider) - .flatMap(CallbackProvider::getLast) - .orElse(null); callbackDeviceConnection(blePeripheralDevice, connectionChangeCallback, isConnected); - callbackDeviceServicesDiscovered(blePeripheralDevice, discoveredCallback, isConnected); } private void onCharacteristicReadEvent(BlePeripheralDevice device, GattCharacteristic characteristic, int ret) { @@ -174,27 +175,42 @@ public class GattEventMonitor { ReadBleCharacteristicValueCallback readCallback = Optional.ofNullable(readCharacteristicProvider) .flatMap(CallbackProvider::getLast) .orElse(null); + String validServiceUuid = Optional.ofNullable(characteristic.getService()) + .map(GattService::getUuid) + .map(UUID::toString) + .orElse(""); + String validCharacteristicUuid = Optional.ofNullable(characteristic.getUuid()) + .map(UUID::toString) + .orElse(""); OptionalX.ofNullable(readCallback) .ifPresent(callback -> callback.onCharacteristicRead(CharacteristicChangeData.builder() .deviceId(device.getDeviceAddr()) - .characteristicId(characteristic.getUuid().toString()) - .serviceId(characteristic.getService().getUuid().toString()) + .serviceId(validServiceUuid) + .characteristicId(validCharacteristicUuid) .characteristicData(BluetoothProfileByteUtil.bytesToHexString(characteristic.getValue())).build())) .ifNotPresent(() -> LogUtil.debug(TAG, "ReadCharacteristicCallback is empty")); } - private void onCharacteristicWriteEvent(BlePeripheralDevice device, GattCharacteristic characteristic, int ret) { - LogUtil.info(TAG, "characteristicReadEvent ret = " + ret); + private void onCharacteristicWriteEvent(BlePeripheralDevice device, + @NotNull GattCharacteristic characteristic, int ret) { + LogUtil.info(TAG, "characteristicWriteEvent ret = " + ret); WriteBleCharacteristicValueCallback writeCallback = Optional.ofNullable(writeCharacteristicProvider) .flatMap(CallbackProvider::getLast) .orElse(null); + String validServiceUuid = Optional.ofNullable(characteristic.getService()) + .map(GattService::getUuid) + .map(UUID::toString) + .orElse(""); + String validCharacteristicUuid = Optional.ofNullable(characteristic.getUuid()) + .map(UUID::toString) + .orElse(""); OptionalX.ofNullable(writeCallback) .ifPresent(callback -> callback.onCharacteristicWrite(CharacteristicChangeData.builder() .deviceId(device.getDeviceAddr()) - .characteristicId(characteristic.getUuid().toString()) - .serviceId(characteristic.getService().getUuid().toString()) + .serviceId(validServiceUuid) + .characteristicId(validCharacteristicUuid) .characteristicData(BluetoothProfileByteUtil.bytesToHexString(characteristic.getValue())).build())) - .ifNotPresent(() -> LogUtil.debug(TAG, "ReadCharacteristicCallback is empty")); + .ifNotPresent(() -> LogUtil.debug(TAG, "WriteCharacteristicCallback is empty")); } private void onCharacteristicChangedEvent(BlePeripheralDevice device, GattCharacteristic characteristic) { @@ -257,19 +273,4 @@ public class GattEventMonitor { .ifNotPresent(() -> LogUtil.debug(TAG, "ConnectionStateChangeCallback with invalid device"))) .ifNotPresent(() -> LogUtil.debug(TAG, "ConnectionStateChangeCallback is empty")); } - - private void callbackDeviceServicesDiscovered(@NonNull BlePeripheralDevice blePeripheralDevice, - BleServiceDiscoveredCallback discoveredCallback, boolean isConnected) { - boolean isDiscoverSuccess = Optional.of(blePeripheralDevice) - .filter(device -> isConnected) - .map(BlePeripheralDevice::discoverServices) - .orElse(false); - String deviceId = Optional.of(blePeripheralDevice) - .map(BlePeripheralDevice::getDeviceAddr) - .orElse(null); - OptionalX.ofNullable(discoveredCallback) - .ifPresent(callback -> ConditionOperation.of(isDiscoverSuccess) - .ifNotExist(failed -> callback.onBleServiceDiscovered(BleServiceDiscoveryResult.of(deviceId, false)))) - .ifNotPresent(() -> LogUtil.debug(TAG, "discoveredCallbackCallback is empty")); - } } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/HttpClientProcessor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/HttpClientProcessor.java index 407dd7946d469d6c6bd3b3db608902116c5be04f..94c60652995ea90666f2e2d5619232069653f8c1 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/HttpClientProcessor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/HttpClientProcessor.java @@ -20,6 +20,7 @@ import com.huawei.healthecology.data.http.HttpResponseCallback; import com.huawei.healthecology.data.http.HttpResponseCode; import com.huawei.healthecology.data.http.HttpResponseData; import com.huawei.healthecology.data.http.KitHttpRequest; +import com.huawei.healthecology.data.http.response.HttpRequestResponseData; import com.huawei.healthecology.data.utils.CallbackProvider; import com.huawei.healthecology.json.JsonMapper; @@ -104,4 +105,44 @@ public class HttpClientProcessor implements HttpClient, HealthEcologyProcessor { callback.onResponse(HttpResponseData.builder().errorMessage(e.getMessage()).build()); } } + + @Override + public HttpRequestResponseData syncProcessHttpRequest(@NotNull KitHttpRequest httpRequest) { + Headers.Builder headerBuilder = new Headers.Builder(); + Optional.ofNullable(httpRequest.getRequestHeaders()) + .flatMap(jsonMapper::getJsonMap) + .ifPresent(map -> map.forEach(headerBuilder::add)); + Request.Builder requestBuilder = new Request.Builder() + .headers(headerBuilder.build()) + .url(httpRequest.getHttpUrl()); + return httpRequest.getRequestType() + .buildRequest(httpRequest.getRequestData(), requestBuilder) + .map(validRequest -> + HttpRequestResponseData.builder() + .responseCode(HttpResponseCode.OPERATION_SUCCESS) + .httpResponseData(syncProcessRequest(validRequest)) + .build()) + .orElse(HttpRequestResponseData.builder() + .responseCode(HttpResponseCode.OPERATION_FAILED) + .build()); + } + + private HttpResponseData syncProcessRequest(Request request) { + HttpResponseData httpResponseData; + try (Response response = httpClient.newCall(request).execute()) { + Optional body = Optional.of(response).map(Response::body); + String resultBody = (body.isPresent()) + ? body.get().string() + : EMPTY_RESPONSE_BODY; + httpResponseData = HttpResponseData.builder() + .httpHeaders(response.headers().toString()) + .httpCode(response.code()) + .httpMessage(response.message()) + .responseData(resultBody) + .build(); + } catch (IOException e) { + httpResponseData = HttpResponseData.builder().errorMessage(e.getMessage()).build(); + } + return httpResponseData; + } } diff --git a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/WifiDeviceProcessor.java b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/WifiDeviceProcessor.java index 4f9c18d7023861eee5edd78b2747e2e2339d9f13..05390438790ebc64992293cbfbe491b77e263c6f 100644 --- a/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/WifiDeviceProcessor.java +++ b/OpenHealthEcologyFA/OhosKit/src/main/java/com/huawei/healthecology/processor/WifiDeviceProcessor.java @@ -105,6 +105,7 @@ public class WifiDeviceProcessor implements WifiCentral, HealthEcologyProcessor public WifiConnectionResponse getConnectedInformation() { return Optional.ofNullable(wifiDevice) .flatMap(WifiDevice::getLinkedInfo) + .filter(linkedInfo -> Optional.ofNullable(linkedInfo.getConnState()).isPresent()) .map(linkedInfo -> WifiConnectionResponse.builder() .responseCode(WifiResponseCode.OPERATION_SUCCESS) .information(WifiConnectedInfo.of(linkedInfo.getSsid(), @@ -118,6 +119,7 @@ public class WifiDeviceProcessor implements WifiCentral, HealthEcologyProcessor @Override public WifiScanningResponse getScannedInformation() { return Optional.ofNullable(wifiDevice) + .filter(device -> Optional.ofNullable(device.getScanInfoList()).isPresent()) .map(device -> device.getScanInfoList().stream()) .map(infoStream -> infoStream .map(wifiScanInfo -> WifiScannedInfo.of(wifiScanInfo.getSsid(), diff --git a/OpenHealthEcologyFA/README.md b/OpenHealthEcologyFA/README.md index a3555d6adfc2636412c9448b4e8741ae673a9bdb..b1de5c347071ea9e34647cb7f692a456f537b6e1 100644 --- a/OpenHealthEcologyFA/README.md +++ b/OpenHealthEcologyFA/README.md @@ -27,7 +27,7 @@ Please have the following setup ready: - [DevEco Studio 2.1 Release or later](https://developer.harmonyos.com/cn/develop/deveco-studio) -- A HarmonyOS device with OS version 2.0.0.168 or later +- A HarmonyOS device with OS version 2.0.0.200 or later - A Ble peripheral device(or possibly a phone acting as a Ble peripheral device with the nrf-connect app) @@ -35,18 +35,6 @@ Please have the following setup ready: - You need to create the HarmonyOS application and apply for a certificate in [AppGalleryConnect](https://developer.huawei.com/consumer/cn/service/josp/agc/index.html#/). For details, see [Preparations](https://device.harmonyos.com/cn/docs/devicepartner/DevicePartner-Guides/health-fa-development-preparations-0000001172144685) -### Get Started - -* It's recommended to clone the project directly, but you may also download it with a zip file. -* Install `node.js` dependencies in the following path `OpenHealthEcologyFA/entry`: - ```shell - cd entry - npm install --save - ``` -* Please copy the folder `OpenHealthEcologyFA/@health-ecology-kit` into `OpenHealthEcologyFA/entry/node_modules`: - ```shell - cp ../@health-ecology-kit ./node_modules/@health-ecology-kit -r - ``` ### Configurations diff --git a/OpenHealthEcologyFA/README_zh.md b/OpenHealthEcologyFA/README_zh.md index b777fe8a9dd7e8be3bdd27891af24851b57a9353..ac83eaf15d4152bbf1424143cd6dbe5cd3991f86 100644 --- a/OpenHealthEcologyFA/README_zh.md +++ b/OpenHealthEcologyFA/README_zh.md @@ -28,7 +28,7 @@ OpenHealthEcologyFA 是华为所提供的专用于运动健康品类三方设备 - [DevEco Studio 2.1 Release 或更高版本](https://developer.harmonyos.com/cn/develop/deveco-studio) -- 一台鸿蒙手机,软件版本2.0.0.168及以上 +- 一台鸿蒙手机,软件版本2.0.0.200及以上 - 一台支持蓝牙Ble连接的设备,可以为外设或手机(需使用nrf-connect模拟Ble设备) @@ -36,18 +36,6 @@ OpenHealthEcologyFA 是华为所提供的专用于运动健康品类三方设备 - 安装示例代码到真机上运行还需要在[AppGalleryConnect](https://developer.huawei.com/consumer/cn/service/josp/agc/index.html#/)创建HarmonyOS应用并申请证书,请参阅[开发准备](https://device.harmonyos.com/cn/docs/devicepartner/DevicePartner-Guides/health-fa-development-preparations-0000001172144685) -### 安装 - -1. 请将码云仓库克隆至本地,或下载压缩包解压。 -2. 请进入`OpenHealthEcologyFA/entry`,安装node.js依赖包: - ```shell - cd entry - npm install --save - ``` -3. 请将`OpenHealthEcologyFA/@health-ecology-kit`文件夹整体拷贝或剪切至`OpenHealthEcologyFA/entry/node_modules`: - ```shell - cp ../@health-ecology-kit ./node_modules/@health-ecology-kit -r - ``` ### 配置选项 diff --git a/OpenHealthEcologyFA/build.gradle b/OpenHealthEcologyFA/build.gradle index 57ec1491494aabb1e57ff2e6b9b571e4fceb3ba6..fbc647a90b12310f1fb9970423082e24a3449104 100644 --- a/OpenHealthEcologyFA/build.gradle +++ b/OpenHealthEcologyFA/build.gradle @@ -3,9 +3,9 @@ apply plugin: 'com.huawei.ohos.app' //For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 ohos { - compileSdkVersion 5 + compileSdkVersion 6 defaultConfig { - compatibleSdkVersion 5 + compatibleSdkVersion 6 } } @@ -20,8 +20,8 @@ buildscript { jcenter() } dependencies { - classpath 'com.huawei.ohos:hap:2.4.4.2' - classpath 'com.huawei.ohos:decctest:1.2.4.1' + classpath 'com.huawei.ohos:hap:3.0.3.4' + classpath 'com.huawei.ohos:decctest:1.2.6.0' } } diff --git a/OpenHealthEcologyFA/entry/build.gradle b/OpenHealthEcologyFA/entry/build.gradle index 2e6044de41131cdfae81115454361c8217a4cbf1..d560333e6e5f608fd692822a49a33dd3830bfc72 100644 --- a/OpenHealthEcologyFA/entry/build.gradle +++ b/OpenHealthEcologyFA/entry/build.gradle @@ -1,10 +1,11 @@ apply plugin: 'com.huawei.ohos.hap' apply plugin: 'com.huawei.ohos.decctest' +apply from: "../utils.gradle" //For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 ohos { - compileSdkVersion 5 + compileSdkVersion 6 defaultConfig { - compatibleSdkVersion 5 + compatibleSdkVersion 6 } buildTypes { release { @@ -14,6 +15,9 @@ ohos { } } } + afterEvaluate { + preBuild.dependsOn initNodeModules + } } dependencies { @@ -24,7 +28,7 @@ dependencies { ohosTestImplementation 'org.hamcrest:hamcrest-core:2.2' ohosTestImplementation 'org.hamcrest:hamcrest:2.2' - api 'org.projectlombok:lombok:1.18.12' + compileOnly 'org.projectlombok:lombok:1.18.12' implementation 'org.jetbrains:annotations:17.0.0' annotationProcessor 'org.projectlombok:lombok:1.18.12' implementation 'com.huawei.hms:jsb-ohos-adapter:5.3.0.303' diff --git a/OpenHealthEcologyFA/entry/src/main/config.json b/OpenHealthEcologyFA/entry/src/main/config.json index c4b90522530ce14948f9899e480364768f25bfa1..e44f36ac900825dd377c356e08bdd926c6c543c6 100644 --- a/OpenHealthEcologyFA/entry/src/main/config.json +++ b/OpenHealthEcologyFA/entry/src/main/config.json @@ -23,6 +23,10 @@ { "name": "com.huawei.hms.client.appid", "value": "123456789" + }, + { + "name": "hwc-theme", + "value": "androidhwext:style/Theme.Emui.Translucent.NoTitleBar" } ] }, @@ -51,32 +55,7 @@ "action.system.home" ] } - ], - "metaData": { - "customizeData": [ - { - "name": "hwc-theme", - "value": "androidhwext:style/Theme.Emui.Translucent.NoTitleBar" - } - ] - } - }, - { - "visible": false, - "name": "com.huawei.health.ecology.fa.ability.JumpAbility", - "icon": "$media:icon", - "label": "$string:main_JumpAbility", - "description": "$string:main_JumpAbility_description", - "type": "page", - "launchType": "singleton", - "metaData": { - "customizeData": [ - { - "name": "hwc-theme", - "value": "androidhwext:style/Theme.Emui.Translucent.NoTitleBar" - } - ] - } + ] } ], "reqPermissions": [ @@ -140,7 +119,6 @@ "pages": [ "pages/index/index", "pages/guide/guide", - "pages/services/services", "pages/settings/settings", "pages/about/about" ], diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/JumpAbility.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/JumpAbility.java deleted file mode 100644 index acae61a37bfcfb1e44a3949307e2baecb5699803..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/JumpAbility.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -package com.huawei.health.ecology.fa.ability; - -import ohos.aafwk.content.Intent; -import ohos.aafwk.content.Operation; -import ohos.ace.ability.AceAbility; - -/** - * Jump Ability - */ -public class JumpAbility extends AceAbility { - @Override - public void onStart(Intent intent) { - super.onStart(intent); - Intent intentVariable = new Intent(); - Operation operation = new Intent.OperationBuilder().withDeviceId("") - .withBundleName(getBundleName()) - .withAbilityName(MainAbility.class.getName()) - .withFlags(Intent.FLAG_ABILITY_NEW_MISSION) - .build(); - intentVariable.setOperation(operation); - intentVariable.setParams(intent.getParams()); - startAbility(intentVariable); - terminateAbility(); - } - - @Override - public void onStop() { - super.onStop(); - } -} diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/MainAbility.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/MainAbility.java index 02a41cb9d3ee53c3a1ac08e4995e292b5dc88a1b..00faeb14a6157dd0a5d7b3f3aacbfe5e3597eeb4 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/MainAbility.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/ability/MainAbility.java @@ -74,11 +74,13 @@ public class MainAbility extends AceAbility { private static final String INTENT_PRODUCT_INFO = "productInfo"; + private static final String INTENT_PARAM_RESTART_REQUIRED = "restartRequired"; + private static final String INTENT_PARAM_BUSINESS_INFO = "businessInfo"; private static final String INTENT_PARAM_BUNDLE_NAME = "bundleName"; - private static final String INTENT_PARAM_ABILITY_NAME = "jumpAbilityName"; + private static final String INTENT_PARAM_ABILITY_NAME = "abilityName"; private static final String INTENT_KEY_91 = "91"; @@ -183,7 +185,7 @@ public class MainAbility extends AceAbility { ConditionOperation.of(loadedPageStack.get() == 0).ifExist(emptyStack -> { ClientModule.release(); CentralClientModule.destroy(); - }), DEFAULT_AUTO_TERMINATE_TIME, TimeUnit.MILLISECONDS); + }), DEFAULT_AUTO_TERMINATE_TIME, TimeUnit.MILLISECONDS); super.onStop(); } @@ -195,7 +197,7 @@ public class MainAbility extends AceAbility { private void setBundleInfo(Intent intentVariable) { intentVariable.setParam(INTENT_PARAM_BUNDLE_NAME, getBundleName()); - intentVariable.setParam(INTENT_PARAM_ABILITY_NAME, JumpAbility.class.getName()); + intentVariable.setParam(INTENT_PARAM_ABILITY_NAME, getClass().getName()); } /** @@ -231,16 +233,14 @@ public class MainAbility extends AceAbility { String macAddress = validateMacAddress(address) ? address : address.replaceAll(REGEX_REPLACE_MAC, MAC_REPLACEMENT).substring(1); - Optional.ofNullable(intentVariable).ifPresent(intent -> intent.setParam(INTENT_PARAM_MAC_ADDRESS, macAddress)); + Optional.ofNullable(intentVariable).ifPresent( + intent -> intent.setParam(INTENT_PARAM_MAC_ADDRESS, macAddress.toUpperCase(Locale.getDefault()))); } private boolean validateMacAddress(String address) { String macRegex = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"; Pattern pattern = Pattern.compile(macRegex); - return Optional.ofNullable(address) - .map(pattern::matcher) - .map(Matcher::matches) - .orElse(false); + return Optional.ofNullable(address).map(pattern::matcher).map(Matcher::matches).orElse(false); } private void setMacAddressByByteArray(Intent intent, IntentParams businessInfo) { @@ -297,4 +297,12 @@ public class MainAbility extends AceAbility { .map(netHandles -> netHandles.length > 0) .orElse(false); } + + @Override + public void onNewIntent(Intent intent) { + super.onNewIntent(intent); + if (intent.getBooleanParam(INTENT_PARAM_RESTART_REQUIRED, false)) { + restart(); + } + } } diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/AbilityOperation.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/AbilityOperation.java deleted file mode 100644 index dd7b11274219b85140eb1e76c14efed1cabb940d..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/AbilityOperation.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -package com.huawei.health.ecology.fa.central.api; - -import com.huawei.health.ecology.fa.central.request.ProxyRegisterRequest; -import com.huawei.health.ecology.fa.central.request.StartAbilityRequest; -import com.huawei.health.ecology.fa.central.response.CentralResponseCode; -import com.huawei.health.ecology.fa.central.response.QueryUniqueIdResponse; - -/** - * Ability Operation interface - */ -public interface AbilityOperation { - /** - * Gets unique id for BI analysis. - * - * @return the response contains unique id - */ - QueryUniqueIdResponse getUniqueId(); - - /** - * Start ability. - * - * @param startAbilityRequest the start ability request - * @return the central response code - */ - CentralResponseCode startAbility(StartAbilityRequest startAbilityRequest); - - /** - * Open url with another application. - * - * @param url the url link - * @return the central response code - */ - CentralResponseCode openUrl(String url); - - /** - * Perform proxy register. - * - * @param proxyRegisterRequest the register request - * @return the central response code - */ - CentralResponseCode performProxyRegister(ProxyRegisterRequest proxyRegisterRequest); -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/OhosPermissionOperation.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/OhosPermissionOperation.java index 4df177b8b59d70a883c737fe68b3bd72ce41c1b7..b54b740e7fd555f1608231dc0be392391bfc5474 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/OhosPermissionOperation.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/api/OhosPermissionOperation.java @@ -15,6 +15,7 @@ package com.huawei.health.ecology.fa.central.api; +import com.huawei.health.ecology.fa.central.callback.PermissionStateCallback; import com.huawei.health.ecology.fa.central.request.PermissionAcquireRequest; import com.huawei.health.ecology.fa.central.request.PermissionVerifyRequest; import com.huawei.health.ecology.fa.central.response.CentralResponseCode; @@ -32,6 +33,13 @@ public interface OhosPermissionOperation { */ PermissionStateResponse checkPermissions(PermissionVerifyRequest permissionVerifyRequest); + /** + * Applying for Permissions from Users + * + * @param permissionStateCallback permission callback + */ + void onPermissionRequest(PermissionStateCallback permissionStateCallback); + /** * Applying for Permissions from Users * diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/data/IntentOptions.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/data/IntentOptions.java index 68bdf594085043d83fc68e38f83568be271fb4f5..216b53efadb6e1c372ef46585f818af4c499afd1 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/data/IntentOptions.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/data/IntentOptions.java @@ -24,7 +24,7 @@ import lombok.Getter; @Getter @Builder public class IntentOptions { - private final int flags; + private final Integer flags; private final String uri; diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/module/CentralClientModule.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/module/CentralClientModule.java index f3d075065a70f279b8be2d371cac261c85b58833..a38757958e58a284a4f0549338f47574e5a08e15 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/module/CentralClientModule.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/module/CentralClientModule.java @@ -15,7 +15,6 @@ package com.huawei.health.ecology.fa.central.module; -import com.huawei.health.ecology.fa.central.processor.AbilityOperationProcessor; import com.huawei.health.ecology.fa.central.processor.AudioPlayerProcessor; import com.huawei.health.ecology.fa.central.processor.OhosPermissionProcessor; import com.huawei.healthecology.json.GsonMapper; @@ -32,8 +31,6 @@ import java.util.Optional; public class CentralClientModule { private static JsonModule jsonModule; - private static AbilityOperationProcessor abilityOperationProcessor; - private static OhosPermissionProcessor ohosPermissionProcessor; private static AudioPlayerProcessor audioPlayerProcessor; @@ -48,10 +45,8 @@ public class CentralClientModule { */ public static void inject(Context context) { jsonModule = JsonModule.init(GsonMapper.get()); - abilityOperationProcessor = AbilityOperationProcessor.builder().context(context).build(); ohosPermissionProcessor = OhosPermissionProcessor.builder().context(context).build(); audioPlayerProcessor = AudioPlayerProcessor.builder(context).build(); - abilityOperationProcessor.initProcessor(); ohosPermissionProcessor.initProcessor(); audioPlayerProcessor.initProcessor(); } @@ -65,15 +60,6 @@ public class CentralClientModule { return Optional.ofNullable(jsonModule).map(JsonModule::getMapper); } - /** - * Gets ability operation processor. - * - * @return The ability operation processor - */ - public static Optional getAbilityOperationProcessor() { - return Optional.ofNullable(abilityOperationProcessor); - } - /** * Gets ohos permission processor. * @@ -107,11 +93,9 @@ public class CentralClientModule { * Destroy allocations */ public static void destroy() { - abilityOperationProcessor.destroyProcessor(); ohosPermissionProcessor.destroyProcessor(); audioPlayerProcessor.destroyProcessor(); jsonModule = null; - abilityOperationProcessor = null; ohosPermissionProcessor = null; audioPlayerProcessor = null; } diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/operator/CentralOperationCode.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/operator/CentralOperationCode.java index 29087ed6a6f6968ac888a9a7140b2701e5a790d8..38cd6f0377d0f37f05f71bcbf81580b7f84f40fb 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/operator/CentralOperationCode.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/operator/CentralOperationCode.java @@ -16,13 +16,10 @@ package com.huawei.health.ecology.fa.central.operator; import com.huawei.health.ecology.fa.central.module.CentralClientModule; -import com.huawei.health.ecology.fa.central.processor.AbilityOperationProcessor; import com.huawei.health.ecology.fa.central.processor.AudioPlayerProcessor; import com.huawei.health.ecology.fa.central.request.AudioPlayRequest; import com.huawei.health.ecology.fa.central.request.PermissionAcquireRequest; import com.huawei.health.ecology.fa.central.request.PermissionVerifyRequest; -import com.huawei.health.ecology.fa.central.request.ProxyRegisterRequest; -import com.huawei.health.ecology.fa.central.request.StartAbilityRequest; import com.huawei.health.ecology.fa.central.response.CentralResponseCode; import com.huawei.healthecology.data.platform.PlatformOperation; import com.huawei.healthecology.data.platform.PlatformRequest; @@ -81,46 +78,6 @@ public enum CentralOperationCode { .build())); } }, - START_ABILITY(2_004) { - @Override - Optional toProcessRequest(PlatformOperation operation) { - return CentralClientModule.getAbilityOperationProcessor() - .map(processor -> operation.getRawRequest() - .flatMap(rawRequest -> CentralClientModule.getParser() - .flatMap(parser -> parser.mapTo(rawRequest, StartAbilityRequest.class)) - .map(processor::startAbility) - .map(responseCode -> PlatformResponse.builder() - .responseCode(responseCode) - .build())) - .orElse(PlatformResponse.builder() - .responseCode(CentralResponseCode.OPERATION_FAILED) - .build())); - } - }, - OPEN_URL_REQUEST(2_005) { - @Override - Optional toProcessRequest(PlatformOperation operation) { - return CentralClientModule.getAbilityOperationProcessor() - .map(processor -> operation.getRawRequest() - .map(processor::openUrl) - .map(responseCode -> PlatformResponse.builder() - .responseCode(responseCode) - .build()) - .orElse(PlatformResponse.builder() - .responseCode(CentralResponseCode.OPERATION_FAILED) - .build())); - } - }, - GET_UNIQUE_ID(2_006) { - @Override - Optional toProcessRequest(PlatformOperation operation) { - return CentralClientModule.getAbilityOperationProcessor() - .map(AbilityOperationProcessor::getUniqueId) - .map(response -> PlatformResponse.builder() - .responseValue(response) - .build()); - } - }, START_AUDIO_PLAY(2_007) { @Override Optional toProcessRequest(PlatformOperation operation) { @@ -147,22 +104,6 @@ public enum CentralOperationCode { .build()); } }, - PERFORM_PROXY_REGISTER(2_009) { - @Override - Optional toProcessRequest(PlatformOperation operation) { - return CentralClientModule.getAbilityOperationProcessor() - .map(processor -> operation.getRawRequest() - .flatMap(rawRequest -> CentralClientModule.getParser() - .flatMap(parser -> parser.mapTo(rawRequest, ProxyRegisterRequest.class))) - .map(processor::performProxyRegister) - .map(responseCode -> PlatformResponse.builder() - .responseCode(responseCode) - .build()) - .orElse(PlatformResponse.builder() - .responseCode(CentralResponseCode.OPERATION_FAILED) - .build())); - } - }, UNKNOWN_OPERATOR(1_1111) { @Override Optional toProcessRequest(PlatformOperation operation) { diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/AbilityOperationProcessor.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/AbilityOperationProcessor.java deleted file mode 100644 index 8dc2ee4e0a9bcffb2c40f1be3f5f8e2addca6ca3..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/AbilityOperationProcessor.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -package com.huawei.health.ecology.fa.central.processor; - -import com.huawei.health.ecology.fa.central.api.AbilityOperation; -import com.huawei.health.ecology.fa.central.data.IntentOptions; -import com.huawei.health.ecology.fa.central.request.ProxyRegisterRequest; -import com.huawei.health.ecology.fa.central.request.StartAbilityRequest; -import com.huawei.health.ecology.fa.central.response.CentralResponseCode; -import com.huawei.health.ecology.fa.central.response.QueryUniqueIdResponse; -import com.huawei.healthecology.data.utils.ConditionOperation; -import com.huawei.healthecology.data.utils.OptionalX; -import com.huawei.healthecology.processor.HealthEcologyProcessor; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import ohos.aafwk.content.Intent; -import ohos.aafwk.content.Operation; -import ohos.app.Context; -import ohos.data.DatabaseHelper; -import ohos.data.preferences.Preferences; -import ohos.utils.net.Uri; - -import java.util.Locale; -import java.util.Optional; -import java.util.UUID; - -/** - * The processor for ability context related operations - */ -@Builder -@AllArgsConstructor -public class AbilityOperationProcessor implements AbilityOperation, HealthEcologyProcessor { - private static final String TAG = "AbilityOperationProcessor"; - - private static final String URL = "url"; - - private static final String URI = "uri"; - - private static final String SEPARATOR = "-"; - - private static final String FLAGS = "flags"; - - private static final String PARAMS = "params"; - - private static final String UUID_KEY = "uuid"; - - private static final String UNIQUE_ID = "uniqueId"; - - private static final String FILE_NAME = "common_db"; - - private static final String KEY_FROM_APP = "&fromApp="; - - private static final String INTENT_ACTION_VIEW = "android.intent.action.VIEW"; - - private static final String PROXY_REGISTER_URI = "hilink://hilinksvc.huawei.com/device?action=deviceAdd&prodId="; - - private final Context context; - - private String uniqueId; - - @Override - public void initProcessor() { - setUniqueId(); - } - - @Override - public void releaseResource() { - } - - @Override - public void destroyProcessor() { - } - - @Override - public QueryUniqueIdResponse getUniqueId() { - return Optional.ofNullable(uniqueId) - .map(uniqueIdVariable -> QueryUniqueIdResponse.builder() - .responseCode(CentralResponseCode.OPERATION_SUCCESS) - .uniqueId(uniqueIdVariable) - .build()) - .orElse(QueryUniqueIdResponse.builder() - .responseCode(CentralResponseCode.OPERATION_FAILED) - .build()); - } - - private void setUniqueId() { - DatabaseHelper databaseHelper = new DatabaseHelper(context); - Preferences preferences = databaseHelper.getPreferences(FILE_NAME); - Optional.ofNullable(preferences).ifPresent(preferencesVariable -> { - uniqueId = Optional.of(preferencesVariable.getString(UNIQUE_ID, "")) - .filter(uniqueIdVariable -> !uniqueIdVariable.isEmpty()) - .orElse(UUID.randomUUID().toString().replace(SEPARATOR, "").toLowerCase(Locale.ROOT)); - preferencesVariable.putString(UNIQUE_ID, uniqueId); - preferencesVariable.flush(); - }); - } - - @Override - public CentralResponseCode startAbility(StartAbilityRequest startAbilityRequest) { - return Optional.of(startAbilityRequest) - .flatMap(this::getStartAbilityIntent) - .map(intent -> toStartAbility(intent, startAbilityRequest.getIntentOptions())) - .orElse(CentralResponseCode.OPERATION_FAILED); - } - - private Optional getStartAbilityIntent(StartAbilityRequest startAbilityRequest) { - Intent.OperationBuilder operationBuilder = new Intent.OperationBuilder(); - Optional.ofNullable(startAbilityRequest.getIntentOptions()).ifPresent(optionsVariable -> { - OptionalX.ofNullable(optionsVariable.getAction()) - .ifPresent(operationBuilder::withAction) - .ifNotPresent(() -> operationBuilder - .withAbilityName(startAbilityRequest.getAbilityName()) - .withBundleName(startAbilityRequest.getBundleName())); - Optional.ofNullable(optionsVariable.getUri()).map(Uri::parse).ifPresent(operationBuilder::withUri); - Optional.of(optionsVariable.getFlags()).ifPresent(operationBuilder::withFlags); - }); - Intent intent = new Intent(); - Optional.ofNullable(startAbilityRequest.getIntentParams()) - .ifPresent(paramsVariable -> intent.setParam(PARAMS, paramsVariable)); - intent.setOperation(operationBuilder.build()); - return Optional.of(intent); - } - - private CentralResponseCode toStartAbility(Intent intent, IntentOptions intentOptions) { - boolean isNewMissionFlag = - (intent.getFlags() & Intent.FLAG_ABILITY_NEW_MISSION) == Intent.FLAG_ABILITY_NEW_MISSION; - ConditionOperation.of(isNewMissionFlag) - .ifExist(isNewMission -> { - Optional.ofNullable(intentOptions) - .filter(IntentOptions::isTerminable) - .ifPresent(options -> context.terminateAbility()); - context.startAbility(intent, 0); - }) - .ifNotExist(notNewMission -> context.startAbility(intent, 0)); - return CentralResponseCode.OPERATION_SUCCESS; - } - - @Override - public CentralResponseCode openUrl(String url) { - Intent intent = new Intent(); - Operation operation = new Intent.OperationBuilder() - .withUri(Uri.parse(url)) - .withAction(INTENT_ACTION_VIEW) - .withFlags(Intent.FLAG_ABILITY_NEW_MISSION) - .build(); - intent.setOperation(operation); - context.startAbility(intent, 0); - return CentralResponseCode.OPERATION_SUCCESS; - } - - @Override - public CentralResponseCode performProxyRegister(ProxyRegisterRequest proxyRegisterRequest) { - return Optional.of(proxyRegisterRequest) - .filter(request -> (request.getProductId() != null && request.getRegisterUuid() != null)) - .map(request -> obtainProxyRegisterIntent(request.getRegisterUuid(), request.getProductId())) - .map(this::performProxyRegister) - .orElse(CentralResponseCode.OPERATION_FAILED); - } - - private Intent obtainProxyRegisterIntent(String uuid, String productId) { - Operation operation = new Intent.OperationBuilder().withDeviceId("") - .withFlags(Intent.FLAG_ABILITY_NEW_MISSION | Intent.FLAG_NOT_OHOS_COMPONENT) - .withUri(Uri.parse(PROXY_REGISTER_URI + productId + KEY_FROM_APP + context.getBundleName())) - .build(); - Intent intent = new Intent(); - intent.setOperation(operation); - intent.setParam("uuid", uuid); - return intent; - } - - private CentralResponseCode performProxyRegister(Intent intent) { - context.startAbility(intent, 0); - context.terminateAbility(); - return CentralResponseCode.OPERATION_SUCCESS; - } -} diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/OhosPermissionProcessor.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/OhosPermissionProcessor.java index bee40f2859723e80ad2acb3e410d53f83fce569f..9de4bec71c973e3a7dd43fa324e0ddea0034d313 100644 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/OhosPermissionProcessor.java +++ b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/processor/OhosPermissionProcessor.java @@ -104,11 +104,7 @@ public class OhosPermissionProcessor implements OhosPermissionOperation, HealthE return CentralResponseCode.OPERATION_SUCCESS; } - /** - * Applying for Permissions from Users - * - * @param permissionStateCallback permission callback - */ + @Override public void onPermissionRequest(PermissionStateCallback permissionStateCallback) { OptionalX.ofNullable(permissionStateProvider) .ifPresent(callbackProvider -> callbackProvider.add(permissionStateCallback)) diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/ProxyRegisterRequest.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/ProxyRegisterRequest.java deleted file mode 100644 index 74e13786d9034a02d811067720dea5a0d7436074..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/ProxyRegisterRequest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -package com.huawei.health.ecology.fa.central.request; - -import lombok.Builder; -import lombok.Getter; -import lombok.NonNull; - -/** - * The proxy register request - */ -@Getter -@Builder -public class ProxyRegisterRequest { - @NonNull - private final String registerUuid; - - @NonNull - private final String productId; -} diff --git a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/StartAbilityRequest.java b/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/StartAbilityRequest.java deleted file mode 100644 index aba8029e92bfb6eef11ab8f162540181489c3a39..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/java/com/huawei/health/ecology/fa/central/request/StartAbilityRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -package com.huawei.health.ecology.fa.central.request; - -import com.huawei.health.ecology.fa.central.data.IntentOptions; - -import lombok.Builder; -import lombok.Getter; - -/** - * The start ability request - */ -@Getter -@Builder -public class StartAbilityRequest { - private final String bundleName; - - private final String abilityName; - - private final String intentParams; - - private final IntentOptions intentOptions; -} diff --git a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.hml b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.hml index 75ec1702b110537bbd1034667b206eb434f4fbfa..85bb4e5bf9dc401285334dfca972d51c62fb6991 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.hml @@ -57,10 +57,10 @@ src='{{ checkboxIcon }}'> - {{ $t('strings.public_agree', { statement : $t('strings.custom_FA_name') }) }} + {{ $t('strings.public_agree') }} - {{ $t('strings.public_privacy_statement') }} + {{ $t('strings.public_privacy_statement', { faName : $t('strings.custom_FA_name') }) }} diff --git a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.js b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.js index 5a2396bbca032af69154907779a96dfe20c2549c..efd47ef381d72b01319d4023925c455316bbcf53 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.js +++ b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/loginDialog/loginDialog.js @@ -74,7 +74,7 @@ export default { }, openPrivacyDialog() { console.info(JS_TAG + 'openPrivacyDialog'); - this.$emit('onPrivacyButtonClick'); + this.$emit('onPrivacyDisplay'); }, exit() { app.terminate(); diff --git a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/permissionForbiddenDialog/permissionForbiddenDialog.js b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/permissionForbiddenDialog/permissionForbiddenDialog.js index f0c595f9a77a0754805cd0dcba943057332c9593..16b8b01fbf8f77a026c9c316f6d522bf7bb81583 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/permissionForbiddenDialog/permissionForbiddenDialog.js +++ b/OpenHealthEcologyFA/entry/src/main/js/connection/common/components/permissionForbiddenDialog/permissionForbiddenDialog.js @@ -14,12 +14,12 @@ */ import app from '@system.app'; +import wantConstant from '@ohos.ability.wantConstant'; +import featureAbility from '@ohos.ability.featureAbility' import state from '../../../../share/common/state.js' -import centralOperator from '../../../../share/common/scripts/centralOperator'; const showState = [state.connection.PERMISSION_FORBIDDEN] const JS_TAG = 'JS/Component/Permission forbidden dialog: '; -const SETTING_ACTION = 'ohos.settings.application.details'; const URI_SCHEMA = 'package:' export default { @@ -36,13 +36,13 @@ export default { app.terminate(); }, enterSetting() { - centralOperator.startAbility({ - intentOptions: { - action: SETTING_ACTION, + let startAbilityOption = { + want:{ + action:wantConstant.Action.ACTION_APPLICATION_DETAILS_SETTINGS, uri: URI_SCHEMA + this.$app.$def.globalData.bundleName - }, - success: app.terminate, - fail(code, err) {}, - }); + } + } + console.error(JSON.stringify(startAbilityOption)); + featureAbility.startAbility(startAbilityOption); }, } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.hml b/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.hml index 8bacf51a2636a335b31b4936426442751b4b7940..43801b41e780a6280f5e80ee0e0e1fc42e15084d 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.hml @@ -20,11 +20,11 @@ -
+
diff --git a/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.js b/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.js index 250306845784a04040224532a432d4fcc19368ec..5d30809adc84624dd1c82c9027318ebc7d81c086 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.js +++ b/OpenHealthEcologyFA/entry/src/main/js/connection/pages/index/index.js @@ -14,12 +14,14 @@ */ import prompt from '@system.prompt'; -import storage from '@system.storage'; +import dataStorage from '@ohos.data.storage' +import wantConstant from '@ohos.ability.wantConstant'; +import featureAbility from '@ohos.ability.featureAbility' +import HuaweiAccount from '../../../share/common/scripts/HuaweiAccount.js' import state from '../../../share/common/state.js'; import config from '../../../share/common/config.js'; -import hekOperator from '@health-ecology-kit/hek-operator'; -import constants from '../../../share/common/scripts/constants.js'; -import centralOperator from '../../../share/common/scripts/centralOperator'; +import app from '@system.app' +import {HealthEcologyOperator as hekOperator, BleNotifyType} from '@health-ecology-kit/hek-operator'; import permissionHelper from '../../../share/common/scripts/permissionHelper.js'; const JS_TAG = 'JS/Page/Connection: '; @@ -50,33 +52,25 @@ export default { hekOperator.onBluetoothAdapterStateChange(this.bluetoothAdapterStateCallback); hekOperator.onBleCharacteristicValueChange(this.bleCharacteristicChangeCallback); }, -////////////////////////////////////////// -//////// 隐私同意与账号登陆 /////// - checkLoginAndPrivacy() { + ////////////////////////////////////////// + //////// 隐私同意与账号登陆 /////// + async checkLoginAndPrivacy() { console.info(JS_TAG + 'Checking login and privacy status'); - storage.get({ - key: 'rt_expire_timestamp', - default: undefined, - success: expireTimestamp => { - if (expireTimestamp != '') { - let timestampNow = new Date().getTime(); - if (timestampNow < expireTimestamp) { - // Refresh Token not expired - console.debug(JS_TAG + 'Refresh token not expired!') - this.onLoginFinished(); - } else { - // Refresh Token Expired - prompt.showToast({ - message: this.$t('strings.public_logged_out_message') - }); - console.debug(JS_TAG + 'Refresh token expired!'); - } - } - }, - fail: (data, code) => { - console.error(JS_TAG + 'Check refresh token data failed, error code:' + code + ', data: ' + data); - } - }); + let path = await featureAbility.getContext().getFilesDir(); + let storage = dataStorage.getStorageSync(path + '/preferences'); + let expireTimestamp = storage.getSync('rt_expire_timestamp', '0'); + let timestampNow = new Date().getTime(); + if (timestampNow < expireTimestamp) { + // Refresh Token not expired + console.debug(JS_TAG + 'Refresh token not expired!') + this.onLoginFinished(); + } else { + // Refresh Token Expired + prompt.showToast({ + message: this.$t('strings.public_logged_out_message') + }); + console.debug(JS_TAG + 'Refresh token expired!'); + } }, privacyButtonClick() { console.debug(JS_TAG + 'onPrivacyButtonClick'); @@ -102,25 +96,32 @@ export default { console.error(JS_TAG + 'onLoginError, error = ' + JSON.stringify(loginError)); this.changeState(state.connection.PRIVACY, state.connection.DISCOVERING, state.connection.CONNECTING); }, - async onLoginFinished(){ + async onLoginFinished() { this.changeState(state.connection.DISCOVERING, state.connection.PRIVACY); if (config.proxyRegisterRequired && !this.deviceId && this.uuid && this.ProtocolID == 2) { // with proxyRegisterRequired flag is true, // with sufficient nfc tag(protocolId == 2), // with deviceId empty(not registered), // with uuid exists(for hilink authentication, carried by hilink at startup) - await centralOperator.performProxyRegister({ - uuid: this.uuid, - productId: this.productId, - success: this.checkBluetoothAdapterState, - fail(code, err) {}, - }) + let startAbilityOption = { + want: { + uri: 'hilink://hilinksvc.huawei.com/device?action=deviceAdd&prodId=' + + this.productId + '&fromApp=' + this.bundleName, + flags: wantConstant.Flags.FLAG_ABILITY_NEW_MISSION | wantConstant.Flags.FLAG_NOT_OHOS_COMPONENT, + parameters: { + uuid: this.uuid + } + } + } + featureAbility.startAbility(startAbilityOption); + app.terminate(); } else { this.checkBluetoothAdapterState(); } + }, -////////////////////////////////////////// -//////// 位置权限检查与授予 /////// + ////////////////////////////////////////// + //////// 位置权限检查与授予 /////// checkAndRequestPermissions() { console.debug(JS_TAG + 'Scan required is :' + config.scanRequired); if (config.scanRequired) { @@ -143,8 +144,8 @@ export default { : state.connection.PERMISSION_DENIED; this.changeState(updateState); }, -//////////////////////////////////////// -//////// 蓝牙接口调用 /////// + //////////////////////////////////////// + //////// 蓝牙接口调用 /////// checkBluetoothAdapterState() { hekOperator.getBluetoothAdapterState({ success: this.onCheckAdapterStateSuccess, @@ -155,6 +156,7 @@ export default { hekOperator.startBleDevicesDiscovery({ isAllowDuplicatesKey: false, reportInterval: 0, // Report the device as soon as it is found + timeoutInMillis: 10000, uuidServices: config.scanFilterUuid, success: this.onStartDiscoverySuccess, fail: this.onDeviceDiscoveryFailed @@ -185,15 +187,15 @@ export default { deviceId: this.macAddress, serviceId: config.serviceUuid, characteristicId: config.characterUuid, - enableNotify: true, // true for notify, and false for indicate + notifyType: BleNotifyType.INDICATION, // NOTIFICATION for notify, INDICATION for indicate success: () => { console.debug(JS_TAG + 'Enable notify and indicate success!'); }, fail: this.onEnableNotifyFailed }); }, -//////////////////////////////////////// -//////// 蓝牙回调处理 /////// + //////////////////////////////////////// + //////// 蓝牙回调处理 /////// bluetoothAdapterStateCallback(adapterState) { if (adapterState.isAvailable && (this.state == state.connection.RECONNECT_REQUESTED || this.state == state.connection.REDISCOVER_REQUESTED)) { @@ -213,12 +215,13 @@ export default { } }, bleServiceDiscoveredCallback(bleServiceDiscoveredResult) { - this.deviceConnected && bleServiceDiscoveredResult.isDiscoverySuccess ? - this.onServiceDiscoveredSuccess() : this.onServiceDiscoveredFailed(); + (this.deviceConnected && bleServiceDiscoveredResult.isDiscoverySuccess) + ? this.onServiceDiscoveredSuccess() + : this.onServiceDiscoveredFailed(); }, bleDeviceFoundCallback(foundDevices) { console.debug(JS_TAG + 'bleDeviceFoundCallback: ' + JSON.stringify(foundDevices)); - if (foundDevices.length == 0) { + if (foundDevices.length == 0 && this.state == state.connection.DISCOVERING) { this.onDeviceDiscoveryFailed(undefined, 'Discovery timeout.'); } for (let device of foundDevices) { @@ -231,8 +234,8 @@ export default { bleCharacteristicChangeCallback(bleCharacteristicChangeValue) { console.debug(JS_TAG + 'change data: ' + JSON.stringify(bleCharacteristicChangeValue.characteristicData)); }, -//////////////////////////////////////// -//////// 页面流程处理 /////// + //////////////////////////////////////// + //////// 页面流程处理 /////// onBackPress() { console.debug(JS_TAG + 'On back pressed.'); if (this.state == state.connection.PRIVACY_CONTENT) { @@ -320,19 +323,22 @@ export default { }, toDashboard() { console.debug(JS_TAG + 'Connected, jumping to dashboard.'); - centralOperator.startAbility({ - bundleName: this.bundleName, - abilityName: this.jumpAbilityName, - intentParams: { - macAddress: this.macAddress, - productId: this.productId, - }, - intentOptions: { - flags: constants.FLAG_ABILITY_NEW_MISSION, - isTerminable: true - }, - success(response) {}, - fail(code, err) {}, + let startAbilityOption = { + want: { + bundleName: this.bundleName, + abilityName: this.abilityName, + flags: wantConstant.Flags.FLAG_ABILITY_NEW_MISSION, + parameters: { + params: JSON.stringify({ + macAddress: this.macAddress, + productId: this.productId, + }), + restartRequired: true + } + } + } + featureAbility.startAbility(startAbilityOption).then(result => { + console.debug(JS_TAG + 'startAbilityOption success. Data: ' + JSON.stringify(result)); }); }, changeState(newState, ...oldStates) { diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/about/about.hml b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/about/about.hml index 1a53009d8e3b68107faf51ca37dab75d52c879c8..048cc2a8e1ef6d7dd3f4334983a038d1e399d8bf 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/about/about.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/about/about.hml @@ -15,7 +15,7 @@ -
+
@@ -33,10 +33,10 @@
- - {{ $t('strings.public_privacy_statement') }} + + {{ $t('strings.public_privacy_statement', { faName : $t('strings.custom_FA_name') }) }} - + {{ $t('strings.public_copyright', { CompanyName : $t('strings.custom_company_name') }) }} diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.hml b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.hml index a958e760bd1e1051fcf16efe9abfe2e85a80ad69..8f01919f643f43da3b4b51c00761984bc3e9b54a 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.hml @@ -52,7 +52,7 @@ label='{{ exceptionHintLabel }}' show-object='{{ true }}' show-next-icon='{{ true }}' - @on-click='onAlertClicked'> + @on-pressed='onAlertClicked'>
@@ -65,8 +65,8 @@ + @on-left-icon-pressed='onClickLeftIcon' + @on-right-icon-pressed='onClickRightIcon'> + @on-icon-pressed='onClickIcon'> + @on-text-pressed='onClickText'> </plaintext> <iconandtext type='{{ deviceStatusType }}' @@ -89,16 +89,16 @@ </div> <informationpanel - style="margin-top : {{ isFullScreen ? '10px' : '16px' }}" - config='{{ informationPanelConfig }}' - data='{{ informationPanelData }}'> + style="margin-top : {{ isFullScreen ? '10px' : '16px' }}" + config='{{ informationPanelConfig }}' + data='{{ informationPanelData }}'> </informationpanel> <div style='margin-top : 16px'> <modesswitchpanel - config='{{ modesSwitchPanelConfig }}' - data='{{ modesSwitchPanelData }}' - @on-change='onModeChange'> + config='{{ modesSwitchPanelConfig }}' + data='{{ modesSwitchPanelData }}' + @on-change='onModeChange'> </modesswitchpanel> </div> @@ -162,9 +162,9 @@ id='textPickerDialog' config='{{ textPickerConfig }}' data='{{ textPickerData }}' - @on-click-item='onClickItem' - @on-click-left='closeTextPickerDialog' - @on-click-right='onTextPickerConfirmed' + @on-item-pressed='onClickItem' + @on-left-pressed='closeTextPickerDialog' + @on-right-pressed='onTextPickerConfirmed' show='{{ isFullScreen }}'> </dialogbox> @@ -172,21 +172,19 @@ id='listSelectorDialog' config='{{ listSelectorConfig }}' data='{{ listSelectorData }}' - @on-click-item='onClickItem' - @on-click-left='closeListSelectorDialog' - @on-click-right='onListSelectorConfirmed' + @on-item-pressed='onClickItem' + @on-left-pressed='closeListSelectorDialog' + @on-right-pressed='onListSelectorConfirmed' show='{{ isFullScreen }}'> </dialogbox> <dialogbox id='infoDialog' config='{{ infoConfig }}' - @on-click-item='onClickItem' - @on-click-left='closeInfoDialog' - @on-click-right='closeInfoDialog' + @on-item-pressed='onClickItem' + @on-left-pressed='closeInfoDialog' + @on-right-pressed='closeInfoDialog' show='{{ isFullScreen }}'> </dialogbox> - - </div> diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.js b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.js index e79521ea01d3222aa78e0ffda3df756276252435..217540d4e0574b8362483bbe8682089f9632e347 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.js +++ b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/index/index.js @@ -15,10 +15,11 @@ import app from '@system.app'; import prompt from '@system.prompt'; -import storage from '@system.storage'; +import dataStorage from '@ohos.data.storage' +import featureAbility from '@ohos.ability.featureAbility' import config from '../../../share/common/config.js'; import dataParser from '../../../share/common/dataParser'; -import hekOperator from '@health-ecology-kit/hek-operator'; +import {HealthEcologyOperator as hekOperator, BleNotifyType} from '@health-ecology-kit/hek-operator'; import HuaweiAccount from '../../../../js/share/common/scripts/HuaweiAccount'; import TitleBarParams from '../../../share/common/components/titleBar/TitleBarParams'; import SliderBarParams from '../../../share/common/components/sliderBar/SliderBarParams'; @@ -39,7 +40,7 @@ import DeviceStatusCardDoubleIconParams from '../../../share/common/components/d const JS_TAG = 'JS/Page/Dashboard/index: '; const TOKEN_INVALID_ERROR_CODE = 1203; -const ENABLE_NOTIFY = true; +const NOTIFY_TYPE = BleNotifyType.INDICATION; const SERVICE_UUID = '0000abcd-0000-0000-0000-000000000000'; const CHARACTER_UUID = '0000abcd-0000-0000-0000-000000000000'; @@ -47,7 +48,6 @@ export default { data: { isFullScreen: false, macAddress: undefined, - productLogoIcon: '/common/img/base/ic_public_hw_logo.png', //组件数据初始化,必选 deviceStatus: 0, middleTitle: '17:52', @@ -128,14 +128,12 @@ export default { this.onLoggedOut(); } }, - onLoggedOut() { - storage.set({ - key: 'rt_expire_timestamp', - value: '0' - }) - storage.delete({ - key: 'refresh_token' - }) + async onLoggedOut() { + let path = await featureAbility.getContext().getFilesDir(); + let storage = dataStorage.getStorageSync(path + '/preferences'); + storage.putSync('rt_expire_timestamp', '0'); + storage.deleteSync('refresh_token'); + storage.flushSync(); prompt.showDialog({ message: this.$t('strings.public_logged_out_message'), buttons: [ @@ -579,7 +577,7 @@ export default { deviceId: this.macAddress, serviceId: SERVICE_UUID, characteristicId: CHARACTER_UUID, - enableNotify: ENABLE_NOTIFY, + notifyType: NOTIFY_TYPE, success: () => { console.debug(JS_TAG + 'Enable notify and indicate success!'); }, @@ -593,6 +591,9 @@ export default { }, bleConnectionStateCallback(connectionState) { console.debug(JS_TAG + 'Connection state changed: ' + JSON.stringify(connectionState)); + if (connectionState.deviceId != this.macAddress) { + return; + } if (connectionState.isConnected) { this.exceptionHintLabel = 'Device connected.'; } else { @@ -608,11 +609,14 @@ export default { } }, bleCharacteristicChangeCallback(bleCharacteristicChangeValue) { + if (bleCharacteristicChangeValue.deviceId != this.macAddress) { + return; + } this.showUndevelopedWarning('bleCharacteristicChangeCallback().'); console.debug(JS_TAG + 'onBleCharacteristicValueChange result = ' + JSON.stringify(bleCharacteristicChangeValue)); // 处理设备上报的特征值,需要开发者自行实现具体的协议解析 let result = dataParser.dealWithCharacteristicValue(bleCharacteristicChangeValue.deviceId, - bleCharacteristicChangeValue.data.characteristicId, bleCharacteristicChangeValue.data.changeData); + bleCharacteristicChangeValue.characteristicId, bleCharacteristicChangeValue.characteristicData); }, //////////////////////////////////////// //////// 页面流程处理 /////// diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.css b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.css deleted file mode 100644 index 677039e1df18f6ff182439fcb9f76c7fca5ccd03..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.css +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -@import '../../../style/common.css'; - -.list-content { - align-items: center; - margin-top: 56px; - flex: 1; - margin-left: 8px; - margin-right: 8px; -} - -.list-item-content { - margin-left: 4px; - margin-right: 4px; -} - -@media (dark-mode: true) { - .flex-column { - background-color: #202224; - } -} - - diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.hml b/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.hml deleted file mode 100644 index 178b6b925d5b25d716ce37b3d58a2544d3a0c2a3..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.hml +++ /dev/null @@ -1,33 +0,0 @@ -<!-- - Copyright (c) 2021 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. - --> - -<element name='titleBar' src='../../../share/common/components/titleBar/TitleBar'></element> -<element name='featuredItem' src='../../../share/common/components/featuredCard/featuredItem/FeaturedItem'></element> - -<div class='flex-column'> - <titlebar - config='{{ titleBarConfig }}' - show-object='true'></titlebar> - - <list class='list-content' id='list' style='columns : {{ columnsNum }}'> - <list-item class='list-item-content' type='listItem' clickeffect='false' for='{{ data }}'> - <featuredItem - width='{{ width }}' - height='{{ height }}' - item='{{ $item }}'> - </featuredItem> - </list-item> - </list> -</div> \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/alertHint/AlertHint.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/alertHint/AlertHint.js index 83b338aa32167a3a5a388a34b3168b84216c6785..37b1eb7c45b623bee3a722b2bec78663534dab64 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/alertHint/AlertHint.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/alertHint/AlertHint.js @@ -48,6 +48,6 @@ export default { DefaultValueOperator.imgPath(this.arrowRightImagePath, DEFAULT_IMAGE_PATH, this.$app.$def.globalData.isDarkMode); }, onClick() { - this.$emit('onClick'); + this.$emit('onPressed'); } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/circularProgressBar/CircularProgressBar.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/circularProgressBar/CircularProgressBar.js index ceac504da356b14ee770e356e9bc3cc7d7cac1ed..1363dd790e3be3f6369081b09088aabd8e92f16a 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/circularProgressBar/CircularProgressBar.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/circularProgressBar/CircularProgressBar.js @@ -16,84 +16,84 @@ const LOAD_PROGRESS=1; const PERCENT_PROGRESS=2; export default { - props: ['progressStatus', 'percent', 'updateVersion','productLogoIcon'], - data: { - isProgress: true, - isClock: false, - updatePercent: 0, - updateText: '0%', - updateVersion: '1.0.0', - percentShow: false, - imageShow: true, - }, - onInit() { - this.$watch('progressStatus', 'statusChange') - this.$watch('percent', 'percentChange') - }, - onPageShow() { - this.onShow(); - }, - statusChange(progressStatus, oldV) { - if (progressStatus == LOAD_PROGRESS) { - this.updatePercent = 20; - this.start(); - var context = this; - } - if (progressStatus == PERCENT_PROGRESS) { - this.imageShow = false; - this.percentShow = true; - this.finish(); + props: ['progressStatus', 'percent', 'updateVersion', 'productLogoIcon'], + data: { + isProgress: true, + isClock: false, + updatePercent: 0, + updateText: '0%', + updateVersion: '1.0.0', + percentShow: false, + imageShow: true, + }, + onInit() { + this.$watch('progressStatus', 'statusChange') + this.$watch('percent', 'percentChange') + }, + onPageShow() { + this.onShow(); + }, + statusChange(progressStatus, oldV) { + if (progressStatus == LOAD_PROGRESS) { + this.updatePercent = 20; + this.start(); + var context = this; + } + if (progressStatus == PERCENT_PROGRESS) { + this.imageShow = false; + this.percentShow = true; + this.finish(); + } + }, + percentChange(newV, oldV) { + if (!this.isClock) { + this.isClock = true; + } + this.updateText = newV + '%'; + this.updatePercent = newV; + }, + onShow() { + var options = { + duration: 1600, + easing: 'linear', + fill: 'forwards', + iterations: 'Infinity', + direction: 'normal', + }; + var frames = [ + { + transform: { + rotate: '0' } - }, - percentChange(newV, oldV) { - if (!this.isClock) { - this.isClock = true; + }, + { + transform: { + rotate: '360' } - this.updateText = newV + '%'; - this.updatePercent = newV; - }, - onShow() { - var options = { - duration: 1600, - easing: 'linear', - fill: 'forwards', - iterations: 'Infinity', - direction: 'normal', - }; - var frames = [ - { - transform: { - rotate: '0' - } - }, - { - transform: { - rotate: '360' - } - }, - ]; - this.animation = this.$element('progress-id').animate(frames, options); - var context = this; - this.animation.onfinish = function () { - context.updatePercent = 0; - }; - this.animation.onrepeat = function () { - if (context.isProgress) { - context.updatePercent = 0; - context.isProgress = false; - } else { - context.updatePercent = 20; - context.isProgress = true; - } - }; - }, - start() { - this.animation.play(); - }, - cancel() { - this.animation.cancel(); - }, - finish() { - this.animation.finish(); - } + }, + ]; + this.animation = this.$element('progress-id').animate(frames, options); + var context = this; + this.animation.onfinish = function () { + context.updatePercent = 0; + }; + this.animation.onrepeat = function () { + if (context.isProgress) { + context.updatePercent = 0; + context.isProgress = false; + } else { + context.updatePercent = 20; + context.isProgress = true; + } + }; + }, + start() { + this.animation.play(); + }, + cancel() { + this.animation.cancel(); + }, + finish() { + this.animation.finish(); + } } diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIcon.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIcon.js index 5f63333bfeb675004b20b3337fd584b7c79566a9..43d453febe2a282ba906723f43218f7ae39996c7 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIcon.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIcon.js @@ -61,9 +61,9 @@ export default { onReady() { }, clickFirstIcon() { - this.$emit('onClickLeftIcon', {}); + this.$emit('onLeftIconPressed', {}); }, clickSecondIcon() { - this.$emit('onClickRightIcon', {}); + this.$emit('onRightIconPressed', {}); }, } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/plainText/DeviceStatusCardText.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/plainText/DeviceStatusCardText.js index 9baa245bfbfc59e9f0e5abdc04c9f812038d99d9..2dd75ef01de84a82da9ff0f3963b3a1d00443e7d 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/plainText/DeviceStatusCardText.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/plainText/DeviceStatusCardText.js @@ -59,6 +59,6 @@ export default { onReady() { }, onChange() { - this.$emit('onClickText', {}); + this.$emit('onTextPressed', {}); } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIcon.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIcon.js index 19136b682984e1b6a983350b3573565605e73e27..9521c3f8b65839682f8350e1c35b9462f68d277f 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIcon.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIcon.js @@ -58,6 +58,6 @@ export default { onReady() { }, onChange() { - this.$emit('onClickIcon', {}); + this.$emit('onIconPressed', {}); } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.css b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.css deleted file mode 100644 index 689c16b8e213bde175f3f69f3688a995f0b2c72d..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.css +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -@import '../../../../../style/common.css'; - -.container { - flex: 1; - align-items: center; - width: 100%; - height: 88px; - padding-left: 16px; - padding-right: 16px; - border-radius: 16px; -} - -.container:disabled { - opacity: 0.4; -} - -.item-style { - height: 100%; - flex-direction: column; - justify-content: center; -} - -.item-icon-outer { - height: 40px; - border-radius: 30px; - justify-content: flex-end; - align-items: center; -} diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.hml deleted file mode 100644 index 54fc78d66f15ad8a6c563a2872ca0468081840bf..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.hml +++ /dev/null @@ -1,44 +0,0 @@ -<!-- - Copyright (c) 2021 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. - --> - -<div class='flex-row color-card-bg container' style="margin-top : 16px;" show="{{ showObj }}"> - <div class='item-style' style="width : 100%;"> - <text class='text-color-primary text-scale-18to14'> - {{ title }} - </text> - </div> - <div class='item-style' style="width : 100%; align-items : center;"> - <div show="{{ middleTitle != '' || subTitle != '' }}" class='flex-column' - style='justify-content : center; align-items : center;'> - <text class='text-color-primary text-scale-24to18' style='max-lines : 1;'> - {{ middleTitle }} - </text> - <text class='text-color-secondary text-scale-12to9' style='max-lines : 1; margin-top : 2px;' - show="{{ subTitle != '' }}"> - {{ subTitle }} - </text> - </div> - </div> - <div class='item-style' style="width : 100%; align-items : flex-end;"> - <div class="item-icon-outer" show="{{ rightText != '' }}" onclick="onChange()"> - <text class='text-scale-18to9 text-color-primary-activated'> - {{ rightText }} - </text> - </div> - </div> -</div> - - - diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.js deleted file mode 100644 index 9baa245bfbfc59e9f0e5abdc04c9f812038d99d9..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardText.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -import DeviceStatusCardParams from './DeviceStatusCardTextParams.js' -import DefaultValueOperator from '../../../scripts/defaultValueOperator.js' -import DeviceStateConstants from '../DeviceStateConstants' - -const JS_TAG = 'JS/Component/Device Status Card Text : ' -const showType = DeviceStateConstants.TEXT - -export default { - data: { - checkedID: 0, - title: '', - middleTitle: '', - subTitle: '', - rightText: '', - }, - props: ['type', 'data'], - computed: { - showObj() { - return showType == this.type; - }, - }, - onInit() { - this.$watch('data', 'onPropertyChange'); - if (this.data == undefined) { - return - } - let parsedData = DeviceStatusCardParams.getDeviceStatusCardTextData(this.data); - console.debug(JS_TAG + 'parsedData = ' + JSON.stringify(parsedData)); - this.title = DefaultValueOperator.stringValue(parsedData.title, this.title); - this.subTitle = DefaultValueOperator.stringValue(parsedData.subTitle, this.subTitle); - this.middleTitle = DefaultValueOperator.stringValue(parsedData.middleTitle, this.middleTitle); - this.rightText = DefaultValueOperator.stringValue(parsedData.rightText, this.rightText); - }, - onPropertyChange() { - if (this.data == undefined) { - return - } - let parsedData = DeviceStatusCardParams.getDeviceStatusCardTextData(this.data); - this.title = DefaultValueOperator.stringValue(parsedData.title, this.title); - this.subTitle = DefaultValueOperator.stringValue(parsedData.subTitle, ''); - this.middleTitle = DefaultValueOperator.stringValue(parsedData.middleTitle, ''); - this.rightText = DefaultValueOperator.stringValue(parsedData.rightText, ''); - }, - onReady() { - }, - onChange() { - this.$emit('onClickText', {}); - } -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.d.ts b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.d.ts deleted file mode 100644 index 9e577d0d344d08eeb8239e781a63ea210607daa0..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -interface DeviceStatusCardTextData{ - middleTitle ?: string, - title : string, - subTitle ?: string, - rightText ?:string, -} -declare class DeviceStatusCardTextParams{ - public static getDeviceStatusCardTextData(data:DeviceStatusCardTextData):DeviceStatusCardTextData; -} -export default DeviceStatusCardTextParams; \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.js deleted file mode 100644 index e831d14d7bc87263934ae706081c4211e81eb027..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -class DeviceStatusCardTextParams { - static getDeviceStatusCardTextData(data){ - return data - } -} - -export default DeviceStatusCardTextParams; \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/buttons/buttons.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/buttons/buttons.js index ff26d75c75cd2fabc734bf332ca7c37cb14ddc0c..41f79ea32ddfa05b7c6259dd2ce4dda93572b310 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/buttons/buttons.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/buttons/buttons.js @@ -54,9 +54,9 @@ export default { this.rightButtonBgColor = DefaultValueOperator.stringValue(buttonConfig.rightButtonBgColor, this.rightButtonBgColor) }, onClickLeft() { - this.$emit('onClickLeft') + this.$emit('onLeftPressed') }, onClickRight() { - this.$emit('onClickRight') + this.$emit('onRightPressed') } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.hml index 49c40c86399fa28d264e5b8fda6ef45026d2e265..643cb2cfd1d45bac35d3ef1278f07f1eeb94ef85 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.hml @@ -37,8 +37,8 @@ config='{{ config }}'></info> <buttons config='{{ config }}' - @on-click-left='onClickLeft' - @on-click-right='onClickRight'></buttons> + @on-left-pressed='onClickLeft' + @on-right-pressed='onClickRight'></buttons> </div> </dialog> diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.js index f07303e6abfcd2f62618377649d41f8f19957433..a2e472bdf427f32aa4e665702e860553bbdfbda6 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBox.js @@ -67,18 +67,18 @@ export default { if (!this.itemCanClick) { return } - this.$emit('onClickItem', { + this.$emit('onItemPressed', { params: this.defaultIndex }) }, onClickLeft() { - this.$emit('onClickLeft', { + this.$emit('onLeftPressed', { params: this.defaultIndex }) this.$element('dialog-box').close(); }, onClickRight() { - this.$emit('onClickRight', { + this.$emit('onRightPressed', { params: this.defaultIndex }) }, diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBoxParams.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBoxParams.js index 477d4e7cfbc6aa3a027939a62a0146f4edce0750..1c349b2f63a3370aa6ab47f1d558a26c5c108d01 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBoxParams.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/dialogBox/DialogBoxParams.js @@ -17,30 +17,29 @@ const TEXT_PICKER = 0; const TEXT_LIST = 1; const INFO = 2; -class DialogBoxParams{ - - static getTextPickerConfig(config){ - config.type = TEXT_PICKER - return config - } - - static getTextPickerData(config) { - return config - } - - static getListSelectorConfig(config){ - config.type = TEXT_LIST - return config - } - - static getListSelectorData(config) { - return config - } - - static getInfoConfig(config) { - config.type = INFO - return config - } +class DialogBoxParams { + static getTextPickerConfig(config) { + config.type = TEXT_PICKER + return config + } + + static getTextPickerData(config) { + return config + } + + static getListSelectorConfig(config) { + config.type = TEXT_LIST + return config + } + + static getListSelectorData(config) { + return config + } + + static getInfoConfig(config) { + config.type = INFO + return config + } } export default DialogBoxParams; \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/listSelector.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/listSelector.hml index d3a0d042326d1cb0d011133fdc2076e0c4f7e519..8d3c98332ef81165f867243e5860f2d6594ebe58 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/listSelector.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/listSelector.hml @@ -25,7 +25,7 @@ inactive-icon='{{ inactiveIcon }}' active-icon='{{ activeIcon }}' default-index='{{ defaultIndex }}' - @on-click-item='onSingleSelect'></singleselect> + @on-item-pressed='onSingleSelect'></singleselect> <multiselect if='{{ mode == 1 }}' index='{{ index }}' @@ -33,7 +33,7 @@ inactive-icon='{{ inactiveIcon }}' active-icon='{{ activeIcon }}' default-index='{{ defaultIndex }}' - @on-click-item='onMultiSelect'></multiselect> + @on-item-pressed='onMultiSelect'></multiselect> </list-item> </list> \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/multiSelect/multiSelect.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/multiSelect/multiSelect.js index 2da7de53c250b976726810392fb3f73c5b20e8d4..2bb0f7d5c45ab3143ac029945b98b744eb738f66 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/multiSelect/multiSelect.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/multiSelect/multiSelect.js @@ -18,40 +18,33 @@ import {ITEM_HEIGHT_1, ITEM_HEIGHT_2} from '../listSelector.js'; export default { props: ['index', 'value', 'defaultIndex', 'inactiveIcon', 'activeIcon'], data: { - title: undefined, - subTitle: undefined, + title: '', + subTitle: '', selected: false, }, computed: { itemHeight() { - return this.subTitle ? ITEM_HEIGHT_2 : ITEM_HEIGHT_1 + return this.subTitle ? ITEM_HEIGHT_2 : ITEM_HEIGHT_1; }, }, onInit() { - this.$watch('value', 'valueUpdate') - this.$watch('defaultIndex', 'defaultIndexUpdate') - this.initValue() - this.initDefaultIndex() - }, - valueUpdate(newV, oldV) { - this.data = newV - this.initValue() - }, - defaultIndexUpdate(newV, oldV) { - this.initDefaultIndex() + this.$watch('value', 'initValue'); + this.$watch('defaultIndex', 'initDefaultIndex'); + this.initValue(); + this.initDefaultIndex(); }, initValue() { if (this.value == undefined) { - return + return; } - this.title = this.$t(this.value.title) - this.subTitle = this.$t(this.value.subTitle) + this.title = this.$t(this.value.title); + this.subTitle = this.$t(this.value.subTitle); }, initDefaultIndex() { - this.selected = this.defaultIndex.indexOf(this.index) >= 0 + this.selected = this.defaultIndex.indexOf(this.index) >= 0; }, onClickItem(index) { - this.$emit('onClickItem', { + this.$emit('onItemPressed', { index: index, }) }, diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/singleSelect/singleSelect.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/singleSelect/singleSelect.js index b4f1cf32b31c11532693a1500846ed9282083234..f67810e870de09c5b4c7e3f405fdb20b568807cf 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/singleSelect/singleSelect.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/listSelector/singleSelect/singleSelect.js @@ -18,44 +18,38 @@ import {ITEM_HEIGHT_1, ITEM_HEIGHT_2} from '../listSelector.js'; export default { props: ['index', 'value', 'defaultIndex', 'inactiveIcon', 'activeIcon'], data: { - title: undefined, - subTitle: undefined, + title: '', + subTitle: '', selected: false, }, computed: { itemHeight() { - return this.subTitle ? ITEM_HEIGHT_2 : ITEM_HEIGHT_1 + return this.subTitle ? ITEM_HEIGHT_2 : ITEM_HEIGHT_1; }, }, onInit() { - this.$watch('value', 'valueUpdate') - this.$watch('defaultIndex', 'defaultIndexUpdate') - this.initValue() - this.initDefaultIndex() - }, - valueUpdate(newV, oldV) { - this.initValue() - }, - defaultIndexUpdate(newV, oldV) { - this.initDefaultIndex() + this.$watch('value', 'initValue'); + this.$watch('defaultIndex', 'initDefaultIndex'); + this.initValue(); + this.initDefaultIndex(); }, initValue() { if (this.value == undefined) { - return + return; } - this.title = this.$t(this.value.title) - this.subTitle = this.$t(this.value.subTitle) + this.title = this.$t(this.value.title); + this.subTitle = this.$t(this.value.subTitle); }, initDefaultIndex() { if (this.defaultIndex == undefined) { - this.selected = false + this.selected = false; } else { - this.selected = this.index == this.defaultIndex[0] + this.selected = this.index == this.defaultIndex[0]; } }, onClickItem(index) { - this.$emit('onClickItem', { + this.$emit('onItemPressed', { index: [index], - }) + }); }, } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/title/title.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/title/title.js index e9a9b1e5c6d46fe0e1a033603c769da3bd1f3d92..d011c69e0d14c75d97b78fedef6c22b1cc683876 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/title/title.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/dialog/title/title.js @@ -16,25 +16,22 @@ export default { props: ['config'], data: { - title: undefined, - subTitle: undefined, + title: '', + subTitle: '', }, onInit() { - this.$watch('config', 'configUpdate') - this.initConfig() - }, - configUpdate(newV, oldV) { - this.config = newV + this.$watch('config', 'initConfig'); + this.initConfig(); }, initConfig() { if (this.config == undefined) { - return + return; } - let titleConfig = this.config.titleConfig + let titleConfig = this.config.titleConfig; if (titleConfig == undefined) { - return + return; } - this.title = this.$t(titleConfig.title) - this.subTitle = this.$t(titleConfig.subTitle) + this.title = this.$t(titleConfig.title); + this.subTitle = this.$t(titleConfig.subTitle); } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.css b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.css deleted file mode 100644 index 482b6886e38fb64d6846acbe64f3840b69e8f59b..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.css +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -@import '../../../../style/common.css'; - -.good-service-select { - align-items: center; - justify-content: space-between; - margin-bottom: 8px; - margin-top: 24px; -} - -.image-arrow_right { - width: 12px; - height: 25px; -} - -.item-style-wrap { - margin-right: 8px; -} - -.item-style-wrap-last { -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.hml deleted file mode 100644 index 228243dfea5cd5014c346da0b401e501ec297df9..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.hml +++ /dev/null @@ -1,35 +0,0 @@ -<!-- - Copyright (c) 2021 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. - --> - -<element name='featuredItem' src='./featuredItem/FeaturedItem.hml'></element> - -<div style='flex-direction : column;' show='{{ showObject }}'> - <div class='good-service-select' onclick='showAllServices' show='{{ displayServices.length > 0 }}' - disabled='{{ abilityList.length < showServicesCount }}'> - <text class='text-size-heading6'>{{ $t('strings.public_more_service') }}</text> - <image class='image-arrow_right' src='{{ arrowRightImagePath }}' - show='{{ abilityList.length > showServicesCount }}'></image> - </div> - - <div> - <div class='{{ getItemStyleByIndex($item.index) }}' for='{{ displayServices }}'> - <featuredItem - width='164px' - height='164px' - item='{{ $item }}'> - </featuredItem> - </div> - </div> -</div> \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.js deleted file mode 100644 index 920db262851a2dd1b6f9a7e0dda69d783d2ad26d..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/FeaturedCard.js +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -import fetch from '@system.fetch' -import configuration from '@system.configuration'; -import device from '@system.device'; -import app from '@system.app'; -import router from '@system.router'; -import centralOperator from '../../scripts/centralOperator' -import config from '../../../../share/common/config.js' -import DefaultValueOperator from '../../scripts/defaultValueOperator.js' - -const JS_TAG = 'JS/Component/Service card: '; -export const SHOW_SERVICES_COUNT = 2; -export const SHOW_DEVICES_COUNT = 4; -export const TYPE_SERVICES = 0; -export const TYPE_DEVICES = 1; -const LIMIT_COUNT = 1000; // Specifies the length of the subscription list to be obtained. The pair value is 20 -const DETAIL_HEAD_TYPE = 'SubscribeIntentRequest'; -const PRODUCT_PACKAGE = 'HAG-product-package'; -const BASE_URL = 'HAG-host-name'; -const SUBSCRIBE_INFO_URL = BASE_URL + '/user-ability/v1/candidate-abilities/products/query'; -const ABILITY_DETAIL_URL = BASE_URL + '/user-inquiry/v1/dist-abilities/inquiry'; -const CONST_VERSION = 'version'; -const CONST_CATEGORY = 'category'; -const CONST_SCENE = 'scene'; -const CONST_CROWD = 'crowd'; -const CONST_MATCHING = 'matching'; -const DEFAULT_IMAGE_PATH = '/common/img/base/ic_public_arrow_right.png'; - -export default { - props: { - showObject: false, - }, - data: { - aarrowRightImagePath: DEFAULT_IMAGE_PATH, - language: undefined, - appBaseInfo: {}, - commonHeader: {}, - terminalInfo: {}, - commonServiceIdList: [], - deviceServiceIdList: [], - abilityList: [], - deviceList: [], - displayServices: [], - showServicesCount: SHOW_SERVICES_COUNT, - serviceImageWidth: undefined, - serviceImageHeight: undefined, - }, - onInit() { - console.info(JS_TAG + 'onInit'); - this.arrowRightImagePath = - DefaultValueOperator.imgPath(this.arrowRightImagePath, DEFAULT_IMAGE_PATH, this.$app.$def.globalData.isDarkMode); - let localeInfo = configuration.getLocale(); - this.language = localeInfo.language + '_' + localeInfo.countryOrRegion; - this.initAppSystemInfo(); - }, - initAppSystemInfo() { - var info = app.getInfo(); - console.debug(JS_TAG + 'Get app info = ' + JSON.stringify(info)); - this.appBaseInfo.versionName = info.versionName; - this.appBaseInfo.versionCode = info.versionCode; - let self = this; - try { - device.getInfo({ - success: function (data) { - console.info(JS_TAG + 'Device information obtained successfully. Device brand:' + JSON.stringify(data)); - self.appBaseInfo.brand = data.brand; - self.appBaseInfo.product = data.product; - self.appBaseInfo.model = data.model; - self.appBaseInfo.deviceType = data.deviceType; - self.appBaseInfo.region = data.region; - self.onInitInfoSuccess(); - }, - fail: function (data, code) { - console.error(JS_TAG + 'Device information obtained failed. Error code:' + code + '; Error information: ' + - JSON.stringify(data)); - self.appBaseInfo.brand = data.brand; - self.appBaseInfo.product = data.product; - self.appBaseInfo.model = data.model; - self.appBaseInfo.deviceType = data.deviceType; - self.appBaseInfo.region = data.region; - self.onInitInfoSuccess(); - }, - }); - } catch (e) { - console.error(JS_TAG + 'initAppSystemInfo Device getInfo error: ' + e); - } - }, - onInitInfoSuccess() { - try { - centralOperator.getUniqueId({ - success(response) { - console.debug(JS_TAG + 'getUniqueId: ' + JSON.stringify(response)); - if (response.data.uniqueId) { - this.appBaseInfo.uniqueId = response.data.uniqueId; - } else { - this.appBaseInfo.uniqueId = this.$app.$def.globalData.bundleName; - console.error(JS_TAG + 'getUniqueId uniqueId is empty'); - } - this.initRequestInfo(); - }, - fail(code, err) {}, - }); - } catch (e) { - console.error(JS_TAG + 'getUniqueId error = ' + e); - } - }, - initRequestInfo() { - // init the request header - this.commonHeader = { - 'x-hag-trace-id': this.$app.$def.globalData.bundleName + '_' + Date.parse(new Date()), - 'x-udid': this.appBaseInfo.uniqueId, - 'x-device-id': this.appBaseInfo.uniqueId, - 'x-client-version': PRODUCT_PACKAGE + '_' + this.appBaseInfo.versionName, - 'x-prd-pkg-name': PRODUCT_PACKAGE, - 'Content-Type': 'application/json' - } - console.debug(JS_TAG + 'this.commonHeader = ' + JSON.stringify(this.commonHeader)); - // init the request body of subscription query - this.terminalInfo = { - 'prdVer': this.appBaseInfo.versionName, - 'language': this.language, - 'locale': this.language, - 'countryCode': this.appBaseInfo.region, - 'phoneType': this.appBaseInfo.product, - 'deviceType': this.appBaseInfo.deviceType.toUpperCase(), - 'sysVer': 'EMUI11', - 'deltaPlatformVer': this.appBaseInfo.versionCode - } - console.debug(JS_TAG + 'this.terminalInfo = ' + JSON.stringify(this.terminalInfo)); - - this.getSubscribeInfo(); - }, - onInquiryResult(isSuccess) { - if (!isSuccess) { - console.error(JS_TAG + 'inquiry failed.'); - return; - } - this.refreshCard(); - }, - refreshCard() { - if (!this.abilityList || this.abilityList.length == 0) { - console.error(JS_TAG + 'abilityList is empty'); - this.displayServices = []; - return; - } - if (this.abilityList.length <= SHOW_SERVICES_COUNT) { - this.displayServices = this.abilityList; - for (let i = 0; i < this.displayServices.length; i++) { - this.displayServices[i].index = i; - } - } else { - for (let i = 0; i < SHOW_SERVICES_COUNT; i++) { - let service = this.abilityList[i]; - service.index = i; - this.displayServices.push(service); - } - } - console.info(JS_TAG + 'this.services = ' + JSON.stringify(this.displayServices) ); - }, - getSubscribeInfo() { - let GET_SUB_INFO = JS_TAG + 'get subscribe info(): '; - let self = this; - console.debug(GET_SUB_INFO + 'requestUrl = ' + SUBSCRIBE_INFO_URL + ', commonHeader = ' + JSON.stringify(self - .commonHeader)); - fetch.fetch({ - url: SUBSCRIBE_INFO_URL, - method: 'POST', - header: this.commonHeader, - data: { - 'terminalInfo': this.terminalInfo, - 'prdPkgName': PRODUCT_PACKAGE, - 'limit': LIMIT_COUNT - }, - success: function (response) { - self.onGetSubscribeSuccess(response); - }, - fail: function (msg) { - console.error(GET_SUB_INFO + 'fetch fail:' + msg + JSON.stringify(msg)); - } - }); - }, - onGetSubscribeSuccess(response) { - let self = this; - let TAG = JS_TAG + 'onGetSubscribeSuccess: '; - try { - console.debug(TAG + 'getSubscribeInfo success====>' + JSON.stringify(response)); - if (!response || !response.data) { - console.error(TAG + 'response is empty'); - return; - } - let abilities = JSON.parse(response.data).candidateAbilityDetailList; - if (!abilities) { - console.error(TAG + 'abilities empty'); - return; - } - for (let index of Object.keys(abilities)) { - if (abilities[index] && abilities[index].ability) { - const ability = abilities[index].ability; - self.commonServiceIdList.push(ability.abilityId); - } else { - console.error(TAG + 'ability is empty'); - } - } - if (!self.commonServiceIdList) { - console.error(TAG + 'commonServiceIdList is empty'); - } else { - if (self.commonServiceIdList.length > 0) { - self.inquiryAbility(self.commonServiceIdList); - } - } - } catch (e) { - console.error(TAG + 'services onResult error:' + e); - } - }, - inquiryAbility(identifierList) { - let INQUIRY_ABILITY_TAG = JS_TAG + ' inquiry ability(): '; - let requestBody = this.getInquiryRequestBody(identifierList); - if (!requestBody) { - console.error(INQUIRY_ABILITY_TAG + 'requestBody is empty'); - return; - } - let self = this; - fetch.fetch({ - url: ABILITY_DETAIL_URL, - method: 'POST', - header: this.commonHeader, - data: requestBody, - success: function (response) { - try { - console.info(INQUIRY_ABILITY_TAG + 'inquiry success====>' + JSON.stringify(response)); - if (!response) { - console.error(INQUIRY_ABILITY_TAG + 'response is empty'); - return; - } - let resultIntents = JSON.parse(response.data).resultIntents; - if (!resultIntents) { - console.error(INQUIRY_ABILITY_TAG + 'inquiry ability resultIntents is empty, stop parse data'); - return; - } - console.debug(INQUIRY_ABILITY_TAG + 'inquiry ability resultIntents len = ' + JSON.stringify(resultIntents.length)); - self.parseData(resultIntents); - } catch (e) { - self.onInquiryResult(false); - console.error(INQUIRY_ABILITY_TAG + e) - } - self.onInquiryResult(true); - }, - fail: function (msg) { - console.error(INQUIRY_ABILITY_TAG + 'inquiry ability detail fail: ' + JSON.stringify(msg)); - self.onInquiryResult(false); - } - }); - }, - getInquiryRequestBody(identifierList) { - let queryIntents = this.getInquireIntents(identifierList); - if (!queryIntents || queryIntents.length == 0) { - return ''; - } - var data = { - 'header': { - 'type': DETAIL_HEAD_TYPE - }, - 'endpoint': { - 'device': { - 'deviceId': this.appBaseInfo.uniqueId - }, - 'locale': this.language - }, - 'inquire': { - 'intents': queryIntents - } - } - console.debug(JS_TAG + 'get inquiry request body = ' + JSON.stringify(data)); - return data; - }, - getInquireIntents(identifierList) { - var inquireIntents = []; - try { - if (identifierList == null || identifierList.length == 0) { - console.error(JS_TAG + 'get InquireIntents identifierList is empty '); - return; - } - for (let index of Object.keys(identifierList)) { - let element = { - 'selectMode': 'DIRECT_EXECUTE', - 'intentSN': index, - 'channel': '0', - 'intentAbilities': [{ - 'abilityId': identifierList[index], - 'slots': this.getCustomSlots() - }] - } - inquireIntents.push(element); - } - console.debug(JS_TAG + 'get inquireIntents = ' + JSON.stringify(inquireIntents)); - } catch (e) { - console.error(JS_TAG + 'get inquireIntents exception = ' + e); - return; - } - return inquireIntents; - }, - getCustomSlots() { - let filter = {}; - filter.version = this.getSlotItem(CONST_VERSION, config.filterValue.version, null); - filter.scene = this.getSlotItem(CONST_SCENE, config.filterValue.scene, null); - filter.category = this.getSlotItem(CONST_CATEGORY, config.filterValue.category, null); - filter.crowd = this.getSlotItem(CONST_CROWD, config.filterValue.crowd, null); - filter.matching = this.getSlotItem(CONST_MATCHING, config.filterValue.matching, null); - - console.info(JS_TAG + 'get custom slots = ' + JSON.stringify(filter)); - return filter; - }, - getSlotItem(filterType, value, extendValue) { - return { - 'name': filterType, - 'values': [ - { - 'origin': value, - 'real': value, - 'extendValue': extendValue - } - ] - }; - }, - parseData(resultIntents) { - let PARSE_TAG; - for (let index of Object.keys(resultIntents)) { - PARSE_TAG = JS_TAG + ' index-' + index + ' parseData: '; - if (resultIntents[index].abilities && resultIntents[index].abilities[0]) { - let firstAbility = resultIntents[index].abilities[0]; - let commands = firstAbility.commands; - if (commands && commands[0] && commands[0].body) { - console.debug(PARSE_TAG + 'abilityId-commands = ' + firstAbility.ability.ability.abilityId + ' ' + - JSON.stringify(commands)); - this.parseServiceDetail(index, firstAbility, commands[0].body); - } else { - console.error(PARSE_TAG + 'commands or body is empty'); - } - } else { - console.error(PARSE_TAG + 'abilities is empty'); - } - } - }, - parseServiceDetail(index, firstAbility, commandsBody) { - const PARSE_TAG = JS_TAG + index + '-index parseCommonSubscribeData: '; - let info = firstAbility.ability.ability; - console.debug(PARSE_TAG + 'info = ' + JSON.stringify(info)); - - if (!commandsBody || !commandsBody.interaction || !commandsBody.interaction[0]) { - console.error(PARSE_TAG + 'ability commandsBody is empty'); - return; - } - let interaction = commandsBody.interaction[0]; - console.debug(PARSE_TAG + 'getContents interaction element = ' + JSON.stringify(interaction)); - - let abilityInfo = {}; - abilityInfo.index = index; - abilityInfo.abilityId = info.abilityId; - abilityInfo.name = info.name; - abilityInfo.iconUrl = info.iconUrl; - abilityInfo.brief = interaction.brief; - abilityInfo.appLinkType = interaction.appLinkType; - abilityInfo.linkUrl = interaction.linkUrl; - abilityInfo.packageName = interaction.packageName; - abilityInfo.serviceName = interaction.serviceName; - if (interaction && interaction.abilityForms) { - let firstAbilityForm = interaction.abilityForms[0] - if (firstAbilityForm) { - abilityInfo.snapshotUrl = firstAbilityForm.snapshotUrl - } - } - this.abilityList.push(abilityInfo); - console.debug(PARSE_TAG + 'this.abilityList = ' + JSON.stringify(this.abilityList)); - }, - showAllServices() { - console.info(JS_TAG + 'showAllServices onClick'); - router.push({ - uri: 'pages/services/services', - params: { - data: this.abilityList, - type: TYPE_SERVICES - } - }); - }, - getItemStyleByIndex(idx) { - if (idx == SHOW_SERVICES_COUNT - 1) { - return 'item-style-wrap-last'; - } - return 'item-style-wrap'; - }, -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.css b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.css deleted file mode 100644 index aa296fc721efb65f8f8b4be7febfe4c679d634e0..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.css +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -@import '../../../../../style/common.css'; - -.container { - margin-top: 8px; - margin-bottom: 8px; -} - -.title-style { - width: 100%; - height: 20px; - text-align: center; - max-lines: 1; - text-padding: 0px; - margin-top: 6px; -} - -@media (dark-mode: true) { - .stack2-bg { - background-color: #2E3033; - } -} - diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.hml deleted file mode 100644 index e7c0d4fc38a373e04952fab97b0ceeb5e0bd2939..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.hml +++ /dev/null @@ -1,23 +0,0 @@ -<!-- - Copyright (c) 2021 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. - --> - -<div class='flex-column container' style='width : {{ imageWidth }};' onclick='onClickItem'> - <div class='center' style='border-radius : 12px; width : {{ imageWidth }}; height : {{ imageHeight }};'> - <image style="border-radius : 12px;" - alt='{{ placeHolderImagePath }}' - src='{{ item.snapshotUrl ? item.snapshotUrl : item.iconUrl }}'/> - </div> - <text class='text-color-primary text-scale-14to12 title-style'>{{ item.name }}</text> -</div> diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.js deleted file mode 100644 index f936f6b986c0c8c80a18dee40b89be78ef4b4cc7..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/featuredCard/featuredItem/FeaturedItem.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -import centralOperator from '../../../scripts/centralOperator' -import DefaultValueOperator from '../../../scripts/defaultValueOperator.js' - -const JS_TAG = 'JS/Component/Service Item: '; -const FLAG_INSTALL_ON_DEMAND = 2048; -const FLAG_ABILITY_NEW_MISSION = 268435456; -const APP_LINK_TYPE = { - TYPE_URL: 0, - TYPE_RPK: 1, - TYPE_H5: 2, - TYPE_APP: 3, - TYPE_FA: 4 -} -const DEFAULT_IMAGE_PLACE_HOLDER = '/common/img/base/ic_public_picture.png'; - -export default { - props: ['width', 'height', 'item'], - data: { - imgStyle: '', - placeHolderImagePath: '/common/img/base/ic_public_picture.png', - }, - computed: { - imageWidth() { - return this.width ? this.width : '78px' - }, - imageHeight() { - return this.height ? this.height : '78px' - } - }, - onInit() { - this.placeHolderImagePath = DefaultValueOperator.imgPath(this.imagePath, DEFAULT_IMAGE_PLACE_HOLDER, this.$app.$def.globalData.isDarkMode); - }, - onClickItem() { - console.debug(JS_TAG + 'onServiceClick data= ' + JSON.stringify(this.item)); - switch (this.item.appLinkType) { - case APP_LINK_TYPE.TYPE_URL: - case APP_LINK_TYPE.TYPE_RPK: - case APP_LINK_TYPE.TYPE_H5: - case APP_LINK_TYPE.TYPE_APP: - console.debug(JS_TAG + 'this.item.appLinkType = ' + this.item.appLinkType); - centralOperator.openUrl({ - url: this.item.linkUrl, - success(response) {}, - fail(code, err) {}, - }); - break; - case APP_LINK_TYPE.TYPE_FA: - centralOperator.startAbility({ - bundleName: this.item.packageName, - abilityName: this.item.serviceName, - intentParams: {}, - intentOptions: { - flags: FLAG_INSTALL_ON_DEMAND | FLAG_ABILITY_NEW_MISSION - }, - success(response) {}, - fail(code, err) {}, - }); - break; - default: - console.debug(JS_TAG + 'other situations, this.item.appLinkType = ' + this.item.appLinkType); - break; - } - } -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.css b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.css index cf0d40aa82f46fdba7dde9d9279d5b876b904c0f..13d2b778b40c815e634243230654770e988be1d5 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.css +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.css @@ -16,6 +16,7 @@ @import '../../../../style/common.css'; .card-common { + width: 100%; margin-top: 8px; border-radius: 16px; height: 88px; diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.hml b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.hml index ddd469b506e2666852eae2c8792cbd9d60366fe7..0040dbf46c5cb7105b5e3178dee4d300f70f67c6 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.hml +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/InformationPanel.hml @@ -16,8 +16,8 @@ <div class='card-common color-card-bg' style='justify-content : space-between;'> <swiper if='{{ swiperEnabled }}' style='indicator-bottom : 0px;'> - <div> - <div class='flex-column center' + <div style='margin-top: 15px;'> + <div class='flex-column center' style="width: 100%;" for='{{ resultConfigPage1 }}'> <div if='{{ $idx != 0 }}' class='divider-box'> <divider vertical='true' class='color-divider' style='height : 24px;'></divider> @@ -32,8 +32,8 @@ </div> </div> - <div> - <div class='flex-column center' + <div style='margin-top: 15px;'> + <div class='flex-column center' style="width: 100%;" for='{{ resultConfigPage2 }}'> <div if='{{ $idx != 0 }}' class='divider-box'> <divider vertical='true' class='color-divider' style='height : 24px;'></divider> @@ -49,7 +49,7 @@ </div> </swiper> - <div else class='flex-column center' + <div else class='flex-column center' style="width: 100%; margin-top: 15px;" for='{{ resultConfigPage1 }}'> <div if='{{ $idx != 0 }}' class='divider-box'> <divider vertical='true' class='color-divider' style='height : 24px;'></divider> diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/CustomizedInformationPanelParams.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/CustomizedInformationPanelParams.js index 353660f113fdc3de8c68af9fb4d960fcbba7005f..2a4227fb54bdd16b75bf4ed76991886caf87b546 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/CustomizedInformationPanelParams.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/CustomizedInformationPanelParams.js @@ -13,7 +13,6 @@ * limitations under the License. */ - class CustomizedInformationPanelParams { static getConfig(config) { diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/dataTransformer.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/dataTransformer.js deleted file mode 100644 index bc2fc8bbdd77fc839209eeda72c446a0b88557ea..0000000000000000000000000000000000000000 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/informationPanel/customizedInformationPanel/dataTransformer.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -import state from './state.js'; -import CustomizedInformationPanelParams from './CustomizedInformationPanelParams.js'; - -export default { - customizedInformationPanelConfig() { - return CustomizedInformationPanelParams.getConfig({ - column: 3 - }); - }, - customizedInformationPanelTitle() { - let v = { - date: '9月5日', - result: '健康指数:91分' - }; - return CustomizedInformationPanelParams.getTitleConfig({ - subTitle: v.date + ' ' + v.result - }); - }, - customizedInformationPanelRouter() { - let params = [1, 2, 3]; - return CustomizedInformationPanelParams.getRouter({ - uri: 'pages/services/services', - params: params, - }); - }, - customizedInformationPanelData() { - // 模拟接口数据转组件数据 - let result = [0, 1, 2, 3, 4, 5, 6, 7, 8]; - - let data = result.reduce((arr, v) => { - if (v == 1) { - let item = CustomizedInformationPanelParams.getItem({ - value: '正常', - description: 'D' + v, - type: state.TYPE.HEALTHY, - }); - arr.push(item); - } else if (v == 2) { - let item = CustomizedInformationPanelParams.getItem({ - value: '偏高', - description: 'D' + v, - type: state.TYPE.HIGH - }); - arr.push(item); - } else if (v == 3) { - let item = CustomizedInformationPanelParams.getItem({ - value: '高', - description: 'D' + v, - type: state.TYPE.OVERWEIGHT - }); - arr.push(item); - } else { - let item = CustomizedInformationPanelParams.getItem({ - value: 'V' + v, - unit: 'bmp', - description: 'D' + v, - }); - arr.push(item); - } - return arr; - }, []); - - return CustomizedInformationPanelParams.getData({ - items: data - }); - } -} \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBar.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBar.js index 4928c997b93c1ec9a8b5c06d202da397e8af9a97..782588859791030a1d877de300be84586eb814dd 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBar.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBar.js @@ -15,7 +15,6 @@ import TitleBarParams from './TitleBarParams' import router from '@system.router' -import mediaquery from '@system.mediaquery'; const JS_TAG = 'JS/Component/Title bar: '; diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBarParams.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBarParams.js index deca15e92538d11e753eba4fb5e381cc82bce182..eda87f51f5fcb5e606cf590a29434900ed2c1947 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBarParams.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/TitleBarParams.js @@ -13,10 +13,10 @@ * limitations under the License. */ -class TitleBarParams{ - static getTitleBarConfig(config){ - return config - } +class TitleBarParams { + static getTitleBarConfig(config) { + return config + } } export default TitleBarParams; \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/optionsMenu/optionsMenuParams.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/optionsMenu/optionsMenuParams.js index 5acb22fcf03fa7a54e81649024d1d8658d905075..db934d094f78b523f59dfa635177f51d5ed86fe5 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/optionsMenu/optionsMenuParams.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/components/titleBar/optionsMenu/optionsMenuParams.js @@ -14,9 +14,9 @@ */ class OptionsMenuParams { - static getData(data) { - return data; - } + static getData(data) { + return data; + } } export default OptionsMenuParams; diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/config.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/config.js index 762187f582fb8308a5739878de7d55303835bb61..aeb2286b4d2548e10e47a861f4e6b35c4be2a40e 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/config.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/config.js @@ -14,24 +14,37 @@ */ const data = { + // 帐号授权域列表 requireScopeList: [ - 'email' ], + // 必要帐号授权域列表,用户若未全部授予,则无法完成登录进行后续操作 mandatoryScopeList: [ ], + // 应用中OAuth 2.0客户端ID(凭据)的Client ID,在创建应用后由华为开发者联盟为应用分配的唯一标识。 + clientId: '123456789', + // 回调地址,用于应用服务器在获取用户授权后接收Authorization Code和获取凭证Access Token。 + redirectUri: 'http://127.0.0.1', + // 应用中OAuth 2.0客户端ID(凭据)的Client Secret,在创建应用后由华为开发者联盟为应用分配公钥。 + clientSecret: '1234567812345678123456781234567812345678123456781234567812345678', + // 动态申请的系统权限列表 permissions: [ - 'ohos.permission.LOCATION' + 'ohos.permission.LOCATION' ], + // 必须获取的动态权限,若用户拒绝,则跳转到连接失败页面 mandatoryPermissions: ['ohos.permission.LOCATION'], + // toast弹窗显示时长,单位为毫秒 toastDuration: 5000, + // 连接设备前是否需要进行扫描的标识 scanRequired: false, + // 连接设备前是否需要进行智慧生活代理注册的标识 proxyRegisterRequired: false, + // 配对过程中需要注册监听的服务UUID serviceUuid: '00000000-0000-0000-0000-000000000000', + // 配对过程中需要注册监听的特征值UUID characterUuid: '00000000-0000-0000-0000-000000000000', + // 扫描时对设备广播的服务进行过滤,当且仅当设备广播的服务在过滤列表中才上报,该字段设置为空代表不过滤 scanFilterUuid:['00000000-0000-0000-0000-000000000000'], - clientId: '123456789', - redirectUri: 'http://127.0.0.1', - clientSecret: '1234567812345678123456781234567812345678123456781234567812345678', + // 默认的调试数据,用于本地拉起应用时替代NFC标签所传入的必要参数 customDefaultData: { productId: 'A001', deviceMac: '00:00:00:00:00:00' diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/dataParser.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/dataParser.js index e3b5f2cffa9e046082a1bf1b9b04defba0571a15..fcbb58df0d53cd7495733c9f0e7c028867411395 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/dataParser.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/dataParser.js @@ -15,7 +15,7 @@ const JS_TAG = 'JS/Common/Data Parser: '; -export default{ +export default { dealWithCharacteristicValue(deviceId, characteristicId, rawData) { }, } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/HuaweiAccount.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/HuaweiAccount.js index ca0bd17036a281a03026be10ca17685e01740d71..7d0ef005de566c1800e3ee2611fb53e8428b8ec9 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/HuaweiAccount.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/HuaweiAccount.js @@ -13,13 +13,15 @@ * limitations under the License. */ -import fetch from '@system.fetch'; -import storage from '@system.storage'; +import http from '@ohos.net.http'; +import dataStorage from '@ohos.data.storage' +import featureAbility from '@ohos.ability.featureAbility' import config from '../config.js' import {HuaweiIdAuthParamsHelper, HuaweiIdAuthManager, Scope} from '@hmscore/hms-jsb-account' const TAG = 'JS/Connection/HuaweiAccount: ' const TokenURL = 'https://oauth-login.cloud.huawei.com/oauth2/v3/token' +const TokenCheckURL = 'https://oauth-api.cloud.huawei.com/rest.php?nsp_fmt=JSON&nsp_svc=huawei.oauth2.user.getTokenInfo' const REFRESH_TOKEN_EXPIRE_DATE = 180 const LOGIN_ERROR_CODE = { FAILED: -1, @@ -62,8 +64,9 @@ function signInError(error) { function RESTError(e) { // 错误码: https://developer.huawei.com/consumer/cn/doc/development/HMSCore-References/server-error-codes-0000001062371380 - let data = JSON.parse(e.data) - if (e.code == 400) { + console.error(TAG + 'restyError' + JSON.stringify(e)) + let data = JSON.parse(e.result) + if (e.responseCode == 400) { if (data.error == 6 || data.error == 102) { data.errorCode = ResultCode.ACCESS_TOKEN_EFFECT } else if (data.error == 1101 && (data.sub_error == 20155 || data.sub_error == 20156)) { @@ -92,6 +95,7 @@ function performSignIn() { .setProfile() .setScopeList(scopes) .setAuthorizationCode() + .setDialogAuth() .build(); HuaweiIdAuthManager.getAuthApi() .getSignInIntent(signInOption) @@ -126,52 +130,42 @@ function getAccessToken(authId) { redirect_uri: config.redirectUri, code: loginResult.authCode } - fetch.fetch({ - url: TokenURL, - header: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - data: formBody(body), - method: 'POST', - success: (rawTokenResult) => { - let tokenResult = JSON.parse(rawTokenResult.data); + let httpRequest = http.createHttp(); + httpRequest.request(TokenURL, + { + method: 'POST', + header: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' + }, + extraData: formBody(body), + }).then(data => { + if (data.responseCode == 200) { + console.debug(TAG + 'Get access token success!'); + let tokenResult = JSON.parse(data.result); loginResult.accessToken = tokenResult.access_token; loginResult.refreshToken = tokenResult.refresh_token; saveRefreshToken(loginResult.refreshToken) resolve(loginResult); - }, - fail: (data) => { + } else { reject(RESTError(data)); } - }); + }).catch(err => { + reject(err); + }) }); } -function saveRefreshToken(token) { +async function saveRefreshToken(token) { console.info(TAG + 'Start saving Refresh Token data.'); let date = new Date(); date.setDate(date.getDate() + REFRESH_TOKEN_EXPIRE_DATE); // Refresh token is valid in 180 days. However logout/auth cancel may revoke the token. - storage.set({ - key: 'rt_expire_timestamp', - value: date.getTime().toString(), - success: () => { - console.debug(TAG + 'Refresh Token expiration is saved.'); - }, - fail: (data, code) => { - console.error(TAG + 'Save Refresh Token expiration failed, error code:' + code + ', data: ' + data); - } - }); - storage.set({ - key: 'refresh_token', - value: token, - success: () => { - console.debug(TAG + 'Refresh Token is saved.'); - }, - fail: (data, code) => { - console.error(TAG + 'Save Refresh Token failed, error code:' + code + ', data: ' + data); - } - }); + var context = featureAbility.getContext(); + var path = await context.getFilesDir(); + let storage = dataStorage.getStorageSync(path + '/preferences') + storage.putSync('rt_expire_timestamp', date.getTime().toString()) + storage.putSync('refresh_token', token) + storage.flushSync(); } export default { @@ -181,32 +175,84 @@ export default { silentSignIn() { return performSilentSignIn().then(getAccessToken); }, - refreshAccessToken(successCallback, failCallback) { - storage.get({ - key: 'refresh_token', - success: (token) => { - let body = { - grant_type: 'refresh_token', - client_id: config.clientId, - client_secret: config.clientSecret, - refresh_token: token - } - fetch.fetch({ - url: TokenURL, - header: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - data: formBody(body), + checkScope(accessToken, scopeToCheck){ + return new Promise((resolve, reject)=>{ + console.error('Start check scope') + let body = { + access_token: accessToken, + } + let httpRequest = http.createHttp(); + httpRequest.request(TokenCheckURL, + { method: 'POST', - success: (data) => { - successCallback(JSON.parse(data.data)); + header: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, - fail: (data, code) => failCallback(RESTError(data), code) - }); - }, - fail: (data, code) => { - console.error(TAG + 'Refresh access token data failed, error code:' + code + ', data: ' + data); - } + extraData: formBody(body), + }).then(data => { + if (data.responseCode == 200) { + console.debug(TAG + 'Resolve access token success!' + data.result); + let tokenResult = JSON.parse(data.result); + let scopeList = tokenResult.scope.split(' '); + if (scopeList.some(scope => scope == scopeToCheck)) { + resolve(true); + } else { + let err = new Error('ScopeError') + reject(err); + } + } else { + let err = new Error('Rest Error') + err.message = data.result; + reject(err); + } + }).catch(err => { + reject(err); + }); }); + }, + requestSingleScope(scope){ + return new Promise((resolve, reject) => { + let signInOption = new HuaweiIdAuthParamsHelper().setId() + .setScope(new Scope(scope)) + .setAuthorizationCode() + .setDialogAuth() + .build(); + HuaweiIdAuthManager.getAuthApi() + .getSignInIntent(signInOption) + .then(resolve) + .catch(result => reject(signInError(result))); + }).then(getAccessToken) + }, + async refreshAccessToken(successCallback, failCallback) { + var context = featureAbility.getContext(); + var path = await context.getFilesDir(); + let storage = dataStorage.getStorageSync(path + '/preferences'); + let refreshToken = storage.getSync('refresh_token', ''); + if (refreshToken == '') { + return; + } + let httpRequest = http.createHttp(); + let body = { + grant_type: 'refresh_token', + client_id: config.clientId, + client_secret: config.clientSecret, + refresh_token: refreshToken + } + httpRequest.request(TokenURL, + { + method: 'POST', + header: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' + }, + extraData: formBody(body), + }).then(data => { + if (data.responseCode == 200) { + successCallback(JSON.parse(data.result)); + } else { + failCallback(RESTError(data), data.responseCode) + } + }).catch(err => { + failCallback(err.message, err.code) + }) } } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/abilityUtils.js similarity index 35% rename from OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.js rename to OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/abilityUtils.js index 0b233fcd9819336dff0336cf3844e628b785d366..ee5015c8c07acb7fed0e4d33f29cfcc3ff8c8f12 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/dashboard/pages/services/services.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/abilityUtils.js @@ -12,35 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +import featureAbility from '@ohos.ability.featureAbility'; +import wantConstant from '@ohos.ability.wantConstant'; -import router from '@system.router' -import TitleBarParams from '../../../share/common/components/titleBar/TitleBarParams'; -import {TYPE_SERVICES, TYPE_DEVICES, SHOW_SERVICES_COUNT, SHOW_DEVICES_COUNT -} from '../../../share/common/components/featuredCard/FeaturedCard.js'; +const JS_TAG = 'JS/Script/abilityUtils: '; +const KEY_FROM_APP = '&fromApp='; +const PROXY_REGISTER_URI = 'hilink://hilinksvc.huawei.com/device?action=deviceAdd&prodId='; +const INTENT_ACTION_VIEW = 'android.intent.action.VIEW'; export default { - data: { - data: [], - type: TYPE_DEVICES, + openUrl(url) { + let startAbilityParameter = { + want: { + action: INTENT_ACTION_VIEW, + uri: url, + }, + }; + console.info(JS_TAG + 'openUrl startAbilityParameter = ' + JSON.stringify(startAbilityParameter)); + return featureAbility.startAbility(startAbilityParameter); }, - onInit() { - if (this.type == TYPE_SERVICES) { - this.columnsNum = SHOW_SERVICES_COUNT - this.width = '164px' - this.height = '164px' - this.title = 'strings.public_more_service' - } else { - this.columnsNum = SHOW_DEVICES_COUNT - this.width = '76px' - this.height = '76px' - this.title = 'strings.public_devices_recommendation' - } - this.titleBarConfig = TitleBarParams.getTitleBarConfig( - { - title: this.$t(this.title) - }); + performProxyRegister (uuid, productId, bundleName) { + let startAbilityParameter = { + want: { + parameters: { + uuid: uuid, + }, + flag: wantConstant.Flags.FLAG_ABILITY_NEW_MISSION | wantConstant.Flags.FLAG_NOT_OHOS_COMPONENT, + uri: PROXY_REGISTER_URI + productId + KEY_FROM_APP + bundleName + }, + }; + console.info(JS_TAG + 'performProxyRegister startAbilityParameter = ' + JSON.stringify(startAbilityParameter)); + return featureAbility.startAbility(startAbilityParameter); }, - back: function () { - router.back(); - } -} \ No newline at end of file +} diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.d.ts b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.d.ts index e560b5541e4063267a659ed0925fee4d08c10ea9..ff082d3506f80045998a340a1ffa1327173f98c5 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.d.ts +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.d.ts @@ -30,45 +30,28 @@ interface PermissionStateInfo { grantedPermissions: string[]; requestedPermissions: string[]; } -interface IntentOptions { - flags: string; - action?: string; - uri?: string; - isTerminable?: boolean; -} -interface CheckPermissionRequest extends BaseRequest { +interface CheckPermissionData { permissions: string[]; } -interface PermissionRequest extends BaseRequest { +interface PermissionData { permissions: string[]; } -interface StartAbilityRequest extends BaseRequest { - bundleName: string; - abilityName: string; - intentParams: object; - intentOptions: IntentOptions; +interface AudioPlayData { + audioFileList: string[]; } -interface OpenUrlRequest extends BaseRequest { - url: string; +interface CheckPermissionRequest extends BaseRequest, CheckPermissionData { } -interface AudioPlayRequest extends BaseRequest { - audioFileList: string[]; +interface PermissionRequest extends BaseRequest, PermissionData { } -interface ProxyRegisterRequest extends BaseRequest { - uuid: string; - productId: string; +interface AudioPlayRequest extends BaseRequest, AudioPlayData { } declare class CentralOperator { private static getRequestAction; private static processOperation; - static checkPermission(object?: CheckPermissionRequest): Promise<BaseResponse>; + static checkPermission(request?: CheckPermissionRequest): Promise<BaseResponse>; static onPermissionRequest(callback: (object: PermissionInfo) => void): Promise<void>; - static requestPermission(object?: PermissionRequest): Promise<BaseResponse>; - static startAbility(object?: StartAbilityRequest): Promise<void>; - static openUrl(object?: OpenUrlRequest): Promise<void>; - static getUniqueId(object?: BaseRequest): Promise<void>; - static startAudioPlay(object?: AudioPlayRequest): Promise<void>; - static stopAudioPlay(object?: BaseRequest): Promise<void>; - static performProxyRegister(object?: ProxyRegisterRequest): Promise<void>; + static requestPermission(request?: PermissionRequest): Promise<BaseResponse>; + static startAudioPlay(request?: AudioPlayRequest): Promise<void>; + static stopAudioPlay(request?: BaseRequest): Promise<void>; } export default CentralOperator; diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.js index 7a30653e972e2fa398a805caee92c952364a8f13..b8a6ec72481ae39c951ee8aba24e3fef9ba0f36e 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/centralOperator.js @@ -42,12 +42,8 @@ var RequestCode; RequestCode[RequestCode["CHECK_PERMISSION"] = 2001] = "CHECK_PERMISSION"; RequestCode[RequestCode["ON_PERMISSION_REQUEST"] = 2002] = "ON_PERMISSION_REQUEST"; RequestCode[RequestCode["REQUEST_PERMISSION"] = 2003] = "REQUEST_PERMISSION"; - RequestCode[RequestCode["START_ABILITY"] = 2004] = "START_ABILITY"; - RequestCode[RequestCode["OPEN_URL"] = 2005] = "OPEN_URL"; - RequestCode[RequestCode["GET_UNIQUE_ID"] = 2006] = "GET_UNIQUE_ID"; RequestCode[RequestCode["START_AUDIO_PLAY"] = 2007] = "START_AUDIO_PLAY"; RequestCode[RequestCode["STOP_AUDIO_PLAY"] = 2008] = "STOP_AUDIO_PLAY"; - RequestCode[RequestCode["PERFORM_PROXY_REGISTER"] = 2009] = "PERFORM_PROXY_REGISTER"; })(RequestCode || (RequestCode = {})); var ResponseCode; (function (ResponseCode) { @@ -90,14 +86,14 @@ class CentralOperator { } }); } - static checkPermission(object) { + static checkPermission(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.CHECK_PERMISSION); let actionData = { - permissions: object.permissions, + permissions: request.permissions, }; action.data = actionData; - return this.processOperation(object, action); + return this.processOperation(request, action); }); } static onPermissionRequest(callback) { @@ -109,71 +105,30 @@ class CentralOperator { }); }); } - static requestPermission(object) { + static requestPermission(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.REQUEST_PERMISSION); let actionData = { - permissions: object.permissions, + permissions: request.permissions, }; action.data = actionData; - return this.processOperation(object, action); + return this.processOperation(request, action); }); } - static startAbility(object) { - return __awaiter(this, void 0, void 0, function* () { - let action = this.getRequestAction(RequestCode.START_ABILITY); - let actionData = { - bundleName: object.bundleName, - abilityName: object.abilityName, - intentParams: JSON.stringify(object.intentParams), - intentOptions: object.intentOptions, - }; - action.data = actionData; - this.processOperation(object, action); - }); - } - static openUrl(object) { - return __awaiter(this, void 0, void 0, function* () { - if (!object.url) { - console.error(TAG + 'actionData.url is empty or undefined'); - return; - } - let action = this.getRequestAction(RequestCode.OPEN_URL); - action.data = object.url; - this.processOperation(object, action); - }); - } - static getUniqueId(object) { - return __awaiter(this, void 0, void 0, function* () { - let action = this.getRequestAction(RequestCode.GET_UNIQUE_ID); - this.processOperation(object, action); - }); - } - static startAudioPlay(object) { + static startAudioPlay(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.START_AUDIO_PLAY); let actionData = { - audioFileList: object.audioFileList, + audioFileList: request.audioFileList, }; action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } - static stopAudioPlay(object) { + static stopAudioPlay(request) { return __awaiter(this, void 0, void 0, function* () { let action = this.getRequestAction(RequestCode.STOP_AUDIO_PLAY); - this.processOperation(object, action); - }); - } - static performProxyRegister(object) { - return __awaiter(this, void 0, void 0, function* () { - let action = this.getRequestAction(RequestCode.PERFORM_PROXY_REGISTER); - let actionData = { - registerUuid: object.uuid, - productId: object.productId, - }; - action.data = actionData; - this.processOperation(object, action); + this.processOperation(request, action); }); } } diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/defaultValueOperator.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/defaultValueOperator.js index 53a9e8edf836dc54c4c54ba4f307c5e1b47bfac1..d024b6f19be559cc023801693e4750b2106c3158 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/defaultValueOperator.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/scripts/defaultValueOperator.js @@ -13,44 +13,51 @@ * limitations under the License. */ -var stringValue = (value, defaultValue) => { - return (value == undefined || value == '') ? (defaultValue == undefined ? '' : defaultValue) : value; +var stringValue = (value, defaultValue) => { + return (value == undefined || value == '') ? (defaultValue == undefined ? '' : defaultValue) : value; } var booleanValue = (value, defaultValue) => { - return (value != undefined)? value : (defaultValue == undefined ? false : defaultValue) + return (value != undefined) ? value : (defaultValue == undefined ? false : defaultValue) } var numberValue = (value, defaultValue) => { - return value ? value : (defaultValue == undefined ? 0 : defaultValue) + return value ? value : (defaultValue == undefined ? 0 : defaultValue) } var arrayValue = (value, defaultValue) => { - return value ? value : (defaultValue == undefined) ? [] : defaultValue + return value ? value : (defaultValue == undefined) ? [] : defaultValue } var imgPath = (value, defaultValue, isDarkMode) => { - if (value == undefined || value == '') { - if (isDarkMode) { - return buildDarkImgPath(defaultValue) - } - return defaultValue - } else { - if (isDarkMode) { - return buildDarkImgPath(value) - } - return value + if (value == undefined || value == '') { + if (isDarkMode) { + return buildDarkImgPath(defaultValue) } + return defaultValue + } else { + if (isDarkMode) { + return buildDarkImgPath(value) + } + return value + } } var buildDarkImgPath = (imgPath) => { - let lastIndexPoint = imgPath.lastIndexOf('.') - let imgPathPrefix = imgPath.substring(0, lastIndexPoint) - let imgPathSuffix = imgPath.substring(lastIndexPoint, imgPath.length) - return imgPathPrefix.concat('_dark').concat(imgPathSuffix) + let lastIndexPoint = imgPath.lastIndexOf('.') + let imgPathPrefix = imgPath.substring(0, lastIndexPoint) + let imgPathSuffix = imgPath.substring(lastIndexPoint, imgPath.length) + return imgPathPrefix.concat('_dark').concat(imgPathSuffix) } -export default { stringValue, booleanValue, numberValue, arrayValue, imgPath, buildDarkImgPath}; +export default { + stringValue, + booleanValue, + numberValue, + arrayValue, + imgPath, + buildDarkImgPath +}; diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/common/state.js b/OpenHealthEcologyFA/entry/src/main/js/share/common/state.js index b9661e6e943e5b33081dce4087771584131af210..74ec5a0918b738d7fc193360009ba5d9114f3a43 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/common/state.js +++ b/OpenHealthEcologyFA/entry/src/main/js/share/common/state.js @@ -18,19 +18,19 @@ * 修改后,需要进入main/src/main/js/connection/common/components中, * 将对应组件中的showState修改增加需要显示的对应状态 */ -const data ={ - connection:{ - PRIVACY_CONTENT: 'PRIVACY_CONTENT', // 隐私协议内容界面 - PRIVACY: 'PRIVACY', // 隐私协议及登录页面 - PERMISSION_DENIED: 'PERMISSION_DENIED', // 权限禁用 - PERMISSION_FORBIDDEN: 'PERMISSION_FORBIDDEN', // 位置权限被禁止授予后,手动设置引导页面 - DISCOVERING: 'DISCOVERING', // 扫描中页面 - DISCOVER_FAILED: 'DISCOVER_FAILED', // 扫描失败页面 - CONNECTING: 'CONNECTING', // 连接中页面 - CONNECT_FAILED: 'CONNECT_FAILED', // 连接失败页面 - REDISCOVER_REQUESTED: 'REDISCOVER_REQUESTED', // 扫描失败,并已发起重新扫描请求 - RECONNECT_REQUESTED: 'RECONNECT_REQUESTED', // 连接失败,并已发起重连请求 - } +const data = { + connection: { + PRIVACY_CONTENT: 'PRIVACY_CONTENT', // 隐私协议内容界面 + PRIVACY: 'PRIVACY', // 隐私协议及登录页面 + PERMISSION_DENIED: 'PERMISSION_DENIED', // 权限禁用 + PERMISSION_FORBIDDEN: 'PERMISSION_FORBIDDEN', // 位置权限被禁止授予后,手动设置引导页面 + DISCOVERING: 'DISCOVERING', // 扫描中页面 + DISCOVER_FAILED: 'DISCOVER_FAILED', // 扫描失败页面 + CONNECTING: 'CONNECTING', // 连接中页面 + CONNECT_FAILED: 'CONNECT_FAILED', // 连接失败页面 + REDISCOVER_REQUESTED: 'REDISCOVER_REQUESTED', // 扫描失败,并已发起重新扫描请求 + RECONNECT_REQUESTED: 'RECONNECT_REQUESTED', // 连接失败,并已发起重连请求 + } } export default data; \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/i18n/en-US.json b/OpenHealthEcologyFA/entry/src/main/js/share/i18n/en-US.json index 84535341acca3835670b14b69b5ab388cbe7e42e..5c609a58ca163ae7e0b4a699ecb5ca4c9d140ab8 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/i18n/en-US.json +++ b/OpenHealthEcologyFA/entry/src/main/js/share/i18n/en-US.json @@ -2,10 +2,10 @@ "strings":{ "custom_FA_name":"XXX", "custom_company_name":"XXX Company", - "public_privacy_statement":"User Agreement and Privacy Statement", - "public_agree":"Agree with {statement}", - "public_login_Button_text":"Huawei Account Quick Login", - "public_login_hint": "Login with mobile number and authorization are required for continued use.", + "public_privacy_statement":"{faName} User Agreement and Privacy Statement", + "public_agree":"I agree with ", + "public_login_Button_text":"Quick Login with HUAWEI ID", + "public_login_hint": "Authorization is required. Please log in with your phone number.", "public_version": "Version", "public_network_error":"Network error. Try again later.", "public_system_error":"System error. Please try again.", @@ -81,7 +81,7 @@ "4.Manage your data" ], "A001": { - "device_name": "device XXX", + "device_name": "XXX device", "device_image": "/common/img/customised/A001/device.png", "menu_options": [ { @@ -129,7 +129,7 @@ "setting_items": [ { "label": "Device name", - "rightText": "device XXX" + "rightText": "XXX device" }, { "label": "About", diff --git a/OpenHealthEcologyFA/entry/src/main/js/share/i18n/zh-CN.json b/OpenHealthEcologyFA/entry/src/main/js/share/i18n/zh-CN.json index 684b18328832b760feee281945bd4e497bac608d..637d920db9a32298322d923e2b006fdcaf0bd6ae 100644 --- a/OpenHealthEcologyFA/entry/src/main/js/share/i18n/zh-CN.json +++ b/OpenHealthEcologyFA/entry/src/main/js/share/i18n/zh-CN.json @@ -2,8 +2,8 @@ "strings":{ "custom_FA_name":"XXX", "custom_company_name":"XXX公司", - "public_privacy_statement":"用户协议与隐私声明", - "public_agree": "同意{statement}", + "public_privacy_statement":"{faName}用户协议与隐私声明", + "public_agree": "同意", "public_login_Button_text":"华为帐号快捷登录", "public_login_hint": "继续使用需要授权并用手机号登录", "public_version": "版本", diff --git a/OpenHealthEcologyFA/entry/src/main/resources/base/element/string.json b/OpenHealthEcologyFA/entry/src/main/resources/base/element/string.json index 1012578d049cfbe8ad66392c6bffd6f7723cfb3c..c68d3b4c2e0bb2ad5bcfa0761183a1a20b917733 100644 --- a/OpenHealthEcologyFA/entry/src/main/resources/base/element/string.json +++ b/OpenHealthEcologyFA/entry/src/main/resources/base/element/string.json @@ -17,12 +17,12 @@ "value": "No Internet connection." }, { - "name": "main_JumpAbility", - "value": "Atomic Service demo Jump Ability" + "name": "reason_location", + "value": "Searching for available bluetooth devices" }, { - "name": "main_JumpAbility_description", - "value": "Jump Ability" + "name": "device_name", + "value": "Example Device" } ] } \ No newline at end of file diff --git a/OpenHealthEcologyFA/entry/src/main/resources/zh_CN/element/string.json b/OpenHealthEcologyFA/entry/src/main/resources/zh_CN/element/string.json index 332e0b48790e8a6d03fd9f2b2093ae19429a986c..ea178f6edf8feff67554fa0bb0a513e22d4bcc1c 100644 --- a/OpenHealthEcologyFA/entry/src/main/resources/zh_CN/element/string.json +++ b/OpenHealthEcologyFA/entry/src/main/resources/zh_CN/element/string.json @@ -17,12 +17,12 @@ "value": "未开启网络" }, { - "name": "main_JumpAbility", - "value": "原子化服务demo Jump Ability" + "name": "reason_location", + "value": "搜索可用的蓝牙设备" }, { - "name": "main_JumpAbility_description", - "value": "Jump Ability" + "name": "device_name", + "value": "示例设备" } ] } \ No newline at end of file diff --git a/OpenHealthEcologyFA/utils.gradle b/OpenHealthEcologyFA/utils.gradle new file mode 100644 index 0000000000000000000000000000000000000000..fef1270ce0a7c9afaeb54c1a41bc8e3fbc9df948 --- /dev/null +++ b/OpenHealthEcologyFA/utils.gradle @@ -0,0 +1,32 @@ +def GROUP_COMPILE_JS = 'compile:js' +ext { + isWindows = org.gradle.internal.os.OperatingSystem.current().isWindows() + commandExecutable = isWindows ? "cmd" : "bash" + commandArgument = isWindows ? "/c" : "-c" +} + +task initNodeModules() { + group GROUP_COMPILE_JS + def out = new ByteArrayOutputStream() + def execResult + doFirst { + if (file("${rootDir}/entry/node_modules").exists()) { + println "> ---- node_modules installed." + } else { + println "> ---- Installing node_modules ..." + execResult = exec { + workingDir "${rootDir}/entry" + commandLine commandExecutable, commandArgument, "npm install --save" + standardOutput = out + } + println "execResult.exitValue: " + execResult.exitValue + println "npm install result:\n" + out.toString() + } + if (!file("${rootDir}/entry/node_modules/@health-ecology-kit").exists()) { + copy { + from file("${rootDir}/@health-ecology-kit") + into file("${rootDir}/entry/node_modules/@health-ecology-kit") + } + } + } +} \ No newline at end of file