qcloud-iotexplorer-bluetooth-adapter
Advanced tools
Comparing version 0.12.20 to 0.12.21
/// <reference types="miniprogram-api-typings" /> | ||
import { InsightLogger } from 'qcloud-iotexplorer-logger'; | ||
import { BlueToothBase } from './BlueToothBase'; | ||
@@ -32,2 +33,3 @@ import { DeviceAdapter, BlueToothDeviceInfo } from './DeviceAdapter'; | ||
_deviceAdapterStore: SimpleStore<DeviceAdapter>; | ||
/** @deprecated */ | ||
_deviceConnectStatusStore: SimpleStore<{ | ||
@@ -43,2 +45,3 @@ connected: boolean; | ||
protected _deviceLastFoundTime: Record<string, number>; | ||
protected logger: InsightLogger; | ||
constructor({ deviceAdapters, actions, bluetoothApi, h5Websocket, devMode, ignoreAnonymousDevices, mpDisableRefreshCache, }: BlueToothAdapterProps); | ||
@@ -61,2 +64,7 @@ get devMode(): boolean; | ||
resetOnDeviceFoundThrottle(): void; | ||
/** | ||
* 聚合 h5 同步过来的连接状态以及 adapter 抛出的连接状态事件 | ||
* | ||
* @deprecated | ||
*/ | ||
onDeviceConnectStatusChange({ connected, explorerDeviceId, deviceId, }: { | ||
@@ -73,3 +81,3 @@ connected: any; | ||
stopBluetoothDevicesDiscovery(): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
/** | ||
@@ -82,2 +90,3 @@ * 1. wx.openBluetoothAdapter | ||
initProductIds(): Promise<void>; | ||
/** 接收小程序蓝牙 API 的连接状态事件回调,分发到对应的 DeviceAdadpter */ | ||
onBleConnectionStateChange({ deviceId, connected }: { | ||
@@ -103,4 +112,3 @@ deviceId: any; | ||
*/ | ||
searchDevice({ deviceId, serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, ignoreWarning, ignoreCache, disableCache, DeviceAdapter, // 指定adapter,会自动忽略已经注入的adapter | ||
startBluetoothDevicesDiscoveryParams, useCacheFoundDevices, }: SearchDeviceParams): Promise<BlueToothDeviceInfo>; | ||
searchDevice(params: SearchDeviceParams): Promise<BlueToothDeviceInfo>; | ||
stopSearchDevice(): void; | ||
@@ -112,3 +120,3 @@ getDeviceAdapter(params: string | { | ||
instantiateDeviceAdapter({ deviceId, serviceId, deviceName, name, productId, extendInfo, }: ConnectDeviceParams, { DeviceAdapter: SpecificDeviceAdapter, reuseAdapterInstance, }?: ConnectDeviceOptions): DeviceAdapter; | ||
connectDevice({ deviceId, serviceId, mac, deviceName, name, productId, extendInfo, }: ConnectDeviceParams, { DeviceAdapter: SpecificDeviceAdapter, autoNotify, enableDeviceCache, destroyAdapterAfterDisconnect, disableCache, reuseAdapterInstance, }?: ConnectDeviceOptions): Promise<DeviceAdapter>; | ||
connectDevice(deviceInfo: ConnectDeviceParams, options?: ConnectDeviceOptions): Promise<DeviceAdapter>; | ||
connectAdvertisingDevice({ deviceId, deviceName, productId, ...deviceParams }: ConnectDeviceParams, options?: ConnectDeviceOptions): Promise<DeviceAdapter>; | ||
@@ -115,0 +123,0 @@ searchAndConnectDevice({ deviceId, serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, }: SearchDeviceParams, { autoNotify, disableCache, DeviceAdapter, }?: { |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothAdapter=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),lodash_uniqwith_1=tslib_1.__importDefault(require("lodash.uniqwith")),BlueToothBase_1=require("./BlueToothBase"),DeviceAdapter_1=require("./DeviceAdapter"),nativeBluetoothApi_1=tslib_1.__importDefault(require("./nativeBluetoothApi")),BluetoothDeviceCacheManager_1=require("./BluetoothDeviceCacheManager"),SimpleStore_1=require("../libs/SimpleStore"),qcloud_iotexplorer_common_libs_1=require("qcloud-iotexplorer-common-libs"),types_1=require("./types"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,isEmpty=_a.isEmpty,noop=_a.noop,delay=_a.delay,DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE=300,BlueToothAdapter=function(e){function t(t){var i=t.deviceAdapters,r=void 0===i?[]:i,o=t.actions,n=t.bluetoothApi,c=t.h5Websocket,s=t.devMode,a=t.ignoreAnonymousDevices,d=void 0===a||a,u=t.mpDisableRefreshCache,l=void 0!==u&&u,v=e.call(this)||this;return v._devMode=!1,v._ignoreAnonymousDevices=!0,v._bluetoothApi={},v._actions={},v._deviceAdapterFactoryMap={},v._productIdMap={},v._inited=!1,v._available=!1,v._discovering=!1,v._onBluetoothDeviceFoundHandler=null,v._onDeviceFoundThrottle=DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE,v._onBluetoothScanAdvertisingHandler=null,v._initPromise=null,v._searchDevicePromise=null,v._deviceAdapterStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),v._deviceConnectStatusStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),v._initPeripheralServerPromise=null,v._mpDisableRefreshCache=!1,v._deviceLastFoundTime={},v._devMode=s,v.addAdapter(r),isEmpty(v._deviceAdapterFactoryMap)&&console.warn("无合法的deviceAdapter"),v._ignoreAnonymousDevices=d,v._h5Websocket=c,v._bluetoothApi=n||nativeBluetoothApi_1.default,v._actions=o||{},v.deviceCacheManager=new BluetoothDeviceCacheManager_1.BluetoothDeviceCacheManager,v._mpDisableRefreshCache=l,v}return tslib_1.__extends(t,e),Object.defineProperty(t.prototype,"devMode",{get:function(){return"function"==typeof this._devMode?this._devMode():this._devMode},enumerable:!1,configurable:!0}),t.prototype.addAdapter=function(e,t){var i=this;void 0===t&&(t=!1);var r=function(e){t||Object.prototype.isPrototypeOf.call(DeviceAdapter_1.DeviceAdapter,e)?e.serviceId?i._deviceAdapterFactoryMap[e.serviceId]=e:console.error("非法的设备适配器,未配置serviceId",e):console.error("非法的设备适配器",e)};(null==e?void 0:e.splice)?e.forEach(r):r(e)},t.prototype._filterDevices=function(e){var t,i=this,r=e.deviceId,o=e.devices,n=void 0===o?[]:o,c=e.serviceIds,s=e.deviceName,a=void 0===s?"":s,d=e.productId,u=e.ignoreDeviceIds,l=void 0===u?[]:u,v=e.ignoreServiceIds,h=void 0===v?[]:v,p=e.extendInfo,_=void 0===p?{}:p,f=e.DeviceAdapter;if(f)c=[f.serviceId],t=[f.deviceFilter];else{c&&c.length||(c=this._getSupportServiceIds());var D={};(null==h?void 0:h.length)&&(h.forEach((function(e){return D[e]=!0})),c=c.filter((function(e){return!D[e]}))),t=c.map((function(e){return i._deviceAdapterFactoryMap[e].deviceFilter}))}for(var g=[],I=function(e,i){if(r&&n[e].deviceId!==r)return"continue";if(l.find((function(t){return n[e].deviceId===t})))return"continue";for(var o=void 0,s=0,u=t.length;s<u;s++)if(o=t[s](n[e],{serviceIds:c,deviceName:a,productId:d,ignoreDeviceIds:l,ignoreServiceIds:h,extendInfo:_}),a){if(o&&o.deviceName===a)return{value:[o]}}else if(o){g.push(o);break}},b=0,A=n.length;b<A;b++){var m=I(b);if("object"==typeof m)return m.value}return g},t.prototype._getSupportServiceIds=function(){return Object.keys(this._deviceAdapterFactoryMap)},t.prototype.setOnDeviceFoundThrottle=function(e){this._onDeviceFoundThrottle=e},t.prototype.resetOnDeviceFoundThrottle=function(){this._onDeviceFoundThrottle=DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE},t.prototype.onDeviceConnectStatusChange=function(e){var t=e.connected,i=e.explorerDeviceId,r=e.deviceId;console.log("onDeviceConnectStatusChange",{connected:t,explorerDeviceId:i,deviceId:r});var o=this._deviceConnectStatusStore.get({connected:t,explorerDeviceId:i});o?o.connected!==t&&(console.log("device connect status did change",{connected:t,explorerDeviceId:i,deviceId:r}),o.connected=t,this.emit("onDeviceConnectStatusChange",{connected:t,explorerDeviceId:i,deviceId:r})):(this._deviceConnectStatusStore.set({connected:t,explorerDeviceId:i,deviceId:r}),console.log("new device connected",this._deviceConnectStatusStore.getAll()),this.emit("onDeviceConnectStatusChange",{connected:t,explorerDeviceId:i,deviceId:r}))},t.prototype.startBluetoothDevicesDiscovery=function(e){if(!this._discovering)return this._bluetoothApi.startBluetoothDevicesDiscovery(tslib_1.__assign(tslib_1.__assign({powerLevel:"high",interval:this._onDeviceFoundThrottle},e),{allowDuplicatesKey:!0}))},t.prototype.stopBluetoothDevicesDiscovery=function(){return this._bluetoothApi.stopBluetoothDevicesDiscovery()},t.prototype.cleanup=function(t){e.prototype.cleanup.call(this,t),t||(console.log("cleanup bluetooth adapter"),this._discovering&&this.stopBluetoothDevicesDiscovery(),this._bluetoothApi.closeBluetoothAdapter(),console.log("manually disconnect all device",this._deviceAdapterStore.getAll()),this._deviceAdapterStore.getAll().forEach((function(e){e.isConnected&&e.disconnectDevice()})))},t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){return[2,this._initPromise||(this._initPromise=new Promise((function(t,i){return tslib_1.__awaiter(e,void 0,void 0,(function(){var e,r,o,n,c,s,a,d=this;return tslib_1.__generator(this,(function(u){switch(u.label){case 0:if(u.trys.push([0,4,,5]),this._inited){if(this._available)return this._initPromise=null,[2,t()];throw{errCode:10001}}return[4,Promise.all([this.deviceCacheManager.init(),this.initProductIds()])];case 1:return u.sent(),e=function(e){var i=e.available,r=e.discovering;return tslib_1.__awaiter(d,void 0,void 0,(function(){var e,o,n=this;return tslib_1.__generator(this,(function(c){switch(c.label){case 0:return console.log("onBluetoothAdapterStateChange",{available:i,discovering:r}),this._available=i,this._discovering=r,this.emit("adapterStateChange",{available:i,discovering:r}),i?(this._inited=!0,t(),this._initPromise=null,[3,5]):[3,1];case 1:return c.trys.push([1,3,,4]),[4,this._bluetoothApi.getSystemInfo()];case 2:return(null==(e=c.sent())?void 0:e.platform)&&e.platform.toLowerCase().indexOf("android")>-1&&this._deviceAdapterStore.getAll().forEach((function(e){e.isConnected&&(console.log("trigger onBleConnectionStateChange manually"),n.onBleConnectionStateChange({deviceId:e.deviceId,connected:!1}))})),[3,4];case 3:return o=c.sent(),console.error("trigger onBleConnectionStateChange manually error",o),[3,4];case 4:this.cleanup(),c.label=5;case 5:return[2]}}))}))},r=function(e){return d.onBleConnectionStateChange(e)},o=function(e){return d.onBLECharacteristicValueChange(e)},n=function(e){return d.onBluetoothDeviceFound(e)},c={mode:"central"},this._mpDisableRefreshCache&&Object.assign(c,{refreshCache:!1}),[4,this._bluetoothApi.openBluetoothAdapter(c)];case 2:return u.sent(),this._bluetoothApi.onBluetoothAdapterStateChange(e),this._bluetoothApi.onBLEConnectionStateChange(r),this._bluetoothApi.onBLECharacteristicValueChange(o),this._bluetoothApi.onBluetoothDeviceFound(n),this.addCleanupTask("init",(function(){d._available=d._discovering=d._inited=!1,d._initPromise=null,d._bluetoothApi.offBluetoothAdapterStateChange(e),d._bluetoothApi.offBLEConnectionStateChange(r),d._bluetoothApi.offBLECharacteristicValueChange(o),d._bluetoothApi.offBluetoothDeviceFound(n),d._bluetoothApi.closeBluetoothAdapter()})),s=e,[4,this._bluetoothApi.getBluetoothAdapterState()];case 3:return s.apply(void 0,[u.sent()]),[3,5];case 4:return a=u.sent(),this._available=!1,this._inited=!1,this._initPromise=null,i(this._normalizeError(a)),[3,5];case 5:return[2]}}))}))})))]}))}))},t.prototype.initProductIds=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return"function"!=typeof this._actions.initProductIds?[3,2]:(e=this,[4,this._actions.initProductIds()]);case 1:e._productIdMap=t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.onBleConnectionStateChange=function(e){var t=e.deviceId,i=e.connected;console.log("onBLEConnectionStateChange",t,i);var r=this.getDeviceAdapter(t);r?r.onBleConnectionStateChange({connected:i}):console.warn("on bLEConnectionStateChange, but no adapter")},t.prototype.onBLECharacteristicValueChange=function(e){var t=e.deviceId,i=e.serviceId,r=e.characteristicId,o=e.value;console.log("onBLECharacteristicValueChange",t,i,r,o);var n=this.getDeviceAdapter({deviceId:t});if(n)return n.onBLECharacteristicValueChange({serviceId:i,characteristicId:r,value:o});console.warn("on onBLECharacteristicValueChange, but no adapter")},t.prototype.getBluetoothDevices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this._bluetoothApi.getBluetoothDevices()];case 1:return e=t.sent().devices,this._ignoreAnonymousDevices&&(e=e.filter((function(e){return"未知设备"!==e.name}))),[2,e]}}))}))},t.prototype.onBluetoothDeviceFound=function(e){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t,i;return tslib_1.__generator(this,(function(r){switch(r.label){case 0:t=(null==e?void 0:e.devices)||[];try{"function"==typeof this._onBluetoothScanAdvertisingHandler&&this._onBluetoothScanAdvertisingHandler(t)}catch(e){console.error("_onBluetoothScanAdvertisingHandler error",e)}return[4,this.getBluetoothDevices()];case 1:i=r.sent();try{"function"==typeof this._onBluetoothDeviceFoundHandler&&this._onBluetoothDeviceFoundHandler(i,t)}catch(e){console.error("_onBluetoothDeviceFoundHandler error",e)}return[2,i]}}))}))},t.prototype.startSearch=function(e){var t=e.serviceId,i=e.serviceIds,r=e.ignoreDeviceIds,o=void 0===r?[]:r,n=e.ignoreServiceIds,c=void 0===n?[]:n,s=e.onSearch,a=void 0===s?noop:s,d=e.onError,u=void 0===d?noop:d,l=e.timeout,v=void 0===l?2e4:l,h=e.extendInfo,p=void 0===h?{}:h,_=e.DeviceAdapter,f=e.ignoreCachedDevices,D=void 0!==f&&f,g=e.startBluetoothDevicesDiscoveryParams,I=void 0===g?{}:g;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,r,n,s,d,l,h,f=this;return tslib_1.__generator(this,(function(g){switch(g.label){case 0:return[4,this.init()];case 1:g.sent(),t&&!i&&(i=[t]),e=0,r=[],n=0,s=function(e){var t={};return e.forEach((function(e){t[e.deviceId]=e})),r.forEach((function(e){e.isFromCacheBroadcast=!t[e.deviceId]})),r=lodash_uniqwith_1.default(tslib_1.__spread(r,e),(function(e,t){return e.deviceId===t.deviceId})).map((function(e){return t[e.deviceId]||e}))},d=function(e){f.stopSearch(),u(e)},g.label=2;case 2:return g.trys.push([2,4,,5]),n=Date.now(),[4,this.startBluetoothDevicesDiscovery(I)];case 3:return g.sent(),this._onBluetoothDeviceFoundHandler=function(t){var r=D?t.filter((function(e){return"number"!=typeof e.lastFoundTime||e.lastFoundTime>=n})):t;try{var u=s(f._filterDevices({devices:r,serviceIds:i,ignoreDeviceIds:o,ignoreServiceIds:c,extendInfo:p,DeviceAdapter:_}));e=u.length,a(u)}catch(e){console.log("onSearch error",e),d(f._normalizeError(e))}},this.onBluetoothDeviceFound(),l=function(e){e.available||d(f._normalizeError({errCode:10001}))},this.on("adapterStateChange",l),this.addCleanupTask("startSearch",(function(){f._onBluetoothDeviceFoundHandler=null,f.off("adapterStateChange",l)})),setTimeout((function(){e||d("未发现设备,请确认设备已开启")}),v),[3,5];case 4:throw h=g.sent(),this.cleanup("startSearch"),this._normalizeError(h);case 5:return[2]}}))}))},t.prototype.stopSearch=function(){this.cleanup("startSearch"),this.stopBluetoothDevicesDiscovery()},t.prototype.searchDevice=function(e){var t=e.deviceId,i=e.serviceId,r=e.serviceIds,o=e.deviceName,n=e.productId,c=e.ignoreDeviceIds,s=void 0===c?[]:c,a=e.timeout,d=void 0===a?5e3:a,u=e.extendInfo,l=void 0===u?{}:u,v=e.ignoreWarning,h=void 0!==v&&v,p=e.ignoreCache,_=e.disableCache,f=e.DeviceAdapter,D=e.startBluetoothDevicesDiscoveryParams,g=e.useCacheFoundDevices,I=void 0===g||g;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,c=this;return tslib_1.__generator(this,(function(a){switch(a.label){case 0:return h||console.warn("[DEPRECATED] searchDevice + connectDevice 的方式连接设备已废弃,请直接使用 searchAndConnectDevice 方法,会自动处理连接缓存已经失效重搜等逻辑。"),void 0===_&&void 0!==p&&(_=p),[4,this.init()];case 1:return a.sent(),i&&!r&&(r=[i]),console.log("searching for explorerDeviceId => ",o),!_&&(e=this.deviceCacheManager.getDeviceCache(o))?(console.log("find ble deviceInfo from cache for "+o,tslib_1.__assign({deviceName:o,productId:n},e)),[2,Promise.resolve(tslib_1.__assign({deviceName:o,productId:n},e))]):[2,this._searchDevicePromise||(this._searchDevicePromise=new Promise((function(e,i){return tslib_1.__awaiter(c,void 0,void 0,(function(){var c,a,u,v=this;return tslib_1.__generator(this,(function(h){switch(h.label){case 0:c=function(e){v.stopBluetoothDevicesDiscovery(),i(v._normalizeError(e)),v._searchDevicePromise=null,v._onBluetoothDeviceFoundHandler=null},a=function(t){v.stopBluetoothDevicesDiscovery(),e(t),v._searchDevicePromise=null,v._onBluetoothDeviceFoundHandler=null},this._onBluetoothDeviceFoundHandler=function(e,i){try{var d=v._filterDevices({deviceId:t,devices:I?e:i,serviceIds:r,deviceName:o,productId:n,ignoreDeviceIds:s,extendInfo:l,DeviceAdapter:f});d.length>0&&a(d[0])}catch(e){c(e)}},this.addCleanupTask("startSearchDevice",(function(){a(null),v.removeCleanupTask("startSearchDevice")})),h.label=1;case 1:return h.trys.push([1,3,,4]),[4,this.startBluetoothDevicesDiscovery(D)];case 2:return h.sent(),console.log("startBluetoothDevicesDiscovery succ"),this.onBluetoothDeviceFound(),setTimeout((function(){a(null)}),d),[3,4];case 3:return u=h.sent(),c(u),[3,4];case 4:return[2]}}))}))})))]}}))}))},t.prototype.stopSearchDevice=function(){this.stopBluetoothDevicesDiscovery(),this.cleanup("startSearchDevice")},t.prototype.getDeviceAdapter=function(e){var t,i;if(!e)throw"非法的参数,请传入 { deviceId?: string; explorerDeviceId?: string }";return"string"==typeof e?t=e:(t=e.deviceId,i=e.explorerDeviceId),this._deviceAdapterStore.get({deviceId:t,explorerDeviceId:i})},t.prototype.instantiateDeviceAdapter=function(e,t){var i,r,o=this,n=e.deviceId,c=e.serviceId,s=e.deviceName,a=e.name,d=e.productId,u=e.extendInfo,l=void 0===t?{}:t,v=l.DeviceAdapter,h=l.reuseAdapterInstance;if(v){if(v.serviceId!==c)throw"指定的DeviceAdapter serviceId 不匹配,"+v.serviceId+" !== "+c;i=v}else if(!(i=this._deviceAdapterFactoryMap[c]))throw"无匹配serviceId为"+c+"的 deviceAdapter";return h&&(n||d&&s)&&(r=this.getDeviceAdapter({deviceId:n,explorerDeviceId:d+"/"+s})),r||(r=new i({deviceId:n,deviceName:s,productId:d,name:a,actions:this._actions,bluetoothApi:this._bluetoothApi,h5Websocket:this._h5Websocket,extendInfo:u,bluetoothAdapter:this}),this._deviceAdapterStore.set(r),r.on("connect",(function(){r._deviceConnected=!0,o.onDeviceConnectStatusChange({explorerDeviceId:r.explorerDeviceId,connected:!0,deviceId:n})})).on("disconnect",(function(){r._deviceConnected=!1,o.onDeviceConnectStatusChange({explorerDeviceId:r.explorerDeviceId,connected:!1,deviceId:n})})).on("destroy",(function(){console.log("destroy adapter",r),o._deviceAdapterStore.remove({deviceId:n})})),this.emit("deviceAdapterInstantiate",r)),r},t.prototype.connectDevice=function(e,t){var i=e.deviceId,r=e.serviceId,o=e.mac,n=e.deviceName,c=e.name,s=e.productId,a=e.extendInfo,d=void 0===t?{}:t,u=d.DeviceAdapter,l=d.autoNotify,v=d.enableDeviceCache,h=void 0===v||v,p=d.destroyAdapterAfterDisconnect,_=d.disableCache,f=d.reuseAdapterInstance,D=void 0===f||f;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:return d.trys.push([0,3,,4]),void 0===_&&void 0!==h&&(_=!h),[4,this.init()];case 1:return d.sent(),o&&console.warn("[DEPRECATED] mac is deprecated, please use deviceName instead."),void 0!==p&&console.warn("[DEPRECATED] destroyAdapterAfterDisconnect 参数已废弃,默认 deviceAdapter 创建后不会被销毁,如需手动销毁请调用 deviceAdapter.destroy()"),n=n||o,s=s||this._productIdMap[r],(null==(e=this.instantiateDeviceAdapter({deviceId:i,serviceId:r,deviceName:n,name:c,productId:s,extendInfo:a},{DeviceAdapter:u,reuseAdapterInstance:D}))?void 0:e.isConnected)?(console.log("device already connected, returning adapter",e),[2,e]):[4,e.connectDevice({autoNotify:l})];case 2:return d.sent(),!_&&n&&this.deviceCacheManager.setDeviceCache(n,{deviceId:i,serviceId:r,name:c,deviceName:n,productId:s,extendInfo:a}),console.log("deviceConnected"),[2,e];case 3:return t=d.sent(),[2,Promise.reject(t)];case 4:return[2]}}))}))},t.prototype.connectAdvertisingDevice=function(e,t){void 0===t&&(t={});var i=e.deviceId,r=e.deviceName,o=e.productId,n=tslib_1.__rest(e,["deviceId","deviceName","productId"]);return i||(i=o+"/"+r),this.connectDevice(tslib_1.__assign({deviceId:i,deviceName:r,productId:o},n),tslib_1.__assign(tslib_1.__assign({},t),{autoNotify:!1}))},t.prototype.searchAndConnectDevice=function(e,t){var i=e.deviceId,r=e.serviceId,o=e.serviceIds,n=e.deviceName,c=e.productId,s=e.ignoreDeviceIds,a=void 0===s?[]:s,d=e.timeout,u=void 0===d?5e3:d,l=e.extendInfo,v=void 0===l?{}:l,h=void 0===t?{}:t,p=h.autoNotify,_=h.disableCache,f=void 0!==_&&_,D=h.DeviceAdapter;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t,s;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:return d.trys.push([0,7,,8]),e=void 0,!f&&c&&n&&(e=this._deviceAdapterStore.get({explorerDeviceId:c+"/"+n})),e?(console.log("find deviceAdapter in cache, explorerDeviceId: ",c+"/"+n,e),e.isConnected?[3,2]:[4,e.connectDevice({autoNotify:p})]):[3,3];case 1:d.sent(),d.label=2;case 2:return[2,e];case 3:return[4,this.searchDevice({deviceId:i,serviceId:r,serviceIds:o,deviceName:n,productId:c,ignoreDeviceIds:a,timeout:u,extendInfo:v,ignoreWarning:!0,disableCache:f,DeviceAdapter:D})];case 4:return(t=d.sent())?(!t.productId&&c&&(t.productId=c),console.log("deviceInfo",t,c),[4,this.connectDevice(t,{autoNotify:p,disableCache:f,DeviceAdapter:D})]):[2,Promise.reject({code:"DeviceNotFound"})];case 5:return[2,e=d.sent()];case 6:return[3,8];case 7:return s=d.sent(),console.error("searchAndConnectDevice error",s),[2,Promise.reject(s)];case 8:return[2]}}))}))},t.prototype.startScanAdvert=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this.init()];case 1:return t.sent(),this._onBluetoothScanAdvertisingHandler||(this._onBluetoothScanAdvertisingHandler=function(t){void 0===t&&(t=[]);var i=e._deviceAdapterStore.getAll().filter((function(e){return e.isConnected&&e.communicationMode===types_1.CommunicationMode.ADVERT}));i.length<=0||t.forEach((function(e){var t,r=i.find((function(t){return t.deviceId===e.deviceId}));if(r){console.log("get matchAdapter on deviceId");try{"function"==typeof r.advertFilter&&(t=r.advertFilter(e))}catch(e){return void console.error("deviceAdapters advertFilter error",e)}}else for(var o=0;o<i.length;o++)try{if("function"==typeof i[o].advertFilter&&(t=i[o].advertFilter(e)),t){r=i[o];break}}catch(e){console.error("deviceAdapters advertFilter error",e)}if(t&&r)try{"function"==typeof r.onScanAdvert&&r.onScanAdvert(t)}catch(e){console.error("deviceAdapters onScanAdvert error",e)}}))},this.addCleanupTask("startScanAdvert",(function(){console.log("startScanAdvert clean up"),e._onBluetoothScanAdvertisingHandler=null}))),[4,this.startBluetoothDevicesDiscovery()];case 2:return t.sent(),[2]}}))}))},t.prototype.stopScanAdvert=function(){this.cleanup("startScanAdvert"),this.stopBluetoothDevicesDiscovery()},t.prototype._initPeripheralServer=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this.init()];case 1:return t.sent(),[2,this._initPeripheralServerPromise||(this._initPeripheralServerPromise=new Promise((function(t,i){return tslib_1.__awaiter(e,void 0,void 0,(function(){var e,r,o=this;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),this._advertisingQueue=new qcloud_iotexplorer_common_libs_1.SimpleQueue({autoStart:!0,handler:function(e){var t=e.businessData;return tslib_1.__awaiter(o,void 0,void 0,(function(){var e,i,r,o,n,c;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:if(e=t.deviceId,i=t.explorerDeviceId,r=t.duration,o=t.advertiseRequest,n=t.powerLevel,!(c=this.getDeviceAdapter({deviceId:e,explorerDeviceId:i})))throw"deviceAdapter not existed in advertising";if(!c.isConnected)throw'status "isConnected" in deviceAdapter is false, reject advertising; wx deviceId: '+e;return[4,this._blePeripheralServer.startAdvertising({powerLevel:n,advertiseRequest:tslib_1.__assign(tslib_1.__assign({},o),{connectable:!1})})];case 1:return s.sent(),[4,delay(r)];case 2:return s.sent(),[4,this._blePeripheralServer.stopAdvertising()];case 3:return s.sent(),[2]}}))}))},onTaskSuccess:function(e){var t=e.businessData;return"function"==typeof t.onSuccess&&t.onSuccess()},onTaskError:function(e,t){var i=t.businessData;return"function"==typeof i.onError&&i.onError(e)}}),[4,this._bluetoothApi.openBluetoothAdapter({mode:"peripheral"})];case 1:return n.sent(),e=this,[4,this._bluetoothApi.createBLEPeripheralServer()];case 2:return e._blePeripheralServer=n.sent(),this.addCleanupTask("initPeripheralServer",(function(){return tslib_1.__awaiter(o,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),console.log("initPeripheralServer clean up"),this._initPeripheralServerPromise=null,this._advertisingQueue&&(this._advertisingQueue.stop(),this._advertisingQueue=null),this._blePeripheralServer?[4,this._blePeripheralServer.close()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,4];case 3:return e=t.sent(),console.error("clean up initPeripheralServer error",e),[3,4];case 4:return this._blePeripheralServer=null,[2]}}))}))})),console.log("init blePeripheralServer success"),t(),[3,4];case 3:return r=n.sent(),this._initPeripheralServerPromise=null,i(this._normalizeError(r)),console.error("initPeripheralServer error",r),[3,4];case 4:return[2]}}))}))})))]}}))}))},t.prototype.advertising=function(e){var t=e.deviceId,i=e.explorerDeviceId,r=e.powerLevel,o=void 0===r?"medium":r,n=e.advertiseRequest,c=e.duration,s=void 0===c?100:c,a=e.onSuccess,d=e.onError;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return[4,this._initPeripheralServer()];case 1:return e.sent(),s=Math.min(s,3e3),this._advertisingQueue.start(),[2,this._advertisingQueue.push({deviceId:t,explorerDeviceId:i,powerLevel:o,advertiseRequest:n,duration:s,onSuccess:a,onError:d})]}}))}))},t.prototype.stopAdvertising=function(){if(this._advertisingQueue)return this._advertisingQueue.stop()},t}(BlueToothBase_1.BlueToothBase);exports.BlueToothAdapter=BlueToothAdapter; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothAdapter=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),qcloud_iotexplorer_logger_1=tslib_1.__importDefault(require("qcloud-iotexplorer-logger")),lodash_uniqwith_1=tslib_1.__importDefault(require("lodash.uniqwith")),BlueToothBase_1=require("./BlueToothBase"),DeviceAdapter_1=require("./DeviceAdapter"),nativeBluetoothApi_1=tslib_1.__importDefault(require("./nativeBluetoothApi")),BluetoothDeviceCacheManager_1=require("./BluetoothDeviceCacheManager"),SimpleStore_1=require("../libs/SimpleStore"),qcloud_iotexplorer_common_libs_1=require("qcloud-iotexplorer-common-libs"),types_1=require("./types"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,isEmpty=_a.isEmpty,noop=_a.noop,delay=_a.delay,DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE=300,BlueToothAdapter=function(e){function t(t){var i=t.deviceAdapters,r=void 0===i?[]:i,o=t.actions,n=t.bluetoothApi,c=t.h5Websocket,s=t.devMode,a=t.ignoreAnonymousDevices,d=void 0===a||a,u=t.mpDisableRefreshCache,v=void 0!==u&&u,l=e.call(this)||this;return l._devMode=!1,l._ignoreAnonymousDevices=!0,l._bluetoothApi={},l._actions={},l._deviceAdapterFactoryMap={},l._productIdMap={},l._inited=!1,l._available=!1,l._discovering=!1,l._onBluetoothDeviceFoundHandler=null,l._onDeviceFoundThrottle=DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE,l._onBluetoothScanAdvertisingHandler=null,l._initPromise=null,l._searchDevicePromise=null,l._deviceAdapterStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),l._deviceConnectStatusStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),l._initPeripheralServerPromise=null,l._mpDisableRefreshCache=!1,l._deviceLastFoundTime={},l.logger=qcloud_iotexplorer_logger_1.default.derive((function(){return{event:"ble.blueToothAdapter.*"}})),l._devMode=s,l.addAdapter(r),isEmpty(l._deviceAdapterFactoryMap)&&l.logger.warn("noAdapter",{message:"无合法的 deviceAdapter"}),l._ignoreAnonymousDevices=d,l._h5Websocket=c,l._bluetoothApi=n||nativeBluetoothApi_1.default,l._actions=o||{},l.deviceCacheManager=new BluetoothDeviceCacheManager_1.BluetoothDeviceCacheManager,l._mpDisableRefreshCache=v,l}return tslib_1.__extends(t,e),Object.defineProperty(t.prototype,"devMode",{get:function(){return"function"==typeof this._devMode?this._devMode():this._devMode},enumerable:!1,configurable:!0}),t.prototype.addAdapter=function(e,t){var i=this;void 0===t&&(t=!1);var r=function(r){var o,n;t||Object.prototype.isPrototypeOf.call(DeviceAdapter_1.DeviceAdapter,r)?r.serviceId?i._deviceAdapterFactoryMap[r.serviceId]=r:i.logger.error("invalidAdapterServiceId",{message:"非法的设备适配器 "+(null===(n=null==r?void 0:r.constructor)||void 0===n?void 0:n.name)+",未配置serviceId'"}):i.logger.error("invalidAdapterPrototype",{message:"非法的设备适配器 "+(null===(o=null==r?void 0:r.constructor)||void 0===o?void 0:o.name)+", serviceId="+(null==e?void 0:e.serviceId),data:{serviceId:null==e?void 0:e.serviceId}})};(null==e?void 0:e.splice)?e.forEach(r):r(e)},t.prototype._filterDevices=function(e){var t,i=this,r=e.deviceId,o=e.devices,n=void 0===o?[]:o,c=e.serviceIds,s=e.deviceName,a=void 0===s?"":s,d=e.productId,u=e.ignoreDeviceIds,v=void 0===u?[]:u,l=e.ignoreServiceIds,h=void 0===l?[]:l,p=e.extendInfo,_=void 0===p?{}:p,f=e.DeviceAdapter;if(f)c=[f.serviceId],t=[f.deviceFilter];else{c&&c.length||(c=this._getSupportServiceIds());var g={};(null==h?void 0:h.length)&&(h.forEach((function(e){return g[e]=!0})),c=c.filter((function(e){return!g[e]}))),t=c.map((function(e){return i._deviceAdapterFactoryMap[e].deviceFilter}))}for(var D=[],I=function(e,i){if(r&&n[e].deviceId!==r)return"continue";if(v.find((function(t){return n[e].deviceId===t})))return"continue";for(var o=void 0,s=0,u=t.length;s<u;s++)if(o=t[s](n[e],{serviceIds:c,deviceName:a,productId:d,ignoreDeviceIds:v,ignoreServiceIds:h,extendInfo:_}),a){if(o&&o.deviceName===a)return{value:[o]}}else if(o){D.push(o);break}},b=0,m=n.length;b<m;b++){var A=I(b);if("object"==typeof A)return A.value}return D},t.prototype._getSupportServiceIds=function(){return Object.keys(this._deviceAdapterFactoryMap)},t.prototype.setOnDeviceFoundThrottle=function(e){this._onDeviceFoundThrottle=e},t.prototype.resetOnDeviceFoundThrottle=function(){this._onDeviceFoundThrottle=DEFAULT_ON_BLUETOOTH_DEVICE_FOUND_THROTTLE},t.prototype.onDeviceConnectStatusChange=function(e){var t=e.connected,i=e.explorerDeviceId,r=e.deviceId,o=this._deviceConnectStatusStore.get({connected:t,explorerDeviceId:i});o?o.connected!==t&&(o.connected=t,this.emit("onDeviceConnectStatusChange",{connected:t,explorerDeviceId:i,deviceId:r})):(this._deviceConnectStatusStore.set({connected:t,explorerDeviceId:i,deviceId:r}),this.emit("onDeviceConnectStatusChange",{connected:t,explorerDeviceId:i,deviceId:r}))},t.prototype.startBluetoothDevicesDiscovery=function(e){if(!this._discovering)return this._bluetoothApi.startBluetoothDevicesDiscovery(tslib_1.__assign(tslib_1.__assign({powerLevel:"high",interval:this._onDeviceFoundThrottle},e),{allowDuplicatesKey:!0}))},t.prototype.stopBluetoothDevicesDiscovery=function(){return this._bluetoothApi.stopBluetoothDevicesDiscovery()},t.prototype.cleanup=function(t,i){void 0===i&&(i=!1),t||(this.logger.info("cleanup",{message:"cleanup bluetoothAdapter"}),this._discovering&&this.stopBluetoothDevicesDiscovery()),e.prototype.cleanup.call(this,t,i)},t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){return[2,this._initPromise||(this._initPromise=new Promise((function(t,i){return tslib_1.__awaiter(e,void 0,void 0,(function(){var e,r,o,n,c,s,a,d=this;return tslib_1.__generator(this,(function(u){switch(u.label){case 0:if(u.trys.push([0,4,,5]),this._inited){if(this._available)return this._initPromise=null,[2,t()];throw{errCode:10001}}return[4,Promise.all([this.deviceCacheManager.init(),this.initProductIds()])];case 1:return u.sent(),e=function(e){var i=e.available,r=e.discovering;return tslib_1.__awaiter(d,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){return this.logger.info("adapterStateChange","蓝牙适配器状态变化, available="+i+", discovering="+r,{available:i,discovering:r}),this._available=i,this._discovering=r,this.emit("adapterStateChange",{available:i,discovering:r}),i?(this._inited=!0,t(),this._initPromise=null):this.cleanup(),[2]}))}))},r=function(e){return d.onBleConnectionStateChange(e)},o=function(e){return d.onBLECharacteristicValueChange(e)},n=function(e){return d.onBluetoothDeviceFound(e)},c={mode:"central"},this._mpDisableRefreshCache&&Object.assign(c,{refreshCache:!1}),[4,this._bluetoothApi.openBluetoothAdapter(c)];case 2:return u.sent(),this._bluetoothApi.onBluetoothAdapterStateChange(e),this._bluetoothApi.onBLEConnectionStateChange(r),this._bluetoothApi.onBLECharacteristicValueChange(o),this._bluetoothApi.onBluetoothDeviceFound(n),this.addCleanupTask("init",(function(){d._available=!1,d._discovering=!1,d._inited=!1,d._initPromise=null,d._bluetoothApi.offBluetoothAdapterStateChange(e),d._bluetoothApi.offBLEConnectionStateChange(r),d._bluetoothApi.offBLECharacteristicValueChange(o),d._bluetoothApi.offBluetoothDeviceFound(n),d._deviceAdapterStore.getAll().forEach((function(e){e.isConnected&&d.onBleConnectionStateChange({deviceId:e.deviceId,connected:!1})})),d._bluetoothApi.closeBluetoothAdapter()})),s=e,[4,this._bluetoothApi.getBluetoothAdapterState()];case 3:return s.apply(void 0,[u.sent()]),[3,5];case 4:return a=u.sent(),this._available=!1,this._discovering=!1,this._inited=!1,this._initPromise=null,i(this._normalizeError(a)),[3,5];case 5:return[2]}}))}))})))]}))}))},t.prototype.initProductIds=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return"function"!=typeof this._actions.initProductIds?[3,2]:(e=this,[4,this._actions.initProductIds()]);case 1:e._productIdMap=t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.onBleConnectionStateChange=function(e){var t=e.deviceId,i=e.connected;this.logger.info("connectionStateChange",{message:"蓝牙设备 "+t+" 连接"+(i?"建立":"断开"),data:{deviceId:t,connected:i}});var r=this.getDeviceAdapter(t);r&&r.onBleConnectionStateChange({connected:i})},t.prototype.onBLECharacteristicValueChange=function(e){var t=e.deviceId,i=e.serviceId,r=e.characteristicId,o=e.value,n=this.getDeviceAdapter({deviceId:t});if(n)return n.onBLECharacteristicValueChange({serviceId:i,characteristicId:r,value:o})},t.prototype.getBluetoothDevices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this._bluetoothApi.getBluetoothDevices()];case 1:return e=t.sent().devices,this._ignoreAnonymousDevices&&(e=e.filter((function(e){return"未知设备"!==e.name}))),[2,e]}}))}))},t.prototype.onBluetoothDeviceFound=function(e){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t,i;return tslib_1.__generator(this,(function(r){switch(r.label){case 0:t=(null==e?void 0:e.devices)||[];try{"function"==typeof this._onBluetoothScanAdvertisingHandler&&this._onBluetoothScanAdvertisingHandler(t)}catch(e){this.logger.error("eventHandlerError",{message:"_onBluetoothScanAdvertisingHandler error",error:e})}return[4,this.getBluetoothDevices()];case 1:i=r.sent();try{"function"==typeof this._onBluetoothDeviceFoundHandler&&this._onBluetoothDeviceFoundHandler(i,t)}catch(e){this.logger.error("eventHandlerError",{message:"_onBluetoothDeviceFoundHandler error",error:e})}return[2,i]}}))}))},t.prototype.startSearch=function(e){var t=e.serviceId,i=e.serviceIds,r=e.ignoreDeviceIds,o=void 0===r?[]:r,n=e.ignoreServiceIds,c=void 0===n?[]:n,s=e.onSearch,a=void 0===s?noop:s,d=e.onError,u=void 0===d?noop:d,v=e.timeout,l=void 0===v?2e4:v,h=e.extendInfo,p=void 0===h?{}:h,_=e.DeviceAdapter,f=e.ignoreCachedDevices,g=void 0!==f&&f,D=e.startBluetoothDevicesDiscoveryParams,I=void 0===D?{}:D;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,r,n,s,d,v,h,f=this;return tslib_1.__generator(this,(function(D){switch(D.label){case 0:return[4,this.init()];case 1:D.sent(),t&&!i&&(i=[t]),e=0,r=[],n=0,s=function(e){var t={};return e.forEach((function(e){t[e.deviceId]=e})),r.forEach((function(e){e.isFromCacheBroadcast=!t[e.deviceId]})),r=lodash_uniqwith_1.default(tslib_1.__spread(r,e),(function(e,t){return e.deviceId===t.deviceId})).map((function(e){return t[e.deviceId]||e}))},d=function(e){f.stopSearch(),u(e)},D.label=2;case 2:return D.trys.push([2,4,,5]),n=Date.now(),[4,this.startBluetoothDevicesDiscovery(I)];case 3:return D.sent(),this._onBluetoothDeviceFoundHandler=function(t){var r=g?t.filter((function(e){return"number"!=typeof e.lastFoundTime||e.lastFoundTime>=n})):t;try{var u=s(f._filterDevices({devices:r,serviceIds:i,ignoreDeviceIds:o,ignoreServiceIds:c,extendInfo:p,DeviceAdapter:_}));e=u.length,a(u)}catch(e){f.logger.error("eventHandlerError",{message:"onSearch error",error:e}),d(f._normalizeError(e))}},this.onBluetoothDeviceFound(),v=function(e){e.available||d(f._normalizeError({errCode:10001}))},this.on("adapterStateChange",v),this.addCleanupTask("startSearch",(function(){f._onBluetoothDeviceFoundHandler=null,f.off("adapterStateChange",v)})),setTimeout((function(){e||d("未发现设备,请确认设备已开启")}),l),[3,5];case 4:throw h=D.sent(),this.cleanup("startSearch"),this._normalizeError(h);case 5:return[2]}}))}))},t.prototype.stopSearch=function(){this.cleanup("startSearch"),this.stopBluetoothDevicesDiscovery()},t.prototype.searchDevice=function(e){var t;return tslib_1.__awaiter(this,void 0,void 0,(function(){var i,r,o,n,c,s,a,d,u,v,l,h,p,_,f,g,D,I,b=this;return tslib_1.__generator(this,(function(m){switch(m.label){case 0:return i=e.deviceId,r=e.serviceId,o=e.deviceName,n=e.productId,c=e.ignoreDeviceIds,s=void 0===c?[]:c,a=e.timeout,d=void 0===a?5e3:a,u=e.extendInfo,v=void 0===u?{}:u,l=e.ignoreCache,h=e.DeviceAdapter,p=e.startBluetoothDevicesDiscoveryParams,_=e.useCacheFoundDevices,f=void 0===_||_,g=e.serviceIds,void 0===(D=e.disableCache)&&void 0!==l&&(D=l),[4,this.init()];case 1:return m.sent(),r&&!g&&(g=[r]),this.logger.info("searchDevice",{message:"开始搜索设备 "+n+"/"+o,data:tslib_1.__assign(tslib_1.__assign({},e),{DeviceAdapter:h?(null===(t=null==h?void 0:h.constructor)||void 0===t?void 0:t.name)||"specific":"notProvided"}),metric:{type:"start"}}),!D&&(I=this.deviceCacheManager.getDeviceCache(o))?(this.logger.info("searchDevice.useDeviceCache",{message:n+"/"+o+" 使用缓存的搜索结果: "+(null==I?void 0:I.deviceId),data:tslib_1.__assign({productId:n,deviceName:o},I)}),[2,Promise.resolve(tslib_1.__assign({deviceName:o,productId:n},I))]):[2,this._searchDevicePromise||(this._searchDevicePromise=new Promise((function(e,t){return tslib_1.__awaiter(b,void 0,void 0,(function(){var r,c,a,u,l=this;return tslib_1.__generator(this,(function(_){switch(_.label){case 0:r=!1,c=function(e){r||(r=!0,l.stopBluetoothDevicesDiscovery(),t(l._normalizeError(e)),l._searchDevicePromise=null,l._onBluetoothDeviceFoundHandler=null,l.logger.error("searchDevice",{message:"搜索设备 "+n+"/"+o+" 失败",metric:{type:"fail"}}))},a=function(t){r||(r=!0,l.stopBluetoothDevicesDiscovery(),e(t),l._searchDevicePromise=null,l._onBluetoothDeviceFoundHandler=null,t?l.logger.info("searchDevice",{message:"搜索到设备 "+n+"/"+o+" -> "+t.deviceId,data:t,metric:{type:"success"}}):l.logger.error("searchDevice",{message:"未搜索到设备 "+n+"/"+o,metric:{type:"fail"}}))},this._onBluetoothDeviceFoundHandler=function(e,t){try{var r=l._filterDevices({deviceId:i,devices:f?e:t,serviceIds:g,deviceName:o,productId:n,ignoreDeviceIds:s,extendInfo:v,DeviceAdapter:h});r.length>0&&a(r[0])}catch(e){c(e)}},this.addCleanupTask("startSearchDevice",(function(){r||a(null)})),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,this.startBluetoothDevicesDiscovery(p)];case 2:return _.sent(),this.onBluetoothDeviceFound(),setTimeout((function(){a(null)}),d),[3,4];case 3:return u=_.sent(),c(u),[3,4];case 4:return[2]}}))}))})))]}}))}))},t.prototype.stopSearchDevice=function(){this.stopBluetoothDevicesDiscovery(),this.cleanup("startSearchDevice")},t.prototype.getDeviceAdapter=function(e){var t,i;if(!e)throw"非法的参数,请传入 { deviceId?: string; explorerDeviceId?: string }";return"string"==typeof e?t=e:(t=e.deviceId,i=e.explorerDeviceId),this._deviceAdapterStore.get({deviceId:t,explorerDeviceId:i})},t.prototype.instantiateDeviceAdapter=function(e,t){var i,r,o=this,n=e.deviceId,c=e.serviceId,s=e.deviceName,a=e.name,d=e.productId,u=e.extendInfo,v=void 0===t?{}:t,l=v.DeviceAdapter,h=v.reuseAdapterInstance;if(l){if(l.serviceId!==c)throw"指定的DeviceAdapter serviceId 不匹配,"+l.serviceId+" !== "+c;i=l}else if(!(i=this._deviceAdapterFactoryMap[c]))throw"无匹配serviceId为"+c+"的 deviceAdapter";return h&&(n||d&&s)&&(r=this.getDeviceAdapter({deviceId:n,explorerDeviceId:d+"/"+s})),r||(r=new i({deviceId:n,deviceName:s,productId:d,name:a,actions:this._actions,bluetoothApi:this._bluetoothApi,h5Websocket:this._h5Websocket,extendInfo:u,bluetoothAdapter:this}),this._deviceAdapterStore.set(r),r.on("connect",(function(){r._deviceConnected=!0,o.onDeviceConnectStatusChange({explorerDeviceId:r.explorerDeviceId,connected:!0,deviceId:n})})).on("disconnect",(function(){r._deviceConnected=!1,o.onDeviceConnectStatusChange({explorerDeviceId:r.explorerDeviceId,connected:!1,deviceId:n})})).on("destroy",(function(){o.logger.info("destroyDeviceAdapter",{message:"销毁 deviceAdapter "+r.deviceId,data:{deviceId:r.deviceId}}),o._deviceAdapterStore.remove({deviceId:n})})),this.emit("deviceAdapterInstantiate",r)),r},t.prototype.connectDevice=function(e,t){return void 0===t&&(t={}),tslib_1.__awaiter(this,void 0,void 0,(function(){var i,r,o,n,c,s,a,d,u,v,l,h,p,_,f,g,D;return tslib_1.__generator(this,(function(I){switch(I.label){case 0:i=e.deviceId,r=e.serviceId,o=e.mac,n=e.name,c=e.extendInfo,s=e.productId,a=e.deviceName,d=t.DeviceAdapter,u=t.autoNotify,v=t.enableDeviceCache,l=void 0===v||v,h=t.destroyAdapterAfterDisconnect,p=t.reuseAdapterInstance,_=void 0===p||p,f=t.disableCache,I.label=1;case 1:return I.trys.push([1,4,,5]),void 0===f&&void 0!==l&&(f=!l),[4,this.init()];case 2:return I.sent(),o&&console.warn("[DEPRECATED] mac is deprecated, please use deviceName instead."),void 0!==h&&console.warn("[DEPRECATED] destroyAdapterAfterDisconnect 参数已废弃,默认 deviceAdapter 创建后不会被销毁,如需手动销毁请调用 deviceAdapter.destroy()"),a=a||o,s=s||this._productIdMap[r],(null==(g=this.instantiateDeviceAdapter({deviceId:i,serviceId:r,deviceName:a,name:n,productId:s,extendInfo:c},{DeviceAdapter:d,reuseAdapterInstance:_}))?void 0:g.isConnected)?[2,g]:[4,g.connectDevice({autoNotify:u})];case 3:return I.sent(),!f&&a&&this.deviceCacheManager.setDeviceCache(a,{deviceId:i,serviceId:r,name:n,deviceName:a,productId:s,extendInfo:c}),[2,g];case 4:return D=I.sent(),[2,Promise.reject(D)];case 5:return[2]}}))}))},t.prototype.connectAdvertisingDevice=function(e,t){void 0===t&&(t={});var i=e.deviceId,r=e.deviceName,o=e.productId,n=tslib_1.__rest(e,["deviceId","deviceName","productId"]);return i||(i=o+"/"+r),this.connectDevice(tslib_1.__assign({deviceId:i,deviceName:r,productId:o},n),tslib_1.__assign(tslib_1.__assign({},t),{autoNotify:!1}))},t.prototype.searchAndConnectDevice=function(e,t){var i=e.deviceId,r=e.serviceId,o=e.serviceIds,n=e.deviceName,c=e.productId,s=e.ignoreDeviceIds,a=void 0===s?[]:s,d=e.timeout,u=void 0===d?5e3:d,v=e.extendInfo,l=void 0===v?{}:v,h=void 0===t?{}:t,p=h.autoNotify,_=h.disableCache,f=void 0!==_&&_,g=h.DeviceAdapter;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return!f&&c&&n&&(e=this._deviceAdapterStore.get({explorerDeviceId:c+"/"+n})),e?e.isConnected?[3,2]:[4,e.connectDevice({autoNotify:p})]:[3,3];case 1:s.sent(),s.label=2;case 2:return[2,e];case 3:return[4,this.searchDevice({deviceId:i,serviceId:r,serviceIds:o,deviceName:n,productId:c,ignoreDeviceIds:a,timeout:u,extendInfo:l,ignoreWarning:!0,disableCache:f,DeviceAdapter:g})];case 4:return(t=s.sent())?(!t.productId&&c&&(t.productId=c),[4,this.connectDevice(t,{autoNotify:p,disableCache:f,DeviceAdapter:g})]):[2,Promise.reject({code:"DeviceNotFound",msg:"未搜索到设备 "+c+"/"+n})];case 5:return[2,e=s.sent()]}}))}))},t.prototype.startScanAdvert=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this.init()];case 1:return t.sent(),this._onBluetoothScanAdvertisingHandler||(this._onBluetoothScanAdvertisingHandler=function(t){void 0===t&&(t=[]);var i=e._deviceAdapterStore.getAll().filter((function(e){return e.isConnected&&e.communicationMode===types_1.CommunicationMode.ADVERT}));i.length<=0||t.forEach((function(e){var t,r=i.find((function(t){return t.deviceId===e.deviceId}));if(r){console.log("get matchAdapter on deviceId");try{"function"==typeof r.advertFilter&&(t=r.advertFilter(e))}catch(e){return void console.error("deviceAdapters advertFilter error",e)}}else for(var o=0;o<i.length;o++)try{if("function"==typeof i[o].advertFilter&&(t=i[o].advertFilter(e)),t){r=i[o];break}}catch(e){console.error("deviceAdapters advertFilter error",e)}if(t&&r)try{"function"==typeof r.onScanAdvert&&r.onScanAdvert(t)}catch(e){console.error("deviceAdapters onScanAdvert error",e)}}))},this.addCleanupTask("startScanAdvert",(function(){console.log("startScanAdvert clean up"),e._onBluetoothScanAdvertisingHandler=null}))),[4,this.startBluetoothDevicesDiscovery()];case 2:return t.sent(),[2]}}))}))},t.prototype.stopScanAdvert=function(){this.cleanup("startScanAdvert",!0),this.stopBluetoothDevicesDiscovery()},t.prototype._initPeripheralServer=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this.init()];case 1:return t.sent(),[2,this._initPeripheralServerPromise||(this._initPeripheralServerPromise=new Promise((function(t,i){return tslib_1.__awaiter(e,void 0,void 0,(function(){var e,r,o=this;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),this._advertisingQueue=new qcloud_iotexplorer_common_libs_1.SimpleQueue({autoStart:!0,handler:function(e){var t=e.businessData;return tslib_1.__awaiter(o,void 0,void 0,(function(){var e,i,r,o,n,c;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:if(e=t.deviceId,i=t.explorerDeviceId,r=t.duration,o=t.advertiseRequest,n=t.powerLevel,!(c=this.getDeviceAdapter({deviceId:e,explorerDeviceId:i})))throw"deviceAdapter not existed in advertising";if(!c.isConnected)throw'status "isConnected" in deviceAdapter is false, reject advertising; wx deviceId: '+e;return[4,this._blePeripheralServer.startAdvertising({powerLevel:n,advertiseRequest:tslib_1.__assign(tslib_1.__assign({},o),{connectable:!1})})];case 1:return s.sent(),[4,delay(r)];case 2:return s.sent(),[4,this._blePeripheralServer.stopAdvertising()];case 3:return s.sent(),[2]}}))}))},onTaskSuccess:function(e){var t=e.businessData;return"function"==typeof t.onSuccess&&t.onSuccess()},onTaskError:function(e,t){var i=t.businessData;return"function"==typeof i.onError&&i.onError(e)}}),[4,this._bluetoothApi.openBluetoothAdapter({mode:"peripheral"})];case 1:return n.sent(),e=this,[4,this._bluetoothApi.createBLEPeripheralServer()];case 2:return e._blePeripheralServer=n.sent(),this.addCleanupTask("initPeripheralServer",(function(){return tslib_1.__awaiter(o,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),console.log("initPeripheralServer clean up"),this._initPeripheralServerPromise=null,this._advertisingQueue&&(this._advertisingQueue.stop(),this._advertisingQueue=null),this._blePeripheralServer?[4,this._blePeripheralServer.close()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,4];case 3:return e=t.sent(),console.error("clean up initPeripheralServer error",e),[3,4];case 4:return this._blePeripheralServer=null,[2]}}))}))})),console.log("init blePeripheralServer success"),t(),[3,4];case 3:return r=n.sent(),this._initPeripheralServerPromise=null,i(this._normalizeError(r)),console.error("initPeripheralServer error",r),[3,4];case 4:return[2]}}))}))})))]}}))}))},t.prototype.advertising=function(e){var t=e.deviceId,i=e.explorerDeviceId,r=e.powerLevel,o=void 0===r?"medium":r,n=e.advertiseRequest,c=e.duration,s=void 0===c?100:c,a=e.onSuccess,d=e.onError;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return[4,this._initPeripheralServer()];case 1:return e.sent(),s=Math.min(s,3e3),this._advertisingQueue.start(),[2,this._advertisingQueue.push({deviceId:t,explorerDeviceId:i,powerLevel:o,advertiseRequest:n,duration:s,onSuccess:a,onError:d})]}}))}))},t.prototype.stopAdvertising=function(){if(this._advertisingQueue)return this._advertisingQueue.stop()},t}(BlueToothBase_1.BlueToothBase);exports.BlueToothAdapter=BlueToothAdapter; | ||
//# sourceMappingURL=BlueToothAdapter.js.map |
@@ -6,5 +6,5 @@ import EventEmitter from 'event-emitter-for-miniprogram'; | ||
_normalizeError(error: any): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
addCleanupTask(action: any, cleanupFn: any): void; | ||
removeCleanupTask(action: any): void; | ||
} |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothBase=void 0;var tslib_1=require("tslib"),event_emitter_for_miniprogram_1=tslib_1.__importDefault(require("event-emitter-for-miniprogram")),errorMap={1e4:"未初始化蓝牙适配器",10001:"手机的蓝牙开关未打开",10002:"没有找到指定设备",10003:"无法连接,请将手机尽量靠近设备",10004:"没有找到指定服务",10005:"没有找到指定特征值",10006:"当前连接已断开",10007:"当前特征值不支持此操作",10008:"其余所有系统上报的异常",10009:"安卓版本过低,不支持低功耗蓝牙",10012:"连接超时,请将手机尽量靠近设备",10013:"连接 deviceId 为空或者是格式不正确"},BlueToothBase=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._cleanupMap={},t}return tslib_1.__extends(t,e),t.prototype._normalizeError=function(e){return(null==e?void 0:e.errCode)&&Object.assign(e,{code:e.errCode,msg:errorMap[e.errCode]}),e},t.prototype.cleanup=function(e){if(e)this._cleanupMap[e]&&"function"==typeof this._cleanupMap[e]?(console.log("clean up for action: ",e),this._cleanupMap[e]()):console.warn("clean up invalid action",e,this._cleanupMap);else for(var t in this._cleanupMap)"function"==typeof this._cleanupMap[t]&&this._cleanupMap[t]()},t.prototype.addCleanupTask=function(e,t){this._cleanupMap[e]=t},t.prototype.removeCleanupTask=function(e){this._cleanupMap[e]=null},t}(event_emitter_for_miniprogram_1.default);exports.BlueToothBase=BlueToothBase; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothBase=void 0;var tslib_1=require("tslib"),event_emitter_for_miniprogram_1=tslib_1.__importDefault(require("event-emitter-for-miniprogram")),errorMap={1e4:"未初始化蓝牙适配器",10001:"手机的蓝牙开关未打开",10002:"没有找到指定设备",10003:"无法连接,请将手机尽量靠近设备",10004:"没有找到指定服务",10005:"没有找到指定特征值",10006:"与设备的蓝牙连接已断开",10007:"当前特征值不支持此操作",10008:"其余所有系统上报的异常",10009:"安卓版本过低,不支持低功耗蓝牙",10012:"连接超时,请将手机尽量靠近设备",10013:"连接 deviceId 为空或者是格式不正确"},BlueToothBase=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._cleanupMap={},t}return tslib_1.__extends(t,e),t.prototype._normalizeError=function(e){return(null==e?void 0:e.errCode)&&Object.assign(e,{code:e.errCode,msg:errorMap[e.errCode]}),e},t.prototype.cleanup=function(e,t){if(void 0===t&&(t=!1),e)this._cleanupMap[e]&&"function"==typeof this._cleanupMap[e]?(this._cleanupMap[e](),delete this._cleanupMap[e]):t||console.warn("clean up invalid action",e,this._cleanupMap);else{for(var r in this._cleanupMap)"function"==typeof this._cleanupMap[r]&&this._cleanupMap[r]();this._cleanupMap={}}},t.prototype.addCleanupTask=function(e,t){this._cleanupMap[e]=t},t.prototype.removeCleanupTask=function(e){this._cleanupMap[e]=null},t}(event_emitter_for_miniprogram_1.default);exports.BlueToothBase=BlueToothBase; | ||
//# sourceMappingURL=BlueToothBase.js.map |
@@ -8,5 +8,5 @@ import { ConnectDeviceParams } from './types'; | ||
init(): Promise<void>; | ||
setDeviceCache(deviceName: any, deviceInfo: ConnectDeviceParams): void; | ||
setDeviceCache(deviceName: string, deviceInfo: ConnectDeviceParams): void; | ||
getDeviceCache(deviceName: any): ConnectDeviceParams; | ||
removeDeviceCache(deviceName: any): void; | ||
} |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothDeviceCacheManager=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),storage=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils.storage,BluetoothDeviceCacheManager=function(){function e(){this.deviceCacheMap={},this._storageKey="__explorer-bluetooth-deviceCacheMap"}return e.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return e=this,[4,storage.getItem(this._storageKey)];case 1:return e.deviceCacheMap=t.sent()||{},[2]}}))}))},e.prototype.setDeviceCache=function(e,t){console.log("cache ble deviceInfo: ",e,t),this.deviceCacheMap[e]=t,storage.setItem(this._storageKey,this.deviceCacheMap)},e.prototype.getDeviceCache=function(e){return this.deviceCacheMap[e]},e.prototype.removeDeviceCache=function(e){this.deviceCacheMap[e]&&(this.deviceCacheMap[e]=null,storage.setItem(this._storageKey,this.deviceCacheMap))},e}();exports.BluetoothDeviceCacheManager=BluetoothDeviceCacheManager; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothDeviceCacheManager=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),qcloud_iotexplorer_logger_1=tslib_1.__importDefault(require("qcloud-iotexplorer-logger")),storage=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils.storage,BluetoothDeviceCacheManager=function(){function e(){this.deviceCacheMap={},this._storageKey="__explorer-bluetooth-deviceCacheMap"}return e.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return e=this,[4,storage.getItem(this._storageKey)];case 1:return e.deviceCacheMap=t.sent()||{},[2]}}))}))},e.prototype.setDeviceCache=function(e,t){qcloud_iotexplorer_logger_1.default.debug("ble.deviceCache.set",{message:"缓存蓝牙设备信息 "+e,data:t}),this.deviceCacheMap[e]=t,storage.setItem(this._storageKey,this.deviceCacheMap)},e.prototype.getDeviceCache=function(e){return this.deviceCacheMap[e]},e.prototype.removeDeviceCache=function(e){this.deviceCacheMap[e]&&(this.deviceCacheMap[e]=null,storage.setItem(this._storageKey,this.deviceCacheMap))},e}();exports.BluetoothDeviceCacheManager=BluetoothDeviceCacheManager; | ||
//# sourceMappingURL=BluetoothDeviceCacheManager.js.map |
/// <reference types="miniprogram-api-typings" /> | ||
import { InsightLogger } from 'qcloud-iotexplorer-logger'; | ||
import { BlueToothBase } from './BlueToothBase'; | ||
@@ -52,3 +53,2 @@ import { BlueToothAdapter } from './BlueToothAdapter'; | ||
_deviceRegistered: boolean; | ||
_characteristicsAutoNotified: boolean; | ||
_services: any[]; | ||
@@ -61,2 +61,3 @@ characteristicsMap: {}; | ||
_batchWriteInterval: number; | ||
baseLogger: InsightLogger; | ||
constructor({ deviceId, productId, deviceName, name, // 设备原始名称 | ||
@@ -123,3 +124,3 @@ actions, bluetoothApi, h5Websocket, extendInfo, bluetoothAdapter, }: { | ||
}): Promise<void>; | ||
autoNotifyCharacteristics(force?: boolean): Promise<void>; | ||
autoNotifyCharacteristics(): Promise<void>; | ||
write(data: any, { writeId, serviceId, }?: { | ||
@@ -126,0 +127,0 @@ writeId?: string; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DeviceAdapter=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),BlueToothBase_1=require("./BlueToothBase"),types_1=require("./types"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,arrayBufferToHexStringArray=_a.arrayBufferToHexStringArray,hexToArrayBuffer=_a.hexToArrayBuffer,DeviceAdapter=function(e){function t(t){var i=t.deviceId,r=t.productId,o=t.deviceName,c=t.name,n=t.actions,s=t.bluetoothApi,a=t.h5Websocket,d=t.extendInfo,u=void 0===d?{}:d,h=t.bluetoothAdapter,v=e.call(this)||this;if(v.extendInfo={},v._name="",v._deviceId="",v._deviceName="",v._deviceConnected=!1,v._productId="",v._deviceRegistered=!1,v._characteristicsAutoNotified=!1,v._services=[],v.characteristicsMap={},v._actions={},v._bluetoothApi={},v._batchWriteEnabled=!1,v._batchWriteInterval=20,!i)throw"无deviceId";if(!r)throw"productId为空";return v._h5Websocket=a,v._bluetoothApi=s,v._actions=n,v._name=c,v._deviceName=o,v._deviceId=i,v._productId=r,v.extendInfo=u||{},v.bluetoothAdapter=h,v.communicationMode=types_1.CommunicationMode.GATT,v.on("disconnect",(function(){v._characteristicsAutoNotified=!1})),v}return tslib_1.__extends(t,e),t.prototype._getNotifyId=function(e){var t=(void 0===e?{}:e).serviceId,i=void 0===t?"":t;i=i||this.serviceId;var r=this.characteristicsMap[i]||{writeIds:[],notifyIds:[],readIds:[],indicateIds:[]};return r.notifyIds[0]||r.indicateIds[0]},Object.defineProperty(t.prototype,"_writeId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).writeIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_notifyId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).notifyIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_readId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).readIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_indicateId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).indicateIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceId",{get:function(){return this._deviceId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"productId",{get:function(){return this._productId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceName",{get:function(){return this._deviceName},set:function(e){this._deviceName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isConnected",{get:function(){return this._deviceConnected},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"originName",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"explorerDeviceId",{get:function(){return[this._productId||"",this._deviceName||""].join("/")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"serviceId",{get:function(){return this.constructor.serviceId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceInfo",{get:function(){return{productId:this.productId,deviceName:this.deviceName,deviceId:this.deviceId,explorerDeviceId:this.explorerDeviceId,name:this.originName}},enumerable:!1,configurable:!0}),t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return this.bluetoothAdapter?[4,this.bluetoothAdapter.init()]:[3,2];case 1:return e.sent(),[3,3];case 2:console.warn("DeviceAdapter未注入bluetoothAdapter实例,可能使用的不是最新版本的qcloud-iotexplorer-bluetooth-adapter模块"),e.label=3;case 3:return[2]}}))}))},t.prototype.handleBLEMessage=function(e,t){t.serviceId,t.characteristicId;return{}},t.prototype.registerDevice=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return this._deviceRegistered?[3,2]:[4,this._actions.registerDevice({deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId})];case 1:e.sent(),this._deviceRegistered=!0,e.label=2;case 2:return[2]}}))}))},t.prototype.bindDevice=function(e){var t=void 0===e?{}:e,i=t.familyId,r=void 0===i?"":i,o=t.roomId,c=void 0===o?"":o;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,this.registerDevice()];case 1:return i.sent(),e={deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId,familyId:r,roomId:c},[4,this._actions.bindDevice(e)];case 2:return i.sent(),this.emit("bind",e),[2,this.explorerDeviceId];case 3:return t=i.sent(),[2,Promise.reject(this._normalizeError(t))];case 4:return[2]}}))}))},t.prototype.onBleConnectionStateChange=function(e){var t=e.connected;console.log("onBleConnectionStateChange => ",t);var i=this._deviceConnected!==t;this._deviceConnected=t,i&&(t?this.emit("connect",tslib_1.__assign({},this.deviceInfo)):this.emit("disconnect",tslib_1.__assign({},this.deviceInfo)),this.emit("bLEConnectionStateChange",{connected:t}))},t.prototype.onBLECharacteristicValueChange=function(e){var t=e.serviceId,i=e.characteristicId,r=e.value;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,o,c,n,s,a,d,u;return tslib_1.__generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,4,,5]),e=r,r instanceof ArrayBuffer&&(e=arrayBufferToHexStringArray(r)),o=this.handleBLEMessage(e,{serviceId:t,characteristicId:i})||{},c=o.shouldIgnore,n=o.reportData,s=tslib_1.__rest(o,["shouldIgnore","reportData"]),c?[2]:(console.log("[DeviceAdapter] receive data:",e,s),a=Date.now(),d=!1,this._deviceName&&n?(d=!0,"function"!=typeof this._actions.reportDeviceData?[3,2]:[4,this._actions.reportDeviceData({deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId,data:n,timestamp:a})]):[3,3]);case 1:return h.sent(),[3,3];case 2:console.warn("handleBLEMessage return should report but actions.reportDeviceData is not implement."),h.label=3;case 3:return this.emit("message",tslib_1.__assign(tslib_1.__assign({},s),{timestamp:a,dataReported:d})),[3,5];case 4:return u=h.sent(),console.error("onBLECharacteristicValueChange onError,",u),[3,5];case 5:return[2]}}))}))},t.prototype.disconnectDevice=function(){this._bluetoothApi.closeBLEConnection({deviceId:this._deviceId}),this._deviceConnected=!1,this.emit("disconnect",tslib_1.__assign({},this.deviceInfo))},t.prototype.connectDevice=function(e){var t=(void 0===e?{}:e).autoNotify,i=void 0===t||t;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t,r,o;return tslib_1.__generator(this,(function(c){switch(c.label){case 0:e=Date.now(),c.label=1;case 1:return c.trys.push([1,8,,9]),[4,this.init()];case 2:return c.sent(),console.log("start connect device",this.deviceInfo),this.isConnected?(console.log("device is already connected",this.deviceInfo),[2]):(t=Date.now(),[4,this._bluetoothApi.createBLEConnection({deviceId:this._deviceId})]);case 3:if(c.sent(),this._deviceConnected=!0,console.log("createBLEConnection succ",Date.now()-t),!i)return[3,7];c.label=4;case 4:return c.trys.push([4,6,,7]),[4,this.autoNotifyCharacteristics(!0)];case 5:return c.sent(),[3,7];case 6:throw r=c.sent(),this.isConnected&&this.disconnectDevice(),r;case 7:return console.log("connectDevice succeed, time cost: ",Date.now()-e),[3,9];case 8:return o=c.sent(),(o=this._normalizeError(o)).errMsg&&o.errMsg.indexOf("already connect")>-1?(console.log("device is already connected, resolve directly, time cost: ",Date.now()-e),[2,Promise.resolve()]):(console.error("connectDevice error",o),[2,Promise.reject(o)]);case 9:return[2]}}))}))},t.prototype.autoNotifyCharacteristics=function(e){return void 0===e&&(e=!1),tslib_1.__awaiter(this,void 0,void 0,(function(){var t,i,r;return tslib_1.__generator(this,(function(o){switch(o.label){case 0:return this._characteristicsAutoNotified&&!e?(console.log("[DeviceAdapter.autoNotifyCharacteristics] characteristics already notified, no operation performed"),[2]):(t=Date.now(),[4,this.getBLEDeviceServices()]);case 1:return i=o.sent(),console.log("getBLEDeviceServices succ",i,Date.now()-t),this.emit("onGetBLEDeviceServices",i),t=Date.now(),[4,this.getBLEDeviceCharacteristics()];case 2:return r=o.sent(),console.log("getBLEDeviceCharacteristics succ",r,Date.now()-t),this.emit("onGetBLEDeviceCharacteristics",r),t=Date.now(),[4,this.notifyBLECharacteristicValueChange()];case 3:return o.sent(),console.log("notifyBLECharacteristicValueChange succ",Date.now()-t),this._characteristicsAutoNotified=!0,[2]}}))}))},t.prototype.write=function(e,t){var i=void 0===t?{}:t,r=i.writeId,o=void 0===r?"":r,c=i.serviceId,n=void 0===c?"":c;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(t){if("string"==typeof e)console.log("writeBLECharacteristicValue",e),e=hexToArrayBuffer(e);else if(e instanceof ArrayBuffer)try{console.log("writeBLECharacteristicValue",arrayBufferToHexStringArray(e).join(""))}catch(e){}return[2,this._write(e,{writeId:o,serviceId:n})]}))}))},t.prototype._write=function(e,t){var i=void 0===t?{}:t,r=i.writeId,o=void 0===r?"":r,c=i.serviceId,n=void 0===c?"":c;return tslib_1.__awaiter(this,void 0,void 0,(function(){var t;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._bluetoothApi.writeBLECharacteristicValue({deviceId:this._deviceId,characteristicId:o||this._writeId,serviceId:n||this.serviceId,value:e})];case 1:return i.sent(),[3,3];case 2:return t=i.sent(),[2,Promise.reject(this._normalizeError(t))];case 3:return[2]}}))}))},t.prototype.getBLEDeviceServices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this._bluetoothApi.getBLEDeviceServices({deviceId:this._deviceId})];case 1:return e=t.sent().services,this._services=e,[2,e]}}))}))},t.prototype.setCharacteristicsIds=function(e,t){var i={notifyIds:[],writeIds:[],indicateIds:[],readIds:[]},r=function(e,t){-1===e.indexOf(t)&&e.push(t)};t.forEach((function(e){var t=e.uuid,o=e.properties,c=o.notify,n=o.write,s=o.indicate,a=o.read;c?r(i.notifyIds,t):n?r(i.writeIds,t):s?r(i.indicateIds,t):a&&r(i.readIds,t)})),this.characteristicsMap[e]=i},t.prototype.getBLEDeviceCharacteristics=function(e){var t=(void 0===e?{}:e).serviceId,i=void 0===t?"":t;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return i=i||this.serviceId,[4,this._bluetoothApi.getBLEDeviceCharacteristics({deviceId:this._deviceId,serviceId:i})];case 1:return e=t.sent().characteristics,this.setCharacteristicsIds(i,e),[2,e]}}))}))},t.prototype.notifyBLECharacteristicValueChange=function(e){var t=void 0===e?{}:e,i=t.characteristicId,r=void 0===i?"":i,o=t.serviceId,c=void 0===o?"":o,n=t.state,s=void 0===n||n;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return r=r||this._getNotifyId(),c=c||this.serviceId,r?[3,1]:(console.warn("未找到指定service下的notifyId,该设备可能不支持notify"),[3,3]);case 1:return[4,this._bluetoothApi.notifyBLECharacteristicValueChange({deviceId:this._deviceId,characteristicId:r,serviceId:c,state:s})];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},t.prototype.readBLECharacteristicValue=function(e){var t=void 0===e?{}:e,i=t.serviceId,r=void 0===i?"":i,o=t.characteristicId,c=void 0===o?"":o;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return r=r||this.serviceId,c||(c=((this.characteristicsMap[this.serviceId]||{}).readIds||[])[0]),c?[3,1]:(console.warn("未找到指定service下的readId,该设备可能不支持read"),[3,3]);case 1:return[4,this._bluetoothApi.readBLECharacteristicValue({deviceId:this._deviceId,characteristicId:c,serviceId:r})];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},t.prototype.setBLEMTU=function(e){return this._bluetoothApi.setBLEMTU(tslib_1.__assign({deviceId:this._deviceId},e))},t.prototype.getBLEMTU=function(e){return void 0===e&&(e={}),this._bluetoothApi.getBLEMTU(tslib_1.__assign({deviceId:this._deviceId},e))},t.prototype.getBLEDeviceRSSI=function(){return this._bluetoothApi.getBLEDeviceRSSI({deviceId:this._deviceId})},t.prototype.destroy=function(){this.emit("destroy")},t.prototype.advertFilter=function(e){return null},t.prototype.onScanAdvert=function(e){},t.prototype.batchWrite=function(e,t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){throw new Error("DeviceAdapter.batchWrite not implemented")}))}))},t.serviceId="",t.deviceFilter=function(e,t){},t}(BlueToothBase_1.BlueToothBase);exports.DeviceAdapter=DeviceAdapter; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DeviceAdapter=void 0;var tslib_1=require("tslib"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),qcloud_iotexplorer_logger_1=tslib_1.__importDefault(require("qcloud-iotexplorer-logger")),BlueToothBase_1=require("./BlueToothBase"),types_1=require("./types"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,arrayBufferToHexStringArray=_a.arrayBufferToHexStringArray,hexToArrayBuffer=_a.hexToArrayBuffer,DeviceAdapter=function(e){function t(t){var i=t.deviceId,r=t.productId,s=t.deviceName,c=t.name,o=t.actions,n=t.bluetoothApi,a=t.h5Websocket,d=t.extendInfo,u=void 0===d?{}:d,h=t.bluetoothAdapter,v=e.call(this)||this;if(v.extendInfo={},v._name="",v._deviceId="",v._deviceName="",v._deviceConnected=!1,v._productId="",v._deviceRegistered=!1,v._services=[],v.characteristicsMap={},v._actions={},v._bluetoothApi={},v._batchWriteEnabled=!1,v._batchWriteInterval=20,!i)throw"无deviceId";if(!r)throw"productId为空";return v.baseLogger=qcloud_iotexplorer_logger_1.default.derive((function(){return{event:"ble.deviceAdapter.*",context:{bleDeviceId:v.deviceId,productId:v.productId,deviceName:v.deviceName}}})),v._h5Websocket=a,v._bluetoothApi=n,v._actions=o,v._name=c,v._deviceName=s,v._deviceId=i,v._productId=r,v.extendInfo=u||{},v.bluetoothAdapter=h,v.communicationMode=types_1.CommunicationMode.GATT,v}return tslib_1.__extends(t,e),t.prototype._getNotifyId=function(e){var t=(void 0===e?{}:e).serviceId,i=void 0===t?"":t;i=i||this.serviceId;var r=this.characteristicsMap[i]||{writeIds:[],notifyIds:[],readIds:[],indicateIds:[]};return r.notifyIds[0]||r.indicateIds[0]},Object.defineProperty(t.prototype,"_writeId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).writeIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_notifyId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).notifyIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_readId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).readIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_indicateId",{get:function(){return((this.characteristicsMap[this.serviceId]||{}).indicateIds||[])[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceId",{get:function(){return this._deviceId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"productId",{get:function(){return this._productId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceName",{get:function(){return this._deviceName},set:function(e){this._deviceName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isConnected",{get:function(){return this._deviceConnected},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"originName",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"explorerDeviceId",{get:function(){return[this._productId||"",this._deviceName||""].join("/")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"serviceId",{get:function(){return this.constructor.serviceId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"deviceInfo",{get:function(){return{productId:this.productId,deviceName:this.deviceName,deviceId:this.deviceId,explorerDeviceId:this.explorerDeviceId,name:this.originName}},enumerable:!1,configurable:!0}),t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return this.bluetoothAdapter?[4,this.bluetoothAdapter.init()]:[3,2];case 1:return e.sent(),[3,3];case 2:console.warn("DeviceAdapter未注入bluetoothAdapter实例,可能使用的不是最新版本的qcloud-iotexplorer-bluetooth-adapter模块"),e.label=3;case 3:return[2]}}))}))},t.prototype.handleBLEMessage=function(e,t){t.serviceId,t.characteristicId;return{}},t.prototype.registerDevice=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return this._deviceRegistered?[3,2]:[4,this._actions.registerDevice({deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId})];case 1:e.sent(),this._deviceRegistered=!0,e.label=2;case 2:return[2]}}))}))},t.prototype.bindDevice=function(e){var t=void 0===e?{}:e,i=t.familyId,r=void 0===i?"":i,s=t.roomId,c=void 0===s?"":s;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,this.registerDevice()];case 1:return i.sent(),e={deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId,familyId:r,roomId:c},[4,this._actions.bindDevice(e)];case 2:return i.sent(),this.emit("bind",e),[2,this.explorerDeviceId];case 3:return t=i.sent(),[2,Promise.reject(this._normalizeError(t))];case 4:return[2]}}))}))},t.prototype.onBleConnectionStateChange=function(e){var t=e.connected,i=this._deviceConnected!==t;this._deviceConnected=t,i&&(t?this.emit("connect",tslib_1.__assign({},this.deviceInfo)):this.emit("disconnect",tslib_1.__assign({},this.deviceInfo)),this.emit("bLEConnectionStateChange",{connected:t}))},t.prototype.onBLECharacteristicValueChange=function(e){var t=e.serviceId,i=e.characteristicId,r=e.value;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,s,c,o,n,a,d,u;return tslib_1.__generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,4,,5]),e=r,r instanceof ArrayBuffer&&(e=arrayBufferToHexStringArray(r)),s=this.handleBLEMessage(e,{serviceId:t,characteristicId:i})||{},c=s.shouldIgnore,o=s.reportData,n=tslib_1.__rest(s,["shouldIgnore","reportData"]),c?[2]:(this.baseLogger.debug("characteristicValueChange",{message:"设备 "+this.deviceId+" 特征值 "+i+" 变化",data:{hexValue:e}}),a=Date.now(),d=!1,this._deviceName&&o?(d=!0,"function"!=typeof this._actions.reportDeviceData?[3,2]:[4,this._actions.reportDeviceData({deviceId:this.explorerDeviceId,deviceName:this._deviceName,productId:this._productId,data:o,timestamp:a})]):[3,3]);case 1:return h.sent(),[3,3];case 2:console.warn("handleBLEMessage return should report but actions.reportDeviceData is not implement."),h.label=3;case 3:return this.emit("message",tslib_1.__assign(tslib_1.__assign({},n),{timestamp:a,dataReported:d})),[3,5];case 4:return u=h.sent(),this.baseLogger.error("eventHandlerError",{message:"onBLECharacteristicValueChange JS 异常",error:u}),[3,5];case 5:return[2]}}))}))},t.prototype.disconnectDevice=function(){this._bluetoothApi.closeBLEConnection({deviceId:this._deviceId}),this._deviceConnected=!1,this.emit("disconnect",tslib_1.__assign({},this.deviceInfo))},t.prototype.connectDevice=function(e){var t=(void 0===e?{}:e).autoNotify,i=void 0===t||t;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t,r;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:e=Date.now(),s.label=1;case 1:return s.trys.push([1,8,,9]),[4,this.init()];case 2:return s.sent(),this.baseLogger.info("connectDevice",{message:"连接设备 "+this.deviceId+" 开始",data:this.deviceInfo,metric:{type:"start"}}),this.isConnected?(this.baseLogger.info("connectDevice.alreadyConnectNoOp",{message:"已连接到设备 "+this.deviceId+", deviceAdapter.connectDevice 将不进行任何操作",data:this.deviceInfo}),[2]):[4,this._bluetoothApi.createBLEConnection({deviceId:this._deviceId})];case 3:if(s.sent(),this._deviceConnected=!0,!i)return[3,7];s.label=4;case 4:return s.trys.push([4,6,,7]),[4,this.autoNotifyCharacteristics()];case 5:return s.sent(),[3,7];case 6:throw t=s.sent(),this.isConnected&&this.disconnectDevice(),t;case 7:return this.baseLogger.info("connectDevice",{message:"连接设备 "+this.deviceId+" 成功",data:this.deviceInfo,metric:{type:"success",timeCost:Date.now()-e}}),[3,9];case 8:return r=s.sent(),(r=this._normalizeError(r)).errMsg&&r.errMsg.indexOf("already connect")>-1?(this.baseLogger.debug("connectDevice.alreadyConnect",{message:"设备 "+this.deviceId+" 已连接,无需重复进行连接操作"}),[2,Promise.resolve()]):(this.baseLogger.error("connectDevice",{message:"连接设备 "+this.deviceId+" 时发生异常",error:r,metric:{type:"fail",timeCost:Date.now()-e}}),[2,Promise.reject(r)]);case 9:return[2]}}))}))},t.prototype.autoNotifyCharacteristics=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return[4,this.getBLEDeviceServices()];case 1:return e=i.sent(),this.emit("onGetBLEDeviceServices",e),[4,this.getBLEDeviceCharacteristics()];case 2:return t=i.sent(),this.emit("onGetBLEDeviceCharacteristics",t),[4,this.notifyBLECharacteristicValueChange()];case 3:return i.sent(),[2]}}))}))},t.prototype.write=function(e,t){var i=void 0===t?{}:t,r=i.writeId,s=void 0===r?"":r,c=i.serviceId,o=void 0===c?"":c;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(t){return"string"==typeof e&&(e=hexToArrayBuffer(e)),[2,this._write(e,{writeId:s,serviceId:o})]}))}))},t.prototype._write=function(e,t){var i=void 0===t?{}:t,r=i.writeId,s=void 0===r?"":r,c=i.serviceId,o=void 0===c?"":c;return tslib_1.__awaiter(this,void 0,void 0,(function(){var t;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._bluetoothApi.writeBLECharacteristicValue({deviceId:this._deviceId,characteristicId:s||this._writeId,serviceId:o||this.serviceId,value:e})];case 1:return i.sent(),[3,3];case 2:return t=i.sent(),[2,Promise.reject(this._normalizeError(t))];case 3:return[2]}}))}))},t.prototype.getBLEDeviceServices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return[4,this._bluetoothApi.getBLEDeviceServices({deviceId:this._deviceId})];case 1:return e=t.sent().services,this.baseLogger.debug("getServices",{message:"获取到设备 "+this.deviceId+" 的 services",data:{deviceId:this.deviceId,services:e}}),this._services=e,[2,e]}}))}))},t.prototype.setCharacteristicsIds=function(e,t){var i={notifyIds:[],writeIds:[],indicateIds:[],readIds:[]},r=function(e,t){-1===e.indexOf(t)&&e.push(t)};t.forEach((function(e){var t=e.uuid,s=e.properties,c=s.notify,o=s.write,n=s.indicate,a=s.read;c?r(i.notifyIds,t):o?r(i.writeIds,t):n?r(i.indicateIds,t):a&&r(i.readIds,t)})),this.characteristicsMap[e]=i},t.prototype.getBLEDeviceCharacteristics=function(e){var t=(void 0===e?{}:e).serviceId,i=void 0===t?"":t;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e;return tslib_1.__generator(this,(function(t){switch(t.label){case 0:return i=i||this.serviceId,[4,this._bluetoothApi.getBLEDeviceCharacteristics({deviceId:this._deviceId,serviceId:i})];case 1:return e=t.sent().characteristics,this.baseLogger.debug("getCharacteristics",{message:"获取到设备 "+this.deviceId+" service "+i+" 的 characteristics",data:{deviceId:this.deviceId,serviceId:i,characteristics:e}}),this.setCharacteristicsIds(i,e),[2,e]}}))}))},t.prototype.notifyBLECharacteristicValueChange=function(e){var t=void 0===e?{}:e,i=t.characteristicId,r=void 0===i?"":i,s=t.serviceId,c=void 0===s?"":s,o=t.state,n=void 0===o||o;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return r=r||this._getNotifyId(),c=c||this.serviceId,r?[3,1]:(console.warn("未找到指定service下的notifyId,该设备可能不支持notify"),[3,3]);case 1:return[4,this._bluetoothApi.notifyBLECharacteristicValueChange({deviceId:this._deviceId,characteristicId:r,serviceId:c,state:n})];case 2:e.sent(),this.baseLogger.debug("notifyCharacteristics",{message:[(n?"开启":"关闭")+"设备 "+this.deviceId+" service "+c+" ","characteristic "+r+" 的 notify"].join(""),data:{deviceId:this._deviceId,characteristicId:r,serviceId:c,state:n}}),e.label=3;case 3:return[2]}}))}))},t.prototype.readBLECharacteristicValue=function(e){var t=void 0===e?{}:e,i=t.serviceId,r=void 0===i?"":i,s=t.characteristicId,c=void 0===s?"":s;return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){switch(e.label){case 0:return r=r||this.serviceId,c||(c=((this.characteristicsMap[this.serviceId]||{}).readIds||[])[0]),c?[3,1]:(console.warn("未找到指定service下的readId,该设备可能不支持read"),[3,3]);case 1:return[4,this._bluetoothApi.readBLECharacteristicValue({deviceId:this._deviceId,characteristicId:c,serviceId:r})];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},t.prototype.setBLEMTU=function(e){return this._bluetoothApi.setBLEMTU(tslib_1.__assign({deviceId:this._deviceId},e))},t.prototype.getBLEMTU=function(e){return void 0===e&&(e={}),this._bluetoothApi.getBLEMTU(tslib_1.__assign({deviceId:this._deviceId},e))},t.prototype.getBLEDeviceRSSI=function(){return this._bluetoothApi.getBLEDeviceRSSI({deviceId:this._deviceId})},t.prototype.destroy=function(){this.emit("destroy")},t.prototype.advertFilter=function(e){return null},t.prototype.onScanAdvert=function(e){},t.prototype.batchWrite=function(e,t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(e){throw new Error("DeviceAdapter.batchWrite not implemented")}))}))},t.serviceId="",t.deviceFilter=function(e,t){},t}(BlueToothBase_1.BlueToothBase);exports.DeviceAdapter=DeviceAdapter; | ||
//# sourceMappingURL=DeviceAdapter.js.map |
@@ -20,3 +20,2 @@ import { DeviceAdapter } from '../base'; | ||
_deviceRegistered: boolean; | ||
_characteristicsAutoNotified: boolean; | ||
_services: any[]; | ||
@@ -29,2 +28,3 @@ characteristicsMap: {}; | ||
_batchWriteInterval: number; | ||
baseLogger: import("qcloud-iotexplorer-logger").InsightLogger; | ||
_getNotifyId({ serviceId }?: { | ||
@@ -73,3 +73,3 @@ serviceId?: string; | ||
}): Promise<void>; | ||
autoNotifyCharacteristics(force?: boolean): Promise<void>; | ||
autoNotifyCharacteristics(): Promise<void>; | ||
_write(value: any, { writeId, serviceId, }?: { | ||
@@ -111,3 +111,3 @@ writeId?: string; | ||
_normalizeError(error: any): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
addCleanupTask(action: any, cleanupFn: any): void; | ||
@@ -138,3 +138,2 @@ removeCleanupTask(action: any): void; | ||
_deviceRegistered: boolean; | ||
_characteristicsAutoNotified: boolean; | ||
_services: any[]; | ||
@@ -147,2 +146,3 @@ characteristicsMap: {}; | ||
_batchWriteInterval: number; | ||
baseLogger: import("qcloud-iotexplorer-logger").InsightLogger; | ||
_getNotifyId({ serviceId }?: { | ||
@@ -191,3 +191,3 @@ serviceId?: string; | ||
}): Promise<void>; | ||
autoNotifyCharacteristics(force?: boolean): Promise<void>; | ||
autoNotifyCharacteristics(): Promise<void>; | ||
_write(value: any, { writeId, serviceId, }?: { | ||
@@ -229,3 +229,3 @@ writeId?: string; | ||
_normalizeError(error: any): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
addCleanupTask(action: any, cleanupFn: any): void; | ||
@@ -232,0 +232,0 @@ removeCleanupTask(action: any): void; |
@@ -27,3 +27,3 @@ /// <reference types="miniprogram-api-typings" /> | ||
tryCancelDisconnectDevice(deviceId: any): boolean; | ||
disconnectDevice({ deviceId, explorerDeviceId }: { | ||
disconnectDevice({ deviceId: deviceIdFromOptions, explorerDeviceId }: { | ||
deviceId?: string; | ||
@@ -30,0 +30,0 @@ explorerDeviceId?: string; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothAdapter4Mp=void 0;var tslib_1=require("tslib"),base_1=require("../base"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,arrayBufferToHexStringArray=_a.arrayBufferToHexStringArray,hexToArrayBuffer=_a.hexToArrayBuffer,delay=_a.delay,parseAdvertisData=function(e){var t=tslib_1.__assign({},e);if(e.advertisData)try{t.advertisData=arrayBufferToHexStringArray(e.advertisData)}catch(e){console.error("Parse bluetoothe device advertisData fail",e)}return e.serviceData&&"object"==typeof e.serviceData&&(t.serviceData={},Object.entries(e.serviceData).forEach((function(e){var r=tslib_1.__read(e,2),s=r[0],n=r[1];n instanceof ArrayBuffer&&(t.serviceData[s]=arrayBufferToHexStringArray(n))}))),t},BlueToothAdapter4Mp=function(e){function t(t){var r=t.bluetoothApi,s=tslib_1.__rest(t,["bluetoothApi"]),n=e.call(this,tslib_1.__assign({bluetoothApi:r},s))||this;return n._h5ChanelOpened=!1,n._localDiscoveringInUse=!1,n._h5DiscoveringInUse=!1,n._cleanupTimer=null,n._currentProductId="",n.handleH5WsMessage=null,n.deviceDelayDisconnectQueue=[],n._mpBleConnectionStateCache={},n._h5Websocket&&"function"==typeof n._h5Websocket.on&&(n.on("adapterStateChange",(function(e){var t=e.available,r=e.discovering;n.response2BlueToothChanel("onBluetoothAdapterStateChange",{available:t,discovering:r})})),n._h5Websocket.on("message",(function(e){var t=e.data,r=e.reqId;return tslib_1.__awaiter(n,void 0,void 0,(function(){var e,s,n,o,i,c,a,l,u,h,d,v,p,_,f,y,g,D,B=this;return tslib_1.__generator(this,(function(C){switch(C.label){case 0:if(console.log("bluetooth ws on message",t),"function"==typeof this.handleH5WsMessage)try{if(this.handleH5WsMessage({data:t,reqId:r}))return console.log("h5 message already handled by handleH5WsMessage implement."),[2]}catch(e){console.error("call handleH5WsMessage error",e)}switch(e=t.action,s=t.payload,e){case"reportDeviceConnectStatus":return[3,1];case"syncDeviceConnectStatus":return[3,2];case"bindDevice":return[3,3];case"registryDevice":return[3,7];case"connect":return[3,11];case"disconnect":return[3,12];case"init":return[3,13];case"batchWriteBLECharacteristicValue":return[3,17];case"callApi":return[3,21]}return[3,36];case 1:return n=s.connected,o=s.explorerDeviceId,i=s.deviceId,this.onDeviceConnectStatusChange({connected:n,explorerDeviceId:o,deviceId:i}),[3,36];case 2:return c=s.devices,(f=void 0===c?[]:c).forEach((function(e){var t=e.deviceId,r=e.connected,s=B._mpBleConnectionStateCache[t]||!1;s!==r&&(console.log("[syncDeviceConnectStatus] deviceId="+t+",","h5.connected="+r+", actualConnected="+s),B.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:t,connected:s}))})),[3,36];case 3:return C.trys.push([3,5,,6]),l=s.deviceName,u=s.productId,[4,this._actions.bindDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 4:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,6];case 5:return a=C.sent(),this.response2BlueToothChanel("response",a,r),[3,6];case 6:return[3,36];case 7:return C.trys.push([7,9,,10]),l=s.deviceName,u=s.productId,[4,this._actions.registerDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 8:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,10];case 9:return h=C.sent(),this.response2BlueToothChanel("response",h,r),[3,10];case 10:return[3,36];case 11:return console.log("h5chanel opened"),this._h5ChanelOpened=!0,[3,36];case 12:return console.log("h5chanel closed"),this._h5ChanelOpened=!1,this._h5DiscoveringInUse&&this.stopBluetoothDevicesDiscovery(!0),[3,36];case 13:return C.trys.push([13,15,,16]),[4,this.init()];case 14:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,16];case 15:return d=C.sent(),this.response2BlueToothChanel("response",d,r),[3,16];case 16:return[3,36];case 17:return C.trys.push([17,19,,20]),[4,this.batchWriteBLECharacteristicValue(s)];case 18:return C.sent(),this.response2BlueToothChanel("response",{},r),[3,20];case 19:return v=C.sent(),console.error("[BlueToothAdapter4Mp] batchWriteBLECharacteristicValue fail",v),this.response2BlueToothChanel("response",this._normalizeError(v),r),[3,20];case 20:return[3,36];case 21:p=s.api,_=s.params,C.label=22;case 22:switch(C.trys.push([22,34,,35]),console.log("call api",p,_),p){case"createBLEConnection":return[3,23];case"getBluetoothDevices":return[3,25];case"writeBLECharacteristicValue":return[3,27];case"startBluetoothDevicesDiscovery":return[3,29];case"stopBluetoothDevicesDiscovery":return[3,31]}return[3,33];case 23:return this.tryCancelDisconnectDevice(_.deviceId),[4,this._bluetoothApi.createBLEConnection(_)];case 24:return C.sent(),this.response2BlueToothChanel("response",{},r),[2];case 25:return[4,this.getBluetoothDevices()];case 26:return f=C.sent(),this.response2BlueToothChanel("response",{devices:f.map(parseAdvertisData)},r),[2];case 27:return y=_.value,console.log("calling writeBLECharacteristicValue",tslib_1.__assign(tslib_1.__assign({},_),{value:hexToArrayBuffer(y)})),[4,this._bluetoothApi.writeBLECharacteristicValue(tslib_1.__assign(tslib_1.__assign({},_),{value:hexToArrayBuffer(y)}))];case 28:return g=C.sent(),this.response2BlueToothChanel("response",g,r),[2];case 29:return[4,this.startBluetoothDevicesDiscovery({isFromH5:!0,interval:1e3})];case 30:return g=C.sent(),this.response2BlueToothChanel("response",g,r),[2];case 31:return[4,this.stopBluetoothDevicesDiscovery(!0)];case 32:return g=C.sent(),this.response2BlueToothChanel("response",g,r),[2];case 33:return[3,35];case 34:return D=C.sent(),console.error("[BlueToothAdapter4Mp] call bluetoothApi fail",D),this.response2BlueToothChanel("response",this._normalizeError(D),r),[2];case 35:return wx[p]&&wx[p](tslib_1.__assign(tslib_1.__assign({},_),{success:function(e){console.log("[BlueToothAdapter4Mp] call wx api success",e),B.response2BlueToothChanel("response",e,r)},fail:function(e){console.log("call api fail",e),B.response2BlueToothChanel("response",B._normalizeError(e),r)}})),[3,36];case 36:return[2]}}))}))}))),n}return tslib_1.__extends(t,e),t.prototype.tryCancelDisconnectDevice=function(e){var t=this.deviceDelayDisconnectQueue.findIndex((function(t){return t.deviceId===e}));if(t>-1){var r=this.deviceDelayDisconnectQueue[t];return clearTimeout(r.timer),this.deviceDelayDisconnectQueue.splice(t,1),console.log("Cancel disconnect device: "+e),!0}return console.log("Try cancel disconnect device: "+e+", but not found in queue, maybe it's already disconnected"),!1},t.prototype.disconnectDevice=function(e,t){var r=this,s=e.deviceId,n=e.explorerDeviceId;void 0===t&&(t=0),console.log("call disconnectDevice",{deviceId:s,explorerDeviceId:n});var o=this._deviceConnectStatusStore.get({deviceId:s,explorerDeviceId:n});if(null==o?void 0:o.connected)if(t>0){var i=setTimeout((function(){console.log("execute closeBLEConnection for deviceId: "+s+" after "+t+"ms"),r._bluetoothApi.closeBLEConnection({deviceId:s})}),t);console.log("Will disconnect device: "+s+" after "+t+"ms..."),this.deviceDelayDisconnectQueue.push({deviceId:s,timer:i})}else this._bluetoothApi.closeBLEConnection({deviceId:s});else console.log("call disconnectDevice, but device maybe not connected",o,this._deviceConnectStatusStore.getAll())},t.prototype.setCurrentProduct=function(e){this._currentProductId=e},t.prototype.startBluetoothDevicesDiscovery=function(t){void 0===t&&(t={});var r=t.isFromH5,s=void 0!==r&&r,n=tslib_1.__rest(t,["isFromH5"]);return s?this._h5DiscoveringInUse=!0:this._localDiscoveringInUse=!0,e.prototype.startBluetoothDevicesDiscovery.call(this,n)},t.prototype.stopBluetoothDevicesDiscovery=function(t){if(void 0===t&&(t=!1),console.log("try call stopBluetoothDevicesDiscovery,\n isFromH5: "+t+", _h5DiscoveringInUse: "+this._h5DiscoveringInUse+",\n _localDiscoveringInUse: "+this._localDiscoveringInUse),t?this._h5DiscoveringInUse=!1:this._localDiscoveringInUse=!1,this._h5DiscoveringInUse||!this._localDiscoveringInUse)return e.prototype.stopBluetoothDevicesDiscovery.call(this)},t.prototype.response2BlueToothChanel=function(e,t,r){return void 0===t&&(t={}),void 0===r&&(r=""),tslib_1.__awaiter(this,void 0,void 0,(function(){var s;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),this._h5ChanelOpened?[4,this._h5Websocket.send("Response",{action:e,payload:t},{reqId:r})]:[2];case 1:return n.sent(),[3,3];case 2:return s=n.sent(),console.warn("try send bluetooth message fail",s),[3,3];case 3:return[2]}}))}))},t.prototype.startCleanupTimer=function(){var e=this;clearTimeout(this._cleanupTimer),this._cleanupTimer=setTimeout((function(){var t=e._deviceAdapterStore.getAll().filter((function(e){return e.isConnected}));console.log("bluetooth searching or deviceMap not empty, reset cleanup timer",e._discovering,t),e._h5ChanelOpened||e._discovering||t.length?e.startCleanupTimer():e.cleanup()}),3e4)},t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t=this;return tslib_1.__generator(this,(function(r){return[2,e.prototype.init.call(this).then((function(){return t.startCleanupTimer()}))]}))}))},t.prototype.onBleConnectionStateChange=function(t){var r=t.deviceId,s=t.connected;return this.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:r,connected:s}),this._mpBleConnectionStateCache[r]=s,e.prototype.onBleConnectionStateChange.call(this,{deviceId:r,connected:s})},t.prototype.onBLECharacteristicValueChange=function(t){var r=t.deviceId,s=t.serviceId,n=t.characteristicId,o=t.value;return this.response2BlueToothChanel("onBLECharacteristicValueChange",{deviceId:r,serviceId:s,characteristicId:n,value:arrayBufferToHexStringArray(o)}),e.prototype.onBLECharacteristicValueChange.call(this,{deviceId:r,serviceId:s,characteristicId:n,value:o})},t.prototype.getBluetoothDevices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t,r=this;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return[4,e.prototype.getBluetoothDevices.call(this)];case 1:return(t=s.sent()).forEach((function(e){e.lastFoundTime=r._deviceLastFoundTime[e.deviceId]})),[2,t]}}))}))},t.prototype.onBluetoothDeviceFound=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var r,s,n=this;return tslib_1.__generator(this,(function(o){switch(o.label){case 0:return r=Date.now(),Array.isArray(null==t?void 0:t.devices)&&t.devices.forEach((function(e){n._deviceLastFoundTime[e.deviceId]=r})),[4,e.prototype.onBluetoothDeviceFound.call(this,t)];case 1:return s=o.sent(),this.response2BlueToothChanel("onBluetoothDeviceFound",{devices:s.map(parseAdvertisData)}),[2]}}))}))},t.prototype.startSearch=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(r){switch(r.label){case 0:return[4,e.prototype.startSearch.call(this,t)];case 1:return r.sent(),this.startCleanupTimer(),[2]}}))}))},t.prototype.searchDevice=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var r;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return[4,e.prototype.searchDevice.call(this,t)];case 1:return r=s.sent(),this.startCleanupTimer(),[2,r]}}))}))},t.prototype.cleanup=function(t){e.prototype.cleanup.call(this,t),this._mpBleConnectionStateCache={}},t.prototype.batchWriteBLECharacteristicValue=function(e){var t=e.deviceId,r=e.serviceId,s=e.characteristicId,n=e.values,o=e.interval;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,i,c,a,l,u,h;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:console.log("[BlueToothAdapter4Mp] batchWriteBLECharacteristicValue ",{deviceId:t,serviceId:r,characteristicId:s,values:n,interval:o}),e=!0,d.label=1;case 1:d.trys.push([1,9,10,11]),i=tslib_1.__values(n),c=i.next(),d.label=2;case 2:return c.done?[3,8]:(a=c.value,e?(e=!1,[3,5]):[3,3]);case 3:return Number.isSafeInteger(o)&&o>0?[4,delay(o)]:[3,5];case 4:d.sent(),d.label=5;case 5:return[4,this._bluetoothApi.writeBLECharacteristicValue({deviceId:t,serviceId:r,characteristicId:s,value:hexToArrayBuffer(a)})];case 6:d.sent(),d.label=7;case 7:return c=i.next(),[3,2];case 8:return[3,11];case 9:return l=d.sent(),u={error:l},[3,11];case 10:try{c&&!c.done&&(h=i.return)&&h.call(i)}finally{if(u)throw u.error}return[7];case 11:return[2]}}))}))},t}(base_1.BlueToothAdapter);exports.BlueToothAdapter4Mp=BlueToothAdapter4Mp; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueToothAdapter4Mp=void 0;var tslib_1=require("tslib"),base_1=require("../base"),qcloud_iotexplorer_appdev_sdk_1=require("qcloud-iotexplorer-appdev-sdk"),h5CallBluetoothApiWhitelist_1=require("./h5CallBluetoothApiWhitelist"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,arrayBufferToHexStringArray=_a.arrayBufferToHexStringArray,hexToArrayBuffer=_a.hexToArrayBuffer,delay=_a.delay,parseAdvertisData=function(e){var t=tslib_1.__assign({},e);if(e.advertisData)try{t.advertisData=arrayBufferToHexStringArray(e.advertisData)}catch(e){console.error("Parse bluetoothe device advertisData fail",e)}return e.serviceData&&"object"==typeof e.serviceData&&(t.serviceData={},Object.entries(e.serviceData).forEach((function(e){var r=tslib_1.__read(e,2),s=r[0],i=r[1];i instanceof ArrayBuffer&&(t.serviceData[s]=arrayBufferToHexStringArray(i))}))),t},BlueToothAdapter4Mp=function(e){function t(t){var r=t.bluetoothApi,s=tslib_1.__rest(t,["bluetoothApi"]),i=e.call(this,tslib_1.__assign({bluetoothApi:r},s))||this;return i._h5ChanelOpened=!1,i._localDiscoveringInUse=!1,i._h5DiscoveringInUse=!1,i._cleanupTimer=null,i._currentProductId="",i.handleH5WsMessage=null,i.deviceDelayDisconnectQueue=[],i._mpBleConnectionStateCache={},i._h5Websocket&&"function"==typeof i._h5Websocket.on&&(i.on("adapterStateChange",(function(e){var t=e.available,r=e.discovering;i.response2BlueToothChanel("onBluetoothAdapterStateChange",{available:t,discovering:r})})),i._h5Websocket.on("message",(function(e){var t=e.data,r=e.reqId;return tslib_1.__awaiter(i,void 0,void 0,(function(){var e,s,i,n,o,a,c,l,u,h,d,v,p,_,f,g,D,y,I=this;return tslib_1.__generator(this,(function(C){switch(C.label){case 0:if("function"==typeof this.handleH5WsMessage)try{if(this.handleH5WsMessage({data:t,reqId:r}))return[2]}catch(e){this.logger.error("handleH5WsMessage",{message:"call handleH5WsMessage error",error:e,context:{flowId:r},metric:{type:"fail"}})}switch(e=t.action,s=t.payload,e){case"reportDeviceConnectStatus":return[3,1];case"syncDeviceConnectStatus":return[3,2];case"bindDevice":return[3,3];case"registryDevice":return[3,7];case"connect":return[3,11];case"disconnect":return[3,12];case"init":return[3,13];case"batchWriteBLECharacteristicValue":return[3,17];case"callApi":return[3,21]}return[3,38];case 1:return i=s.connected,n=s.explorerDeviceId,o=s.deviceId,this.onDeviceConnectStatusChange({connected:i,explorerDeviceId:n,deviceId:o}),[3,38];case 2:return a=s.devices,(f=void 0===a?[]:a).forEach((function(e){var t=e.deviceId,r=e.connected,s=I._mpBleConnectionStateCache[t]||!1;s!==r&&I.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:t,connected:s})})),[3,38];case 3:return C.trys.push([3,5,,6]),l=s.deviceName,u=s.productId,[4,this._actions.bindDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 4:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,6];case 5:return c=C.sent(),this.response2BlueToothChanel("response",c,r),[3,6];case 6:return[3,38];case 7:return C.trys.push([7,9,,10]),l=s.deviceName,u=s.productId,[4,this._actions.registerDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 8:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,10];case 9:return h=C.sent(),this.response2BlueToothChanel("response",h,r),[3,10];case 10:return[3,38];case 11:return this.logger.info("h5Connect",{message:"H5 侧 websocket 连接建立",context:{flowId:r}}),this._h5ChanelOpened=!0,[3,38];case 12:return this.logger.info("h5Disconnect",{message:"H5 侧 websocket 连接断开",context:{flowId:r}}),this._h5ChanelOpened=!1,this._h5DiscoveringInUse&&this.stopBluetoothDevicesDiscovery(!0),[3,38];case 13:return C.trys.push([13,15,,16]),[4,this.init()];case 14:return C.sent(),this.response2BlueToothChanel("response",{code:0},r),[3,16];case 15:return d=C.sent(),this.response2BlueToothChanel("response",d,r),[3,16];case 16:return[3,38];case 17:return C.trys.push([17,19,,20]),[4,this.batchWriteBLECharacteristicValue(s)];case 18:return C.sent(),this.response2BlueToothChanel("response",{},r),[3,20];case 19:return v=C.sent(),this.response2BlueToothChanel("response",this._normalizeError(v),r),[3,20];case 20:return[3,38];case 21:if(p=s.api,_=s.params,!h5CallBluetoothApiWhitelist_1.H5_CALL_BLUETOOTH_API_WHITELIST[p])return this.logger.warn("callApi.notPermitted","H5 尝试调用白名单外的 API "+p),this.response2BlueToothChanel("response",{code:"InvalidApi",msg:"不支持 H5 调用 API "+p},r),[3,38];C.label=22;case 22:return C.trys.push([22,36,,37]),this._inited||"getSystemInfo"===p?[3,24]:(this.logger.warn("callApi.notInited","H5 在 blueToothAdapter 未初始化时调用蓝牙 API "+p),[4,this.init()]);case 23:C.sent(),C.label=24;case 24:switch(p){case"createBLEConnection":return[3,25];case"getBluetoothDevices":return[3,27];case"writeBLECharacteristicValue":return[3,29];case"startBluetoothDevicesDiscovery":return[3,31];case"stopBluetoothDevicesDiscovery":return[3,33]}return[3,35];case 25:return this.tryCancelDisconnectDevice(_.deviceId),[4,this._bluetoothApi.createBLEConnection(_)];case 26:return C.sent(),this.response2BlueToothChanel("response",{},r),[2];case 27:return[4,this.getBluetoothDevices()];case 28:return f=C.sent(),this.response2BlueToothChanel("response",{devices:f.map(parseAdvertisData)},r),[2];case 29:return g=_.value,[4,this._bluetoothApi.writeBLECharacteristicValue(tslib_1.__assign(tslib_1.__assign({},_),{value:hexToArrayBuffer(g)}))];case 30:return D=C.sent(),this.response2BlueToothChanel("response",D,r),[2];case 31:return[4,this.startBluetoothDevicesDiscovery({isFromH5:!0,interval:1e3})];case 32:return D=C.sent(),this.response2BlueToothChanel("response",D,r),[2];case 33:return[4,this.stopBluetoothDevicesDiscovery(!0)];case 34:return D=C.sent(),this.response2BlueToothChanel("response",D,r),[2];case 35:return[3,37];case 36:return y=C.sent(),this.response2BlueToothChanel("response",this._normalizeError(y),r),[2];case 37:return wx[p]&&wx[p](tslib_1.__assign(tslib_1.__assign({},_),{success:function(e){I.response2BlueToothChanel("response",e,r)},fail:function(e){I.logger.error("callWxApi",{message:"call wx api fail",error:e,context:{flowId:r},metric:{type:"fail"}}),I.response2BlueToothChanel("response",I._normalizeError(e),r)}})),[3,38];case 38:return[2]}}))}))}))),i}return tslib_1.__extends(t,e),t.prototype.tryCancelDisconnectDevice=function(e){var t=this.deviceDelayDisconnectQueue.findIndex((function(t){return t.deviceId===e}));if(t>-1){var r=this.deviceDelayDisconnectQueue[t];return clearTimeout(r.timer),this.deviceDelayDisconnectQueue.splice(t,1),this.logger.info("disconnectDevice.cancel",{message:"取消蓝牙设备 "+e+" 的延迟断开",data:{deviceId:e}}),!0}return!1},t.prototype.disconnectDevice=function(e,t){var r=this,s=e.deviceId,i=e.explorerDeviceId;void 0===t&&(t=0);var n=!1,o=s;if(i){var a=this.getDeviceAdapter({deviceId:o,explorerDeviceId:i});a&&(o=a.deviceId,n=!!this._mpBleConnectionStateCache[a.deviceId])}else o&&(n=!!this._mpBleConnectionStateCache[o]);if(n){var c=function(){r.logger.info("disconnectDevice.exec",{message:"将断开与设备 "+o+" 的蓝牙连接",data:{deviceId:o},metric:{type:"start"}}),r._bluetoothApi.closeBLEConnection({deviceId:o}).then((function(){r.logger.info("disconnectDevice.exec",{message:"断开与设备 "+o+" 的蓝牙连接成功",data:{deviceId:o},metric:{type:"success"}})})).catch((function(e){r.logger.error("disconnectDevice.exec",{message:"断开与设备 "+o+" 的蓝牙连接失败",data:{deviceId:o},error:e,metric:{type:"fail"}})}))};if(t>0){this.logger.warn("disconnectDevice.enqueue",{message:"adapter 将在 "+t+"ms 后断开与设备 "+o+" 的蓝牙连接",data:{deviceId:o,explorerDeviceId:i,delay:t}});var l=setTimeout((function(){r._mpBleConnectionStateCache[o]?c():r.logger.info("disconnectDevice.noop",{message:"延迟 "+t+"ms 后与设备 "+o+" 的蓝牙连接已断开,disconnectDevice 将不进行任何操作",data:{deviceId:o,explorerDeviceId:i}})}),t);this.deviceDelayDisconnectQueue.push({deviceId:o,timer:l})}else c()}else this.logger.warn("disconnectDevice.noop",{message:"adapter 未记录设备 "+o+" 的连接状态,disconnectDevice 将不进行任何操作"})},t.prototype.setCurrentProduct=function(e){this._currentProductId=e},t.prototype.startBluetoothDevicesDiscovery=function(t){void 0===t&&(t={});var r=t.isFromH5,s=void 0!==r&&r,i=tslib_1.__rest(t,["isFromH5"]);return s?this._h5DiscoveringInUse=!0:this._localDiscoveringInUse=!0,this.logger.info("startBluetoothDevicesDiscovery",{message:["isFromH5: "+s,"_h5DiscoveringInUse: "+this._h5DiscoveringInUse,"_localDiscoveringInUse: "+this._localDiscoveringInUse].join(", ")}),e.prototype.startBluetoothDevicesDiscovery.call(this,i)},t.prototype.stopBluetoothDevicesDiscovery=function(t){if(void 0===t&&(t=!1),this.logger.info("stopBluetoothDevicesDiscovery",{message:["isFromH5: "+t,"_h5DiscoveringInUse: "+this._h5DiscoveringInUse,"_localDiscoveringInUse: "+this._localDiscoveringInUse].join(", ")}),t?this._h5DiscoveringInUse=!1:this._localDiscoveringInUse=!1,this._h5DiscoveringInUse||!this._localDiscoveringInUse)return e.prototype.stopBluetoothDevicesDiscovery.call(this)},t.prototype.response2BlueToothChanel=function(e,t,r){return void 0===t&&(t={}),void 0===r&&(r=""),tslib_1.__awaiter(this,void 0,void 0,(function(){var s;return tslib_1.__generator(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),this._h5ChanelOpened?[4,this._h5Websocket.send("Response",{action:e,payload:t},{reqId:r})]:[2];case 1:return i.sent(),[3,3];case 2:return s=i.sent(),this.logger.error("response2BlueToothChanel",{message:"try send bluetooth message fail",context:{flowId:r},error:s,metric:{type:"fail"}}),[3,3];case 3:return[2]}}))}))},t.prototype.startCleanupTimer=function(){var e=this;clearTimeout(this._cleanupTimer),this._cleanupTimer=setTimeout((function(){var t=e._deviceAdapterStore.getAll().filter((function(e){return e.isConnected}));e._h5ChanelOpened||e._discovering||t.length?e.startCleanupTimer():e.cleanup()}),3e4)},t.prototype.init=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t=this;return tslib_1.__generator(this,(function(r){return[2,e.prototype.init.call(this).then((function(){return t.startCleanupTimer()}))]}))}))},t.prototype.onBleConnectionStateChange=function(t){var r=t.deviceId,s=t.connected;return this.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:r,connected:s}),this._mpBleConnectionStateCache[r]=s,e.prototype.onBleConnectionStateChange.call(this,{deviceId:r,connected:s})},t.prototype.onBLECharacteristicValueChange=function(t){var r=t.deviceId,s=t.serviceId,i=t.characteristicId,n=t.value;return this.response2BlueToothChanel("onBLECharacteristicValueChange",{deviceId:r,serviceId:s,characteristicId:i,value:arrayBufferToHexStringArray(n)}),e.prototype.onBLECharacteristicValueChange.call(this,{deviceId:r,serviceId:s,characteristicId:i,value:n})},t.prototype.getBluetoothDevices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t,r=this;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return[4,e.prototype.getBluetoothDevices.call(this)];case 1:return(t=s.sent()).forEach((function(e){e.lastFoundTime=r._deviceLastFoundTime[e.deviceId]})),[2,t]}}))}))},t.prototype.onBluetoothDeviceFound=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var r,s,i=this;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return r=Date.now(),Array.isArray(null==t?void 0:t.devices)&&t.devices.forEach((function(e){i._deviceLastFoundTime[e.deviceId]=r})),[4,e.prototype.onBluetoothDeviceFound.call(this,t)];case 1:return s=n.sent(),this.response2BlueToothChanel("onBluetoothDeviceFound",{devices:s.map(parseAdvertisData)}),[2]}}))}))},t.prototype.startSearch=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(r){switch(r.label){case 0:return[4,e.prototype.startSearch.call(this,t)];case 1:return r.sent(),this.startCleanupTimer(),[2]}}))}))},t.prototype.searchDevice=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var r;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return[4,e.prototype.searchDevice.call(this,t)];case 1:return r=s.sent(),this.startCleanupTimer(),[2,r]}}))}))},t.prototype.cleanup=function(t){this._mpBleConnectionStateCache={},e.prototype.cleanup.call(this,t)},t.prototype.batchWriteBLECharacteristicValue=function(e){var t=e.deviceId,r=e.serviceId,s=e.characteristicId,i=e.values,n=e.interval;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,o,a,c,l,u,h;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:e=!0,d.label=1;case 1:d.trys.push([1,9,10,11]),o=tslib_1.__values(i),a=o.next(),d.label=2;case 2:return a.done?[3,8]:(c=a.value,e?(e=!1,[3,5]):[3,3]);case 3:return Number.isSafeInteger(n)&&n>0?[4,delay(n)]:[3,5];case 4:d.sent(),d.label=5;case 5:return[4,this._bluetoothApi.writeBLECharacteristicValue({deviceId:t,serviceId:r,characteristicId:s,value:hexToArrayBuffer(c)})];case 6:d.sent(),d.label=7;case 7:return a=o.next(),[3,2];case 8:return[3,11];case 9:return l=d.sent(),u={error:l},[3,11];case 10:try{a&&!a.done&&(h=o.return)&&h.call(o)}finally{if(u)throw u.error}return[7];case 11:return[2]}}))}))},t}(base_1.BlueToothAdapter);exports.BlueToothAdapter4Mp=BlueToothAdapter4Mp; | ||
//# sourceMappingURL=BlueToothAdapter4Mp.js.map |
@@ -14,3 +14,2 @@ import { DeviceAdapter } from '../base'; | ||
_deviceRegistered: boolean; | ||
_characteristicsAutoNotified: boolean; | ||
_services: any[]; | ||
@@ -23,2 +22,3 @@ characteristicsMap: {}; | ||
_batchWriteInterval: number; | ||
baseLogger: import("qcloud-iotexplorer-logger").InsightLogger; | ||
_getNotifyId({ serviceId }?: { | ||
@@ -67,3 +67,3 @@ serviceId?: string; | ||
}): Promise<void>; | ||
autoNotifyCharacteristics(force?: boolean): Promise<void>; | ||
autoNotifyCharacteristics(): Promise<void>; | ||
write(data: any, { writeId, serviceId, }?: { | ||
@@ -113,3 +113,3 @@ writeId?: string; | ||
_normalizeError(error: any): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
addCleanupTask(action: any, cleanupFn: any): void; | ||
@@ -134,3 +134,2 @@ removeCleanupTask(action: any): void; | ||
_deviceRegistered: boolean; | ||
_characteristicsAutoNotified: boolean; | ||
_services: any[]; | ||
@@ -143,2 +142,3 @@ characteristicsMap: {}; | ||
_batchWriteInterval: number; | ||
baseLogger: import("qcloud-iotexplorer-logger").InsightLogger; | ||
_getNotifyId({ serviceId }?: { | ||
@@ -187,3 +187,3 @@ serviceId?: string; | ||
}): Promise<void>; | ||
autoNotifyCharacteristics(force?: boolean): Promise<void>; | ||
autoNotifyCharacteristics(): Promise<void>; | ||
write(data: any, { writeId, serviceId, }?: { | ||
@@ -233,3 +233,3 @@ writeId?: string; | ||
_normalizeError(error: any): any; | ||
cleanup(action?: string): void; | ||
cleanup(action?: string, optional?: boolean): void; | ||
addCleanupTask(action: any, cleanupFn: any): void; | ||
@@ -236,0 +236,0 @@ removeCleanupTask(action: any): void; |
{ | ||
"name": "qcloud-iotexplorer-bluetooth-adapter", | ||
"version": "0.12.20", | ||
"version": "0.12.21", | ||
"description": "", | ||
@@ -20,3 +20,4 @@ "main": "lib/index.js", | ||
"qcloud-iotexplorer-appdev-sdk": "^2.3.13", | ||
"qcloud-iotexplorer-common-libs": "^0.12.15", | ||
"qcloud-iotexplorer-common-libs": "^0.12.16", | ||
"qcloud-iotexplorer-logger": "^0.0.11", | ||
"tslib": "^2.0.1" | ||
@@ -27,3 +28,3 @@ }, | ||
}, | ||
"gitHead": "d208071b4debbdfa750bbe038599f9151748bf0b" | ||
"gitHead": "572dae28019e882a5527edc60cd2acb8cc61ac1f" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
199374
57
1371
6
+ Addedqcloud-iotexplorer-logger@0.0.11(transitive)