UNPKG

@iotize/device-com-ble.cordova

Version:

Bluetooth Low Energy (BLE) for IoTize modules Plugin

2 lines 20.8 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@iotize/tap/protocol/api"),require("@iotize/tap/protocol/core"),require("rxjs"),require("rxjs/operators"),require("@iotize/common/error"),require("@iotize/common/debug"),require("@iotize/tap/protocol/ble/common"),require("@iotize/common/byte-converter"),require("@iotize/common/utility")):"function"==typeof define&&define.amd?define("@iotize/device-com-ble.cordova",["exports","@iotize/tap/protocol/api","@iotize/tap/protocol/core","rxjs","rxjs/operators","@iotize/common/error","@iotize/common/debug","@iotize/tap/protocol/ble/common","@iotize/common/byte-converter","@iotize/common/utility"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).iotize=e.iotize||{},e.iotize["device-com-ble"]=e.iotize["device-com-ble"]||{},e.iotize["device-com-ble"].cordova={}),e.api,e.core,e.rxjs,e.rxjs.operators,e.error,e.debug$1,e.common,e.byteConverter,e.utility)}(this,(function(e,t,n,r,i,o,c,u,s,a){"use strict";var l=function(e,t){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},l(e,t)};function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function d(e,t){var n,r,i,o,c={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(u){return function(s){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(c=0)),c;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return c.label++,{value:u[1],done:!1};case 5:c.label++,r=u[1],u=[0];continue;case 7:u=c.ops.pop(),c.trys.pop();continue;default:if(!(i=c.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){c=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){c.label=u[1];break}if(6===u[0]&&c.label<i[1]){c.label=i[1],i=u;break}if(i&&c.label<i[2]){c.label=i[2],c.ops.push(u);break}i[2]&&c.ops.pop(),c.trys.pop();continue}u=t.call(e,c)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,s])}}}Object.create;function h(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}Object.create;"function"==typeof SuppressedError&&SuppressedError;var p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return f(t,e),t.invalidErrorResult=function(e){return new t("Internal error: ble cordova plugin returned an unexpected error object",t.Code.InternalError)},t.invalidErrorCode=function(e){return new t("Internal error: ble cordova plugin returned an invalid error code "+e.code+" with message "+e.message,t.Code.InternalError)},t.invalidNativeCallResult=function(e,n){return new t("Internal error: native call returned an invalid data type. "+n.message,t.Code.InternalError)},t.isValidErrorCode=function(e){return e in t.Code},t.iotizeBLEMissing=function(){return new t("iotizeBLE global variable does not exist. Are you sure app is running inside a Cordova application ?",t.Code.InternalError)},t}(o.CodeError);!function(e){!function(e){e.InternalError="CordovaBLEErrorInternalError",e.IllegalArgument="CordovaBLEErrorIllegalArgument",e.BLENotAvailable="CordovaBLEErrorBLENotAvailable",e.InvalidMacAddress="InvalidMacAddressInvalidMacAddress",e.ConnectionError="CordovaBLEErrorConnectionError",e.RequestError="CordovaBLEErrorRequestError",e.LocationServiceDisabled="CordovaBLEErrorLocationServiceDisabled",e.DisconnectError="CordovaBLEErrorDisconnectError",e.IllegalAction="CordovaBLEErrorIllegalAction",e.NotConnectedError="CordovaBLEErrorNotConnectedError",e.StatusCodeError="CordovaBLEErrorStatusCodeError"}(e.Code||(e.Code={}))}(p||(p={}));var v=c.createDebugger("@iotize/device-com-ble.cordova");function b(){if("object"!=typeof iotizeBLE)throw p.iotizeBLEMissing();return iotizeBLE}var g=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function c(e){try{s(r.next(e))}catch(e){o(e)}}function u(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,u)}s((r=r.apply(e,t||[])).next())}))},y=function(e){function n(t,n,r){var i=e.call(this)||this;return i.deviceId=t,i.cordovaInterfaceOverwrite=r,n?i.options=n:i.options.connect.timeout=6e4,i}return f(n,e),Object.defineProperty(n.prototype,"pluginInterface",{get:function(){return this.cordovaInterfaceOverwrite||b()},enumerable:!1,configurable:!0}),n.prototype._connect=function(e){var n=this;return v("_connect",e),this.pluginInterface.connectAndDiscoverTapServices(this.deviceId).pipe(i.tap((function(e){n.setConnectionState(e)})),i.filter((function(e){return e===t.ConnectionState.CONNECTED})),i.first())},n.prototype._disconnect=function(e){var t=this;return v("_disconnect",e),r.defer((function(){return t.pluginInterface.disConnect(t.deviceId)}))},n.prototype.write=function(e){return g(this,void 0,void 0,(function(){return d(this,(function(e){throw new Error("Method not implemented.")}))}))},n.prototype.read=function(){return g(this,void 0,void 0,(function(){return d(this,(function(e){throw new Error("Method not implemented.")}))}))},n.prototype.send=function(e,n){var o=this;return r.defer((function(){return o.pluginInterface.send(o.deviceId,e)})).pipe(i.catchError((function(e){var n;return(null===(n=e)||void 0===n?void 0:n.code)===p.Code.NotConnectedError&&o.setConnectionState(t.ConnectionState.DISCONNECTED),r.throwError(e)})))},n}(n.QueueComProtocol),m=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function c(e){try{s(r.next(e))}catch(e){o(e)}}function u(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,u)}s((r=r.apply(e,t||[])).next())}))},S=function(){function e(e,n){void 0===n&&(n=b()),this.deviceId=e,this.cordovaPlugin=n,this._stateChange=new r.BehaviorSubject(t.ConnectionState.DISCONNECTED)}return Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateChange.asObservable().pipe(i.distinctUntilChanged())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this.id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this.deviceId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return t.ConnectionState[this._stateChange.value]},enumerable:!1,configurable:!0}),e.prototype.discoverServices=function(e){return m(this,void 0,void 0,(function(){var t,n,r,i,o,c,u,s,a,l,f,p,v,b;return d(this,(function(d){switch(d.label){case 0:return t=this,[4,this.cordovaPlugin.discoverServices(this.deviceId)];case 1:if(t.serviceListCache=d.sent(),n={},e){r=function(e){var t=i.serviceListCache.find((function(t){return t.uuid===e}));t&&(n[e]=new C(t,i))},i=this;try{for(o=h(e),c=o.next();!c.done;c=o.next())u=c.value,r(u)}catch(e){f={error:e}}finally{try{c&&!c.done&&(p=o.return)&&p.call(o)}finally{if(f)throw f.error}}}else try{for(s=h(this.serviceListCache),a=s.next();!a.done;a=s.next())l=a.value,n[l.uuid]=new C(l,this)}catch(e){v={error:e}}finally{try{a&&!a.done&&(b=s.return)&&b.call(s)}finally{if(v)throw v.error}}return[2,n]}}))}))},e.prototype.connect=function(){var e;return m(this,void 0,void 0,(function(){var n,r=this;return d(this,(function(o){switch(o.label){case 0:return null===(e=this.connectionStateSubscription)||void 0===e||e.unsubscribe(),n=this.cordovaPlugin.connect(this.deviceId).pipe(i.shareReplay()),this.connectionStateSubscription=n.subscribe((function(e){r._stateChange.next(e)})),[4,n.pipe(i.filter((function(e){return e===t.ConnectionState.CONNECTED})),i.first()).toPromise()];case 1:return o.sent(),[2]}}))}))},e.prototype.disconnect=function(){var e;return m(this,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,this.cordovaPlugin.disConnect(this.deviceId)];case 1:return n.sent(),this._stateChange.next(t.ConnectionState.DISCONNECTED),null===(e=this.connectionStateSubscription)||void 0===e||e.unsubscribe(),[2]}}))}))},e.prototype.close=function(){var e;return m(this,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,this.cordovaPlugin.close(this.deviceId)];case 1:return n.sent(),this._stateChange.next(t.ConnectionState.DISCONNECTED),null===(e=this.connectionStateSubscription)||void 0===e||e.unsubscribe(),[2]}}))}))},e.prototype.getService=function(e){return m(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return this.serviceListCache?[3,2]:[4,this.discoverServices([e])];case 1:n.sent(),n.label=2;case 2:if(!(t=this.serviceListCache.find((function(t){return t.uuid===e}))))throw u.BleComError.serviceNotFound(e);return[2,new C(t,this)]}}))}))},e}(),C=function(){function e(e,t){this.config=e,this.peripheral=t}return Object.defineProperty(e.prototype,"uuid",{get:function(){return this.config.uuid},enumerable:!1,configurable:!0}),e.prototype.getCharacteristic=function(e){var t;return m(this,void 0,void 0,(function(){var n;return d(this,(function(r){if(!(n=null===(t=this.config.characteristics)||void 0===t?void 0:t.find((function(t){return t.uuid===e}))))throw u.BleComError.charcacteristicNotFound(e);return[2,new E(this,n)]}))}))},e.prototype.getCharacteristics=function(){return m(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return this.config.characteristics?[2,this.config.characteristics.map((function(t){return new E(e,t)}))]:[2,[]]}))}))},e}(),E=function(){function e(e,t){this.service=e,this.config=t}return Object.defineProperty(e.prototype,"uuid",{get:function(){return this.config.uuid},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"properties",{get:function(){return this.config.properties},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){return this.setupDataStreamIfRequired().pipe(i.map((function(e){return{data:e,isNotification:!0}})))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"deviceId",{get:function(){return this.service.peripheral.deviceId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pluginInterface",{get:function(){return this.service.peripheral.cordovaPlugin},enumerable:!1,configurable:!0}),e.prototype.read=function(){return m(this,void 0,void 0,(function(){return d(this,(function(e){return[2,this.pluginInterface.characteristicReadValue(this.deviceId,this.service.uuid,this.uuid)]}))}))},e.prototype.getDescriptor=function(){return m(this,void 0,void 0,(function(){return d(this,(function(e){throw new Error("Not implemented yet")}))}))},e.prototype.getDescriptors=function(){return m(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return this.config.descriptors?[2,this.config.descriptors.map((function(t){return new w(t,e)}))]:[2,[]]}))}))},e.prototype.write=function(e,t){return m(this,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return t?[4,this.pluginInterface.characteristicWriteWithoutResponse(this.deviceId,this.service.uuid,this.uuid,e)]:[3,2];case 1:return n.sent(),[3,4];case 2:return[4,this.pluginInterface.characteristicWrite(this.deviceId,this.service.uuid,this.uuid,e)];case 3:n.sent(),n.label=4;case 4:return[2,e]}}))}))},e.prototype.enableNotifications=function(e){return m(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return e?(this.setupDataStreamIfRequired(),[4,this.pluginInterface.characteristicStartNotification(this.deviceId,this.service.uuid,this.uuid)]):[3,2];case 1:return t.sent(),[3,4];case 2:return[4,this.pluginInterface.characteristicStopNotification(this.deviceId,this.service.uuid,this.uuid)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))},e.prototype.setupDataStreamIfRequired=function(){return this._dataStream||(this._dataStream=this.pluginInterface.characteristicChanged(this.deviceId,this.service.uuid,this.uuid)),this._dataStream},e}(),w=function(){function e(e,t){this.config=e,this.characteristic=t}return Object.defineProperty(e.prototype,"uuid",{get:function(){return this.config.uuid},enumerable:!1,configurable:!0}),e.prototype.readValue=function(){return m(this,void 0,void 0,(function(){return d(this,(function(e){throw new Error("Reading descriptor value is not implemented yet")}))}))},e.prototype.writeValue=function(e){return m(this,void 0,void 0,(function(){return d(this,(function(e){throw new Error("Writing descriptor value is not implemented yet")}))}))},e}(),x=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function c(e){try{s(r.next(e))}catch(e){o(e)}}function u(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,u)}s((r=r.apply(e,t||[])).next())}))},I=function(){function e(e,t){this.cordovaInterfaceOverwrite=e,this.requestDeviceOptions=t,this._results=new r.BehaviorSubject([]),this._scanning$=new r.BehaviorSubject(!1)}return Object.defineProperty(e.prototype,"cordovaInterface",{get:function(){return this.cordovaInterfaceOverwrite||b()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scanning",{get:function(){return this._scanning$.asObservable()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isScanning",{get:function(){return this._scanning$.value},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"results",{get:function(){return this._results.asObservable()},enumerable:!1,configurable:!0}),e.prototype.start=function(e){var t;return x(this,void 0,void 0,(function(){var e=this;return d(this,(function(n){switch(n.label){case 0:return null===(t=this.scanSubscription)||void 0===t||t.unsubscribe(),this.scanSubscription=void 0,this.clearResults(),[4,this.checkAvailable()];case 1:if(!n.sent())throw u.BleComError.bleNotAvailable("BLE is not available. Make sure that BLE is enabled on your device");return v("Start Scanning ..."),this._scanning$.next(!0),[2,new Promise((function(t,n){e.scanSubscription=e.cordovaInterface.startScan(e.requestDeviceOptions).subscribe((function(n){"Ok"!=n?e.addOrRefreshDevice(n):t()}),(function(t){v("Start scan failed with error: ",t),e.cordovaInterface.getLastError().then((function(e){v("Last BLE error "+e)})).catch((function(e){v("Cannot get last BLE error: ",e)})),n(t),e._scanning$.next(!1)}))}))]}}))}))},e.prototype.stop=function(){var e;return x(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:v("Stop Scanning ..."),n.label=1;case 1:return n.trys.push([1,3,,4]),null===(e=this.scanSubscription)||void 0===e||e.unsubscribe(),this.scanSubscription=void 0,[4,this.cordovaInterface.stopScan()];case 2:return n.sent(),this._scanning$.next(!1),[2];case 3:throw t=n.sent(),this._scanning$.next(!1),t;case 4:return[2]}}))}))},e.prototype.checkAvailable=function(){return this.cordovaInterface.checkAvailable()},Object.defineProperty(e.prototype,"devices",{get:function(){return this._results.value},enumerable:!1,configurable:!0}),e.prototype.clearResults=function(){this._results.next([])},e.prototype.addOrRefreshDevice=function(e){var t=this.devices.findIndex((function(t){return t.address==e.address}));if(t>=0){var n=this.devices[t];n.name==e.name&&n.rssi==e.rssi||(v("Updating device at index "+t+", name="+n.name+" with rssi="+n.rssi),this.devices[t]=e,this._results.next(this.devices))}else v("Adding new device name="+e.name+" with rssi="+e.rssi),this.devices.push(e),this._results.next(this.devices)},e}(),O=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function c(e){try{s(r.next(e))}catch(e){o(e)}}function u(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,u)}s((r=r.apply(e,t||[])).next())}))};function R(e){try{return s.hexStringToBuffer(e)}catch(t){throw p.invalidNativeCallResult(e,t)}}var _=function(){function e(){}return e.prototype.checkAvailable=function(){return this.execSingleResult("checkAvailable",[])},e.prototype.requestEnableBle=function(){return this.execSingleResult("enable",[])},e.prototype.startScan=function(e){return this.execMultipleResult("startScan",[JSON.stringify(e)])},e.prototype.stopScan=function(){return this.execSingleResult("stopScan",[])},e.prototype.connect=function(e,n){var r=this;return void 0===n&&(n=!0),this.askBleEnable(n).pipe(i.switchMap((function(){return r.execMultipleResult("connect",[e]).pipe(i.map((function(e){return e in t.ConnectionState||console.warn('Plugin native code returned an invalid connection state: "'+e+'".'),a.safeEnumValue(t.ConnectionState,e)})))})))},e.prototype.askBleEnable=function(e){var t=this;return r.defer((function(){return O(t,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return e?[4,this.checkAvailable()]:[3,3];case 1:return t.sent()?[3,3]:[4,this.requestEnableBle()];case 2:t.sent(),t.label=3;case 3:return[2]}}))}))}))},e.prototype.requestMTU=function(e,t){return this.execSingleResult("requestMTU",[e,t])},e.prototype.connectAndDiscoverTapServices=function(e,n){var r=this;return void 0===n&&(n=!0),this.askBleEnable(n).pipe(i.switchMap((function(){return r.execMultipleResult("connectAndDiscoverTapServices",[e]).pipe(i.map((function(e){return e in t.ConnectionState||console.warn('Plugin native code returned an invalid connection state: "'+e+'".'),a.safeEnumValue(t.ConnectionState,e)})))})))},e.prototype.disConnect=function(e){return this.execSingleResult("disConnect",[e])},e.prototype.close=function(e){return this.execSingleResult("close",[e])},e.prototype.isConnected=function(e){return this.execSingleResult("isConnected",[e])},e.prototype.send=function(e,t){return O(this,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,this.execSingleResult("sendRequest",[e,s.bufferToHexString(t)])];case 1:return[2,R(n.sent())]}}))}))},e.prototype.getLastError=function(){return this.execSingleResult("getLastError",[])},e.prototype.characteristicStartNotification=function(e,t,n){return this.execSingleResult("characteristicStartNotification",[e,t,n])},e.prototype.characteristicChanged=function(e,t,n){return this.execMultipleResult("characteristicChanged",[e,t,n]).pipe(i.map((function(e){return R(e)})))},e.prototype.characteristicStopNotification=function(e,t,n){return this.execSingleResult("characteristicStopNotification",[e,t,n])},e.prototype.characteristicReadValue=function(e,t,n){return O(this,void 0,void 0,(function(){return d(this,(function(r){switch(r.label){case 0:return[4,this.execSingleResult("characteristicRead",[e,t,n])];case 1:return[2,R(r.sent())]}}))}))},e.prototype.characteristicWrite=function(e,t,n,r){return this.execSingleResult("characteristicWrite",[e,t,n,s.bufferToHexString(r)])},e.prototype.characteristicWriteWithoutResponse=function(e,t,n,r){return this.execSingleResult("characteristicWriteWithoutResponse",[e,t,n,s.bufferToHexString(r)])},e.prototype.discoverServices=function(e){return O(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return[4,this.execSingleResult("discoverServices",[e])];case 1:return[2,t.sent()]}}))}))},e.prototype.execSingleResult=function(e,t){return new Promise((function(n,r){cordova.exec(n,(function(e){r(B(e))}),"BLECom",e,t)}))},e.prototype.execMultipleResult=function(e,t){var n=new r.Subject;return cordova.exec((function(e){n.next(e)}),(function(e){n.error(B(e))}),"BLECom",e,t),n.asObservable()},e}();function B(e){return"object"==typeof e&&e.code&&e.message?p.isValidErrorCode(e.code)?new p(e.message,p.Code[e.code]):p.invalidErrorCode(e):p.invalidErrorResult(e)}e.BLEComProtocol=y,e.BLEScanner=I,e.CordovaCharacteristicAdapter=E,e.CordovaPeripheralAdapter=S,e.CordovaServiceAdapter=C,e.getIoTizeBleCordovaPlugin=b,e.getScanRecordsFromBytes=function(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];if(0==r)break;var i=e[n+1];t.push({type:i,data:e.slice(n+2,n+r+1)}),n+=r}return t},e["ɵc"]=_,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=iotize-device-com-ble.cordova.umd.min.js.map