Socket
Socket
Sign inDemoInstall

qcloud-iotexplorer-bluetooth-adapter

Package Overview
Dependencies
Maintainers
5
Versions
164
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

qcloud-iotexplorer-bluetooth-adapter - npm Package Compare versions

Comparing version 0.10.1 to 0.10.3

10

lib/base/BlueToothAdapter.d.ts

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

addAdapter(deviceAdapter: any, forceAdd?: boolean): void;
_filterDevices({ devices, serviceIds, deviceName, productId, ignoreDeviceIds, ignoreServiceIds, extendInfo, DeviceAdapter, }: {
_filterDevices({ deviceId: SpecificDeviceId, devices, serviceIds, deviceName, productId, ignoreDeviceIds, ignoreServiceIds, extendInfo, DeviceAdapter, }: {
deviceId?: string;
devices: WechatMiniprogram.BlueToothDevice[];

@@ -97,4 +98,5 @@ serviceIds?: string[];

*/
searchDevice({ serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, ignoreWarning, ignoreCache, disableCache, DeviceAdapter, // 指定adapter,会自动忽略已经注入的adapter
startBluetoothDevicesDiscoveryParams, }: SearchDeviceParams): Promise<BlueToothDeviceInfo>;
searchDevice({ deviceId, serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, ignoreWarning, ignoreCache, disableCache, DeviceAdapter, // 指定adapter,会自动忽略已经注入的adapter
startBluetoothDevicesDiscoveryParams, useCacheFoundDevices, }: SearchDeviceParams): Promise<BlueToothDeviceInfo>;
stopSearchDevice(): void;
getDeviceAdapter(params: string | {

@@ -107,3 +109,3 @@ deviceId?: string;

connectAdvertisingDevice({ deviceId, deviceName, productId, ...deviceParams }: ConnectDeviceParams, options?: ConnectDeviceOptions): Promise<DeviceAdapter>;
searchAndConnectDevice({ serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, }: SearchDeviceParams, { autoNotify, disableCache, DeviceAdapter, }?: {
searchAndConnectDevice({ deviceId, serviceId, serviceIds, deviceName, productId, ignoreDeviceIds, timeout, extendInfo, }: SearchDeviceParams, { autoNotify, disableCache, DeviceAdapter, }?: {
disableCache?: boolean;

@@ -110,0 +112,0 @@ autoNotify?: boolean;

2

lib/base/BlueToothAdapter.js

@@ -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=e.call(this)||this;return u._devMode=!1,u._ignoreAnonymousDevices=!0,u._bluetoothApi={},u._actions={},u._deviceAdapterFactoryMap={},u._productIdMap={},u._inited=!1,u._available=!1,u._discovering=!1,u._onBluetoothDeviceFoundHandler=null,u._onDeviceFoundThrottle=DefaultOnDeviceFoundThrottle,u._setOnDeviceFoundThrottle=noop,u._onBluetoothScanAdvertisingHandler=null,u._initPromise=null,u._searchDevicePromise=null,u._deviceAdapterStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),u._deviceConnectStatusStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),u._initPeripheralServerPromise=null,u._devMode=s,u.addAdapter(r),isEmpty(u._deviceAdapterFactoryMap)&&console.warn("无合法的deviceAdapter"),u._ignoreAnonymousDevices=d,u._h5Websocket=c,u._bluetoothApi=n||nativeBluetoothApi_1.default,u._actions=o,u.deviceCacheManager=new BluetoothDeviceCacheManager_1.BluetoothDeviceCacheManager,u}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.devices,o=void 0===r?[]:r,n=e.serviceIds,c=e.deviceName,s=void 0===c?"":c,a=e.productId,d=e.ignoreDeviceIds,u=void 0===d?[]:d,l=e.ignoreServiceIds,v=void 0===l?[]:l,h=e.extendInfo,p=void 0===h?{}:h,_=e.DeviceAdapter;if(_)n=[_.serviceId],t=[_.deviceFilter],console.log("specific serviceId: ",n);else{n&&n.length||(n=this._getSupportServiceIds());var f={};(null==v?void 0:v.length)&&(v.forEach((function(e){return f[e]=!0})),n=n.filter((function(e){return!f[e]}))),t=n.map((function(e){return i._deviceAdapterFactoryMap[e].deviceFilter})),console.log("support serviceIds",n)}for(var g=[],D=function(e,i){if(u.find((function(t){return o[e].deviceId===t})))return"break";for(var r=void 0,c=0,d=t.length;c<d;c++)if(r=t[c](o[e],{serviceIds:n,deviceName:s,productId:a,ignoreDeviceIds:u,ignoreServiceIds:v,extendInfo:p}),s){if(r&&r.deviceName===s)return{value:[r]}}else if(r){g.push(r);break}},I=0,b=o.length;I<b;I++){var A=D(I);if("object"==typeof A)return A.value;if("break"===A)break}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=this;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:if(d.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 d.sent(),e=function(e){var i=e.available,r=e.discovering;return tslib_1.__awaiter(a,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 a.onBleConnectionStateChange(e)},o=function(e){return a.onBLECharacteristicValueChange(e)},n=throttle_1.throttle(this._onDeviceFoundThrottle,(function(e){return a.onBluetoothDeviceFound(e)})),this._setOnDeviceFoundThrottle=function(e){n.updateDelay(e)},this._bluetoothApi.onBluetoothAdapterStateChange(e),this._bluetoothApi.onBLEConnectionStateChange(r),this._bluetoothApi.onBLECharacteristicValueChange(o),this._bluetoothApi.onBluetoothDeviceFound(n),this.addCleanupTask("init",(function(){a._available=a._discovering=a._inited=!1,a._initPromise=null,a._bluetoothApi.offBluetoothAdapterStateChange(e),a._bluetoothApi.offBLEConnectionStateChange(r),a._bluetoothApi.offBLECharacteristicValueChange(o),a._bluetoothApi.offBluetoothDeviceFound(n),a._bluetoothApi.closeBluetoothAdapter()})),[4,this._bluetoothApi.openBluetoothAdapter({mode:"central"})];case 2:return d.sent(),c=e,[4,this._bluetoothApi.getBluetoothAdapterState()];case 3:return c.apply(void 0,[d.sent()]),[3,5];case 4:return s=d.sent(),this._available=!1,this._inited=!1,this._initPromise=null,i(this._normalizeError(s)),[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:try{t=(null==e?void 0:e.devices)||[],"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",e,i),"function"==typeof this._onBluetoothDeviceFoundHandler&&this._onBluetoothDeviceFoundHandler(i)}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(g){switch(g.label){case 0:return[4,this.init()];case 1:g.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)},g.label=2;case 2:return g.trys.push([2,4,,5]),[4,this.startBluetoothDevicesDiscovery(f)];case 3:return g.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=g.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.serviceId,i=e.serviceIds,r=e.deviceName,o=e.productId,n=e.ignoreDeviceIds,c=void 0===n?[]:n,s=e.timeout,a=void 0===s?5e3:s,d=e.extendInfo,u=void 0===d?{}:d,l=e.ignoreWarning,v=void 0!==l&&l,h=e.ignoreCache,p=e.disableCache,_=e.DeviceAdapter,f=e.startBluetoothDevicesDiscoveryParams;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,n=this;return tslib_1.__generator(this,(function(s){switch(s.label){case 0:return v||console.warn("[DEPRECATED] searchDevice + connectDevice 的方式连接设备已废弃,请直接使用 searchAndConnectDevice 方法,会自动处理连接缓存已经失效重搜等逻辑。"),void 0===p&&void 0!==h&&(p=h),[4,this.init()];case 1:return s.sent(),t&&!i&&(i=[t]),console.log("searching for explorerDeviceId => ",r),!p&&(e=this.deviceCacheManager.getDeviceCache(r))?(console.log("find ble deviceInfo from cache for "+r,tslib_1.__assign({deviceName:r,productId:o},e)),[2,Promise.resolve(tslib_1.__assign({deviceName:r,productId:o},e))]):[2,this._searchDevicePromise||(this._searchDevicePromise=new Promise((function(e,t){return tslib_1.__awaiter(n,void 0,void 0,(function(){var n,s,d,l=this;return tslib_1.__generator(this,(function(v){switch(v.label){case 0:n=function(e){l.stopBluetoothDevicesDiscovery(),t(l._normalizeError(e)),l._searchDevicePromise=null},s=function(t){l.stopBluetoothDevicesDiscovery(),e(t),l._searchDevicePromise=null},this._onBluetoothDeviceFoundHandler=function(e){try{var t=l._filterDevices({devices:e,serviceIds:i,deviceName:r,productId:o,ignoreDeviceIds:c,extendInfo:u,DeviceAdapter:_});console.log("matchedDevices: ",t),t.length>0&&(console.log("doFindDevice",t[0]),s(t[0]))}catch(e){n(e)}},v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this.startBluetoothDevicesDiscovery(f)];case 2:return v.sent(),console.log("startBluetoothDevicesDiscovery succ"),this.onBluetoothDeviceFound(),setTimeout((function(){s(null)}),a),[3,4];case 3:return d=v.sent(),n(d),[3,4];case 4:return[2]}}))}))})))]}}))}))},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})}))),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,g=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:g}))?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.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=void 0===t?{}:t,h=v.autoNotify,p=v.disableCache,_=void 0!==p&&p,f=v.DeviceAdapter;return tslib_1.__awaiter(this,void 0,void 0,(function(){var e,t,c;return tslib_1.__generator(this,(function(a){switch(a.label){case 0:return a.trys.push([0,7,,8]),e=void 0,!_&&n&&o&&(e=this._deviceAdapterStore.get({explorerDeviceId:n+"/"+o})),e?(console.log("find deviceAdapter in cache, explorerDeviceId: ",n+"/"+o,e),e.isConnected?[3,2]:[4,e.connectDevice({autoNotify:h})]):[3,3];case 1:a.sent(),a.label=2;case 2:return[2,e];case 3:return[4,this.searchDevice({serviceId:i,serviceIds:r,deviceName:o,productId:n,ignoreDeviceIds:s,timeout:d,extendInfo:l,ignoreWarning:!0,disableCache:_,DeviceAdapter:f})];case 4:return(t=a.sent())?(!t.productId&&n&&(t.productId=n),console.log("deviceInfo",t,n),[4,this.connectDevice(t,{autoNotify:h,disableCache:_,DeviceAdapter:f})]):[2,Promise.reject({code:"DeviceNotFound"})];case 5:return[2,e=a.sent()];case 6:return[3,8];case 7:return c=a.sent(),console.error("searchAndConnectDevice error",c),[2,Promise.reject(c)];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"),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=e.call(this)||this;return u._devMode=!1,u._ignoreAnonymousDevices=!0,u._bluetoothApi={},u._actions={},u._deviceAdapterFactoryMap={},u._productIdMap={},u._inited=!1,u._available=!1,u._discovering=!1,u._onBluetoothDeviceFoundHandler=null,u._onDeviceFoundThrottle=DefaultOnDeviceFoundThrottle,u._setOnDeviceFoundThrottle=noop,u._onBluetoothScanAdvertisingHandler=null,u._initPromise=null,u._searchDevicePromise=null,u._deviceAdapterStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),u._deviceConnectStatusStore=new SimpleStore_1.SimpleStore({filter:function(e){return function(t){return t.deviceId===e.deviceId||t.explorerDeviceId===e.explorerDeviceId}}}),u._initPeripheralServerPromise=null,u._devMode=s,u.addAdapter(r),isEmpty(u._deviceAdapterFactoryMap)&&console.warn("无合法的deviceAdapter"),u._ignoreAnonymousDevices=d,u._h5Websocket=c,u._bluetoothApi=n||nativeBluetoothApi_1.default,u._actions=o,u.deviceCacheManager=new BluetoothDeviceCacheManager_1.BluetoothDeviceCacheManager,u}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 y=I(b);if("object"==typeof y)return y.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=this;return tslib_1.__generator(this,(function(d){switch(d.label){case 0:if(d.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 d.sent(),e=function(e){var i=e.available,r=e.discovering;return tslib_1.__awaiter(a,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 a.onBleConnectionStateChange(e)},o=function(e){return a.onBLECharacteristicValueChange(e)},n=throttle_1.throttle(this._onDeviceFoundThrottle,(function(e){return a.onBluetoothDeviceFound(e)})),this._setOnDeviceFoundThrottle=function(e){n.updateDelay(e)},this._bluetoothApi.onBluetoothAdapterStateChange(e),this._bluetoothApi.onBLEConnectionStateChange(r),this._bluetoothApi.onBLECharacteristicValueChange(o),this._bluetoothApi.onBluetoothDeviceFound(n),this.addCleanupTask("init",(function(){a._available=a._discovering=a._inited=!1,a._initPromise=null,a._bluetoothApi.offBluetoothAdapterStateChange(e),a._bluetoothApi.offBLEConnectionStateChange(r),a._bluetoothApi.offBLECharacteristicValueChange(o),a._bluetoothApi.offBluetoothDeviceFound(n),a._bluetoothApi.closeBluetoothAdapter()})),[4,this._bluetoothApi.openBluetoothAdapter({mode:"central"})];case 2:return d.sent(),c=e,[4,this._bluetoothApi.getBluetoothAdapterState()];case 3:return c.apply(void 0,[d.sent()]),[3,5];case 4:return s=d.sent(),this._available=!1,this._inited=!1,this._initPromise=null,i(this._normalizeError(s)),[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})}))),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

@@ -8,2 +8,3 @@ import EventEmitter from 'event-emitter-for-miniprogram';

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}(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

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

export interface SearchDeviceParams extends SearchDeviceBaseParams {
deviceId?: string;
deviceName?: string;

@@ -93,2 +94,3 @@ productId?: string;

disableCache?: boolean;
useCacheFoundDevices?: boolean;
}

@@ -95,0 +97,0 @@ export interface StartAdvertisingParams {

@@ -93,2 +93,3 @@ import { DeviceAdapter } from '../base';

addCleanupTask(action: any, cleanupFn: any): void;
removeCleanupTask(action: any): void;
on: (type: string, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

@@ -190,2 +191,3 @@ once: (type: any, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

addCleanupTask(action: any, cleanupFn: any): void;
removeCleanupTask(action: any): void;
on: (type: string, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

@@ -192,0 +194,0 @@ once: (type: any, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

@@ -96,2 +96,3 @@ import { DeviceAdapter } from '../base';

addCleanupTask(action: any, cleanupFn: any): void;
removeCleanupTask(action: any): void;
on: (type: string, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

@@ -196,2 +197,3 @@ once: (type: any, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

addCleanupTask(action: any, cleanupFn: any): void;
removeCleanupTask(action: any): void;
on: (type: string, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

@@ -198,0 +200,0 @@ once: (type: any, listener: import("event-emitter-for-miniprogram").listenerCallback) => import("event-emitter-for-miniprogram").default;

{
"name": "qcloud-iotexplorer-bluetooth-adapter",
"version": "0.10.1",
"version": "0.10.3",
"description": "",

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

},
"gitHead": "d38861b70471a853178bc29822126af7a29b94a6"
"gitHead": "31152660f228f85f15b76023f89e99b19d6f8151"
}

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc