Socket
Socket
Sign inDemoInstall

qcloud-iotexplorer-bluetooth-adapter

Package Overview
Dependencies
5
Maintainers
5
Versions
164
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.12.3 to 0.12.4

6

lib/base/BlueToothAdapter.d.ts

@@ -28,3 +28,2 @@ /// <reference types="miniprogram-api-typings" />

_onDeviceFoundThrottle: number;
_setOnDeviceFoundThrottle: any;
_onBluetoothScanAdvertisingHandler: any;

@@ -43,2 +42,3 @@ _initPromise: any;

protected _mpDisableRefreshCache: boolean;
protected _deviceLastFoundTime: Record<string, number>;
constructor({ deviceAdapters, actions, bluetoothApi, h5Websocket, devMode, ignoreAnonymousDevices, mpDisableRefreshCache, }: BlueToothAdapterProps);

@@ -66,3 +66,3 @@ get devMode(): boolean;

}): void;
startBluetoothDevicesDiscovery(params?: any): any;
startBluetoothDevicesDiscovery(params?: Record<string, unknown>): any;
/**

@@ -96,3 +96,3 @@ * 1. 本地决定stop,看h5是否在搜,如果在搜则忽略

*/
startSearch({ serviceId, serviceIds, ignoreDeviceIds, ignoreServiceIds, onSearch, onError, timeout, extendInfo, DeviceAdapter, startBluetoothDevicesDiscoveryParams, }: StartSearchParams): Promise<any>;
startSearch({ serviceId, serviceIds, ignoreDeviceIds, ignoreServiceIds, onSearch, onError, timeout, extendInfo, DeviceAdapter, ignoreCachedDevices, startBluetoothDevicesDiscoveryParams, }: StartSearchParams): Promise<any>;
stopSearch(): void;

@@ -99,0 +99,0 @@ /**

@@ -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"),throttle_1=require("../libs/throttle"),types_1=require("./types"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,isEmpty=_a.isEmpty,noop=_a.noop,delay=_a.delay,DefaultOnDeviceFoundThrottle=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=DefaultOnDeviceFoundThrottle,v._setOnDeviceFoundThrottle=noop,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._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],console.log("specific serviceId: ",c);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})),console.log("support serviceIds",c)}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,this._setOnDeviceFoundThrottle(e)},t.prototype.resetOnDeviceFoundThrottle=function(){this._onDeviceFoundThrottle=DefaultOnDeviceFoundThrottle,this._setOnDeviceFoundThrottle(DefaultOnDeviceFoundThrottle)},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"},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=throttle_1.throttle(this._onDeviceFoundThrottle,(function(e){return d.onBluetoothDeviceFound(e)})),this._setOnDeviceFoundThrottle=function(e){n.updateDelay(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,[2,this._ignoreAnonymousDevices?e.filter((function(e){return"未知设备"!==e.name})):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{console.log("onBluetoothDeviceFound",t,i),"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.startBluetoothDevicesDiscoveryParams;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,r,n,s,d,l,h=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=function(e){var t={};return e.forEach((function(e){return 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}))},s=function(e){h.stopSearch(),u(e)},D.label=2;case 2:return D.trys.push([2,4,,5]),[4,this.startBluetoothDevicesDiscovery(f)];case 3:return D.sent(),this._onBluetoothDeviceFoundHandler=function(t){try{var r=n(h._filterDevices({devices:t,serviceIds:i,ignoreDeviceIds:o,ignoreServiceIds:c,extendInfo:p,DeviceAdapter:_}));e=r.length,a(r)}catch(e){console.log("onSearch error",e),s(h._normalizeError(e))}},this.onBluetoothDeviceFound(),d=function(e){e.available||s(h._normalizeError({errCode:10001}))},this.on("adapterStateChange",d),this.addCleanupTask("startSearch",(function(){h._onBluetoothDeviceFoundHandler=null,h.off("adapterStateChange",d)})),setTimeout((function(){e||s("未发现设备,请确认设备已开启")}),v),[3,5];case 4:throw l=D.sent(),this.cleanup("startSearch"),this._normalizeError(l);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});console.log("matchedDevices: ",d),d.length>0&&(console.log("doFindDevice",d[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"),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;
//# sourceMappingURL=BlueToothAdapter.js.map

@@ -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){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;
//# sourceMappingURL=BlueToothBase.js.map

@@ -79,3 +79,4 @@ /// <reference types="miniprogram-api-typings" />

DeviceAdapter?: DeviceAdapterFactory;
startBluetoothDevicesDiscoveryParams?: any;
startBluetoothDevicesDiscoveryParams?: Record<string, unknown>;
ignoreCachedDevices?: boolean;
}

@@ -82,0 +83,0 @@ export interface StartSearchParams extends SearchDeviceBaseParams {

@@ -0,1 +1,2 @@

/// <reference types="miniprogram-api-typings" />
import { BlueToothAdapter, BlueToothDeviceInfo } from '../base';

@@ -31,3 +32,6 @@ import { BlueToothAdapterProps, SearchDeviceParams, StartSearchParams } from '../base/types';

setCurrentProduct(productId: any): void;
startBluetoothDevicesDiscovery(isFromH5?: boolean): any;
startBluetoothDevicesDiscovery({ isFromH5, ...others }?: {
isFromH5?: boolean;
[paramName: string]: unknown;
}): any;
/**

@@ -63,3 +67,4 @@ * 1. 本地决定stop,看h5是否在搜,如果在搜则忽略

}): Promise<void>;
onBluetoothDeviceFound(params: any): Promise<void>;
getBluetoothDevices(): Promise<any>;
onBluetoothDeviceFound(foundResult?: WechatMiniprogram.OnBluetoothDeviceFoundCallbackResult): Promise<void>;
startSearch(params: StartSearchParams): Promise<void>;

@@ -66,0 +71,0 @@ searchDevice(params: SearchDeviceParams): Promise<BlueToothDeviceInfo>;

@@ -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,parseAdvertisData=function(e){var t=tslib_1.__assign({},e);if(t.advertisData)try{t.advertisData=arrayBufferToHexStringArray(t.advertisData)}catch(e){console.error("Parse bluetoothe device advertisData fail",e)}return t},BlueToothAdapter4Mp=function(e){function t(t){var o=t.bluetoothApi,n=tslib_1.__rest(t,["bluetoothApi"]),s=e.call(this,tslib_1.__assign({bluetoothApi:o},n))||this;return s._h5ChanelOpened=!1,s._localDiscoveringInUse=!1,s._h5DiscoveringInUse=!1,s._cleanupTimer=null,s._currentProductId="",s.handleH5WsMessage=null,s.deviceDelayDisconnectQueue=[],s._mpBleConnectionStateCache={},s._h5Websocket&&"function"==typeof s._h5Websocket.on&&(s.on("adapterStateChange",(function(e){var t=e.available,o=e.discovering;s.response2BlueToothChanel("onBluetoothAdapterStateChange",{available:t,discovering:o})})),s._h5Websocket.on("message",(function(e){var t=e.data,o=e.reqId;return tslib_1.__awaiter(s,void 0,void 0,(function(){var e,n,s,r,i,c,a,l,u,h,d,p,v,_,g,f,D,y=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:o}))return console.log("h5 message already handled by handleH5WsMessage implement."),[2]}catch(e){console.error("call handleH5WsMessage error",e)}switch(e=t.action,n=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"callApi":return[3,17]}return[3,32];case 1:return s=n.connected,r=n.explorerDeviceId,i=n.deviceId,this.onDeviceConnectStatusChange({connected:s,explorerDeviceId:r,deviceId:i}),[3,32];case 2:c=n.devices,(_=void 0===c?[]:c).forEach((function(e){var t=e.deviceId,o=e.connected,n=y._mpBleConnectionStateCache[t]||!1;n!==o&&(console.log("[syncDeviceConnectStatus] deviceId="+t+",","h5.connected="+o+", actualConnected="+n),y.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:t,connected:n}))})),C.label=3;case 3:return C.trys.push([3,5,,6]),l=n.deviceName,u=n.productId,[4,this._actions.bindDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 4:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,6];case 5:return a=C.sent(),this.response2BlueToothChanel("response",a,o),[3,6];case 6:return[3,32];case 7:return C.trys.push([7,9,,10]),l=n.deviceName,u=n.productId,[4,this._actions.registerDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 8:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,10];case 9:return h=C.sent(),this.response2BlueToothChanel("response",h,o),[3,10];case 10:return[3,32];case 11:return console.log("h5chanel opened"),this._h5ChanelOpened=!0,[3,32];case 12:return console.log("h5chanel closed"),this._h5ChanelOpened=!1,this._h5DiscoveringInUse&&this.stopBluetoothDevicesDiscovery(!0),[3,32];case 13:return C.trys.push([13,15,,16]),[4,this.init()];case 14:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,16];case 15:return d=C.sent(),this.response2BlueToothChanel("response",d,o),[3,16];case 16:return[3,32];case 17:p=n.api,v=n.params,C.label=18;case 18:switch(C.trys.push([18,30,,31]),console.log("call api",p,v),p){case"createBLEConnection":return[3,19];case"getBluetoothDevices":return[3,21];case"writeBLECharacteristicValue":return[3,23];case"startBluetoothDevicesDiscovery":return[3,25];case"stopBluetoothDevicesDiscovery":return[3,27]}return[3,29];case 19:return this.tryCancelDisconnectDevice(v.deviceId),[4,this._bluetoothApi.createBLEConnection(v)];case 20:return C.sent(),this.response2BlueToothChanel("response",{},o),[2];case 21:return[4,this.getBluetoothDevices()];case 22:return _=C.sent(),this.response2BlueToothChanel("response",{devices:_.map(parseAdvertisData)},o),[2];case 23:return g=v.value,console.log("calling writeBLECharacteristicValue",tslib_1.__assign(tslib_1.__assign({},v),{value:hexToArrayBuffer(g)})),[4,this._bluetoothApi.writeBLECharacteristicValue(tslib_1.__assign(tslib_1.__assign({},v),{value:hexToArrayBuffer(g)}))];case 24:return f=C.sent(),this.response2BlueToothChanel("response",f,o),[2];case 25:return[4,this.startBluetoothDevicesDiscovery(!0)];case 26:return f=C.sent(),this.response2BlueToothChanel("response",f,o),[2];case 27:return[4,this.stopBluetoothDevicesDiscovery(!0)];case 28:return f=C.sent(),this.response2BlueToothChanel("response",f,o),[2];case 29:return[3,31];case 30:return D=C.sent(),console.error("[BlueToothAdapter4Mp] call bluetoothApi fail",D),this.response2BlueToothChanel("response",this._normalizeError(D),o),[2];case 31:return wx[p]&&wx[p](tslib_1.__assign(tslib_1.__assign({},v),{success:function(e){console.log("[BlueToothAdapter4Mp] call wx api success",e),y.response2BlueToothChanel("response",e,o)},fail:function(e){console.log("call api fail",e),y.response2BlueToothChanel("response",y._normalizeError(e),o)}})),[3,32];case 32:return[2]}}))}))}))),s}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 o=this.deviceDelayDisconnectQueue[t];return clearTimeout(o.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 o=this,n=e.deviceId,s=e.explorerDeviceId;void 0===t&&(t=0),console.log("call disconnectDevice",{deviceId:n,explorerDeviceId:s});var r=this._deviceConnectStatusStore.get({deviceId:n,explorerDeviceId:s});if(null==r?void 0:r.connected)if(t>0){var i=setTimeout((function(){console.log("execute closeBLEConnection for deviceId: "+n+" after "+t+"ms"),o._bluetoothApi.closeBLEConnection({deviceId:n})}),t);console.log("Will disconnect device: "+n+" after "+t+"ms..."),this.deviceDelayDisconnectQueue.push({deviceId:n,timer:i})}else this._bluetoothApi.closeBLEConnection({deviceId:n});else console.log("call disconnectDevice, but device maybe not connected",r,this._deviceConnectStatusStore.getAll())},t.prototype.setCurrentProduct=function(e){this._currentProductId=e},t.prototype.startBluetoothDevicesDiscovery=function(t){return void 0===t&&(t=!1),t?this._h5DiscoveringInUse=!0:this._localDiscoveringInUse=!0,e.prototype.startBluetoothDevicesDiscovery.call(this)},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,o){return void 0===t&&(t={}),void 0===o&&(o=""),tslib_1.__awaiter(this,void 0,void 0,(function(){var n;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),this._h5ChanelOpened?(console.log("response2BlueToothChanel",e,t),[4,this._h5Websocket.send("Response",{action:e,payload:t},{reqId:o})]):(console.log("h5 chanel not opened"),[2]);case 1:return s.sent(),[3,3];case 2:return n=s.sent(),console.warn("try send bluetooth message fail",n),[3,3];case 3:return[2]}}))}))},t.prototype.startCleanupTimer=function(){var e=this;clearTimeout(this._cleanupTimer),console.log("start cleanup timer"),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(o){return[2,e.prototype.init.call(this).then((function(){return t.startCleanupTimer()}))]}))}))},t.prototype.onBleConnectionStateChange=function(t){var o=t.deviceId,n=t.connected;return this.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:o,connected:n}),this._mpBleConnectionStateCache[o]=n,e.prototype.onBleConnectionStateChange.call(this,{deviceId:o,connected:n})},t.prototype.onBLECharacteristicValueChange=function(t){var o=t.deviceId,n=t.serviceId,s=t.characteristicId,r=t.value;return this.response2BlueToothChanel("onBLECharacteristicValueChange",{deviceId:o,serviceId:n,characteristicId:s,value:arrayBufferToHexStringArray(r)}),e.prototype.onBLECharacteristicValueChange.call(this,{deviceId:o,serviceId:n,characteristicId:s,value:r})},t.prototype.onBluetoothDeviceFound=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var o;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return[4,e.prototype.onBluetoothDeviceFound.call(this,t)];case 1:return o=n.sent(),this.response2BlueToothChanel("onBluetoothDeviceFound",{devices:o.map(parseAdvertisData)}),[2]}}))}))},t.prototype.startSearch=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(o){switch(o.label){case 0:return[4,e.prototype.startSearch.call(this,t)];case 1:return o.sent(),this.startCleanupTimer(),[2]}}))}))},t.prototype.searchDevice=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var o;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return[4,e.prototype.searchDevice.call(this,t)];case 1:return o=n.sent(),this.startCleanupTimer(),[2,o]}}))}))},t.prototype.cleanup=function(t){e.prototype.cleanup.call(this,t),this._mpBleConnectionStateCache={}},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"),_a=qcloud_iotexplorer_appdev_sdk_1.AppDevSdk.utils,arrayBufferToHexStringArray=_a.arrayBufferToHexStringArray,hexToArrayBuffer=_a.hexToArrayBuffer,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 o=tslib_1.__read(e,2),n=o[0],r=o[1];r instanceof ArrayBuffer&&(t.serviceData[n]=arrayBufferToHexStringArray(r))}))),t},BlueToothAdapter4Mp=function(e){function t(t){var o=t.bluetoothApi,n=tslib_1.__rest(t,["bluetoothApi"]),r=e.call(this,tslib_1.__assign({bluetoothApi:o},n))||this;return r._h5ChanelOpened=!1,r._localDiscoveringInUse=!1,r._h5DiscoveringInUse=!1,r._cleanupTimer=null,r._currentProductId="",r.handleH5WsMessage=null,r.deviceDelayDisconnectQueue=[],r._mpBleConnectionStateCache={},r._h5Websocket&&"function"==typeof r._h5Websocket.on&&(r.on("adapterStateChange",(function(e){var t=e.available,o=e.discovering;r.response2BlueToothChanel("onBluetoothAdapterStateChange",{available:t,discovering:o})})),r._h5Websocket.on("message",(function(e){var t=e.data,o=e.reqId;return tslib_1.__awaiter(r,void 0,void 0,(function(){var e,n,r,s,i,c,a,l,u,h,d,p,v,_,f,D,g,y=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:o}))return console.log("h5 message already handled by handleH5WsMessage implement."),[2]}catch(e){console.error("call handleH5WsMessage error",e)}switch(e=t.action,n=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"callApi":return[3,17]}return[3,32];case 1:return r=n.connected,s=n.explorerDeviceId,i=n.deviceId,this.onDeviceConnectStatusChange({connected:r,explorerDeviceId:s,deviceId:i}),[3,32];case 2:c=n.devices,(_=void 0===c?[]:c).forEach((function(e){var t=e.deviceId,o=e.connected,n=y._mpBleConnectionStateCache[t]||!1;n!==o&&(console.log("[syncDeviceConnectStatus] deviceId="+t+",","h5.connected="+o+", actualConnected="+n),y.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:t,connected:n}))})),C.label=3;case 3:return C.trys.push([3,5,,6]),l=n.deviceName,u=n.productId,[4,this._actions.bindDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 4:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,6];case 5:return a=C.sent(),this.response2BlueToothChanel("response",a,o),[3,6];case 6:return[3,32];case 7:return C.trys.push([7,9,,10]),l=n.deviceName,u=n.productId,[4,this._actions.registerDevice({productId:this.devMode&&u?u:this._currentProductId,deviceName:l})];case 8:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,10];case 9:return h=C.sent(),this.response2BlueToothChanel("response",h,o),[3,10];case 10:return[3,32];case 11:return console.log("h5chanel opened"),this._h5ChanelOpened=!0,[3,32];case 12:return console.log("h5chanel closed"),this._h5ChanelOpened=!1,this._h5DiscoveringInUse&&this.stopBluetoothDevicesDiscovery(!0),[3,32];case 13:return C.trys.push([13,15,,16]),[4,this.init()];case 14:return C.sent(),this.response2BlueToothChanel("response",{code:0},o),[3,16];case 15:return d=C.sent(),this.response2BlueToothChanel("response",d,o),[3,16];case 16:return[3,32];case 17:p=n.api,v=n.params,C.label=18;case 18:switch(C.trys.push([18,30,,31]),console.log("call api",p,v),p){case"createBLEConnection":return[3,19];case"getBluetoothDevices":return[3,21];case"writeBLECharacteristicValue":return[3,23];case"startBluetoothDevicesDiscovery":return[3,25];case"stopBluetoothDevicesDiscovery":return[3,27]}return[3,29];case 19:return this.tryCancelDisconnectDevice(v.deviceId),[4,this._bluetoothApi.createBLEConnection(v)];case 20:return C.sent(),this.response2BlueToothChanel("response",{},o),[2];case 21:return[4,this.getBluetoothDevices()];case 22:return _=C.sent(),this.response2BlueToothChanel("response",{devices:_.map(parseAdvertisData)},o),[2];case 23:return f=v.value,console.log("calling writeBLECharacteristicValue",tslib_1.__assign(tslib_1.__assign({},v),{value:hexToArrayBuffer(f)})),[4,this._bluetoothApi.writeBLECharacteristicValue(tslib_1.__assign(tslib_1.__assign({},v),{value:hexToArrayBuffer(f)}))];case 24:return D=C.sent(),this.response2BlueToothChanel("response",D,o),[2];case 25:return[4,this.startBluetoothDevicesDiscovery({isFromH5:!0,interval:1e3})];case 26:return D=C.sent(),this.response2BlueToothChanel("response",D,o),[2];case 27:return[4,this.stopBluetoothDevicesDiscovery(!0)];case 28:return D=C.sent(),this.response2BlueToothChanel("response",D,o),[2];case 29:return[3,31];case 30:return g=C.sent(),console.error("[BlueToothAdapter4Mp] call bluetoothApi fail",g),this.response2BlueToothChanel("response",this._normalizeError(g),o),[2];case 31:return wx[p]&&wx[p](tslib_1.__assign(tslib_1.__assign({},v),{success:function(e){console.log("[BlueToothAdapter4Mp] call wx api success",e),y.response2BlueToothChanel("response",e,o)},fail:function(e){console.log("call api fail",e),y.response2BlueToothChanel("response",y._normalizeError(e),o)}})),[3,32];case 32:return[2]}}))}))}))),r}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 o=this.deviceDelayDisconnectQueue[t];return clearTimeout(o.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 o=this,n=e.deviceId,r=e.explorerDeviceId;void 0===t&&(t=0),console.log("call disconnectDevice",{deviceId:n,explorerDeviceId:r});var s=this._deviceConnectStatusStore.get({deviceId:n,explorerDeviceId:r});if(null==s?void 0:s.connected)if(t>0){var i=setTimeout((function(){console.log("execute closeBLEConnection for deviceId: "+n+" after "+t+"ms"),o._bluetoothApi.closeBLEConnection({deviceId:n})}),t);console.log("Will disconnect device: "+n+" after "+t+"ms..."),this.deviceDelayDisconnectQueue.push({deviceId:n,timer:i})}else this._bluetoothApi.closeBLEConnection({deviceId:n});else console.log("call disconnectDevice, but device maybe not connected",s,this._deviceConnectStatusStore.getAll())},t.prototype.setCurrentProduct=function(e){this._currentProductId=e},t.prototype.startBluetoothDevicesDiscovery=function(t){void 0===t&&(t={});var o=t.isFromH5,n=void 0!==o&&o,r=tslib_1.__rest(t,["isFromH5"]);return n?this._h5DiscoveringInUse=!0:this._localDiscoveringInUse=!0,e.prototype.startBluetoothDevicesDiscovery.call(this,r)},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,o){return void 0===t&&(t={}),void 0===o&&(o=""),tslib_1.__awaiter(this,void 0,void 0,(function(){var n;return tslib_1.__generator(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),this._h5ChanelOpened?[4,this._h5Websocket.send("Response",{action:e,payload:t},{reqId:o})]:[2];case 1:return r.sent(),[3,3];case 2:return n=r.sent(),console.warn("try send bluetooth message fail",n),[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(o){return[2,e.prototype.init.call(this).then((function(){return t.startCleanupTimer()}))]}))}))},t.prototype.onBleConnectionStateChange=function(t){var o=t.deviceId,n=t.connected;return this.response2BlueToothChanel("onBLEConnectionStateChange",{deviceId:o,connected:n}),this._mpBleConnectionStateCache[o]=n,e.prototype.onBleConnectionStateChange.call(this,{deviceId:o,connected:n})},t.prototype.onBLECharacteristicValueChange=function(t){var o=t.deviceId,n=t.serviceId,r=t.characteristicId,s=t.value;return this.response2BlueToothChanel("onBLECharacteristicValueChange",{deviceId:o,serviceId:n,characteristicId:r,value:arrayBufferToHexStringArray(s)}),e.prototype.onBLECharacteristicValueChange.call(this,{deviceId:o,serviceId:n,characteristicId:r,value:s})},t.prototype.getBluetoothDevices=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var t,o=this;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return[4,e.prototype.getBluetoothDevices.call(this)];case 1:return(t=n.sent()).forEach((function(e){e.lastFoundTime=o._deviceLastFoundTime[e.deviceId]})),[2,t]}}))}))},t.prototype.onBluetoothDeviceFound=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var o,n,r=this;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return o=Date.now(),Array.isArray(t.devices)&&t.devices.forEach((function(e){r._deviceLastFoundTime[e.deviceId]=o})),[4,e.prototype.onBluetoothDeviceFound.call(this,t)];case 1:return n=s.sent(),this.response2BlueToothChanel("onBluetoothDeviceFound",{devices:n.map(parseAdvertisData)}),[2]}}))}))},t.prototype.startSearch=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){return tslib_1.__generator(this,(function(o){switch(o.label){case 0:return[4,e.prototype.startSearch.call(this,t)];case 1:return o.sent(),this.startCleanupTimer(),[2]}}))}))},t.prototype.searchDevice=function(t){return tslib_1.__awaiter(this,void 0,void 0,(function(){var o;return tslib_1.__generator(this,(function(n){switch(n.label){case 0:return[4,e.prototype.searchDevice.call(this,t)];case 1:return o=n.sent(),this.startCleanupTimer(),[2,o]}}))}))},t.prototype.cleanup=function(t){e.prototype.cleanup.call(this,t),this._mpBleConnectionStateCache={}},t}(base_1.BlueToothAdapter);exports.BlueToothAdapter4Mp=BlueToothAdapter4Mp;
//# sourceMappingURL=BlueToothAdapter4Mp.js.map
{
"name": "qcloud-iotexplorer-bluetooth-adapter",
"version": "0.12.3",
"version": "0.12.4",
"description": "",

@@ -26,3 +26,3 @@ "main": "lib/index.js",

},
"gitHead": "819b06cdd6eaa78d3513b0070d9f1e68814381d8"
"gitHead": "3021168608c0306697ad6f655890eaf533d08145"
}

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc