UNPKG

@iotize/tap

Version:

IoTize Device client for Javascript

16 lines (14 loc) 18.7 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@iotize/common/byte-converter"),require("@iotize/common/promise"),require("@iotize/tap/protocol/core"),require("@iotize/tap/client/impl"),require("@iotize/common/debug"),require("@iotize/common/error"),require("@iotize/tap/protocol/api"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define("@iotize/tap/protocol/ble/common",["exports","@iotize/common/byte-converter","@iotize/common/promise","@iotize/tap/protocol/core","@iotize/tap/client/impl","@iotize/common/debug","@iotize/common/error","@iotize/tap/protocol/api","rxjs","rxjs/operators"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).iotize=e.iotize||{},e.iotize.tap=e.iotize.tap||{},e.iotize.tap.protocol=e.iotize.tap.protocol||{},e.iotize.tap.protocol.ble=e.iotize.tap.protocol.ble||{},e.iotize.tap.protocol.ble.common={}),e.byteConverter,e.promise,e.iotize.tap.protocol.core,e.iotize.tap.client.impl,e.debug$1,e.error,e.iotize.tap.protocol.api,e.rxjs,e.rxjs.operators)}(this,(function(e,t,r,i,n,o,a,s,c,u){"use strict";var h={maxPacketLengthWithoutOffset:19,services:{upgrade:{service:"9e5d1e47-5c13-43a0-8635-82ad38a1386f",charac:"347f7608-2e2d-47eb-913b-75d4edc4de3b"},lwm2m:{service:"6c7b16c2-2a5b-8c9f-cf42-d31425470e7b",charac:"cc5c5491-b3be-9287-cb42-f7a6a29a50d5"},fastLwm2m:{service:"7c7b16c2-2a5b-8c9f-cf42-d31425470e7b",charac:"dc5c5491-b3be-9287-cb42-f7a6a29a50d5"},standardClientConfig:{service:"00002902-0000-1000-8000-00805f9b34fb"}}},l=function(e,t){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},l(e,t)}; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function f(e,t){var r,i,n,o,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}Object.create;function d(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}Object.create;var m=function(){function e(e){this.bufferOffset=0,this.dataLength=0,this.data=new Uint8Array(e),this.reset()}return e.prototype.append=function(e){if(e&&!(e.length<2)){if(this.bufferOffset=(255&e[0])-1,this.bufferOffset+e.length>this.data.length)throw new Error("Buffer size exceeded. Maximum size is "+this.data.length+" byte(s).");for(var t=1;t<e.length;t++)this.data[this.bufferOffset+t]=e[t];this.dataLength+=e.length-1}},e.prototype.reset=function(){this.dataLength=0,this.bufferOffset=0},e.prototype.hasAllChunks=function(){return-1===this.bufferOffset},e.prototype.isChecksumValid=function(){var e=this.getComputedChecksum();return this.getExpectedChecksum()===e},e.prototype.getComputedChecksum=function(){return 255&n.Checksum.compute(this.data.subarray(0,this.dataLength-1))},e.prototype.getExpectedChecksum=function(){return this.data[this.dataLength-1]},e.prototype.getData=function(){return this.data.slice(0,this.dataLength-1)},e.prototype.getBuffer=function(){return this.data},e}(),v=function(){function e(e,t){if(this.lastPacketSize=0,this.maxPacketSize=0,this.currentPacketIndex=0,t<1)throw new Error("Packet size must be greater than 0");this.data=e,this.maxPacketSize=t,this.currentPacketIndex=this.getTotalNumberOfPacket()-1,this.lastPacketSize=this.getLastPacketSize()}return e.wrapWithChecksum=function(t,r){var i=e.computeChecksum(t),n=new Uint8Array(t.length+1);return n.set(t),n.set([255&i],t.length),new e(n,r)},e.prototype.getTotalNumberOfPacket=function(){return(this.data.length/this.maxPacketSize|0)+(this.data.length%this.maxPacketSize==0?0:1)},e.prototype.getLastPacketSize=function(){var e=this.data.length%this.maxPacketSize;return 0===e&&(e=this.maxPacketSize),e},e.prototype.getPackets=function(){for(var e=[];this.hasNextPacket();)e.push(this.getNextPacket());return e},e.prototype.getNextPacket=function(){var e,t;this.currentPacketIndex>0?(t=this.lastPacketSize+(this.currentPacketIndex-1)*this.maxPacketSize,e=this.maxPacketSize):(t=0,e=this.lastPacketSize);var r=new Uint8Array(e+1);r[0]=0|t;for(var i=0;i<e;i++)r[i+1]=this.data[t+i];return this.currentPacketIndex--,r},e.prototype.hasNextPacket=function(){return this.currentPacketIndex>=0},e.computeChecksum=function(e){return 255&n.Checksum.compute(e)},e.prototype.getTotalSize=function(){return this.data.length},e}(),b=o.createDebugger("@iotize/tap/protocol/ble");e.BleComError=function(e){function t(t,r){return e.call(this,r,t)||this}return p(t,e),t.invalidBleChunkChecksum=function(e){return y.create(e)},t.writeSizeAboveMTU=function(e,r){return new t(t.Code.BleWriteSizeAboveMTU,"Cannot write "+e.length+" bytes as it's more than the Maximal Transfert Unit ("+r+")")},t.serviceNotFound=function(e){return new t(t.Code.BleGattServiceNotFound,"Bluetooth service with id "+e+" not found")},t.charcacteristicNotFound=function(e){return new t(t.Code.BleGattCharacteristicNotFound,"Bluetooth characteristic with id "+e+" not found")},t.bleNotAvailable=function(e){return void 0===e&&(e="BLE is not available on your device"),new t(t.Code.NotAvailable,e)},t.gattServerNotAvailable=function(){return new t(t.Code.GATTServerNotAvailable,"Generic Attribute Profile (GATT) server is not available")},t.gattServerConnectionFailed=function(){return new t(t.Code.GATTServerConnectionFailed,"Gatt server connection failed")},t}(a.CodeError);var w,g,y=function(t){function r(r){var i=t.call(this,e.BleComError.Code.InvalidChecksum,"Invalid checksum")||this;return i.packetBuilder=r,i}return p(r,t),r.create=function(e){return new r(e)},r}(e.BleComError);g=e.BleComError||(e.BleComError={}),(w=g.Code||(g.Code={})).InvalidChecksum="InvalidChecksum",w.BleGattServiceNotFound="BleGattServiceNotFound",w.BleGattCharacteristicNotFound="BleGattCharacteristicNotFound",w.BleWriteSizeAboveMTU="BleWriteSizeAboveMTU",w.GATTServerNotAvailable="BleComErrorGATTServerNotAvailable",w.GATTServerConnectionFailed="BleComErrorGATTServerConnectionFailed",w.NotAvailable="BleComErrorNotAvailable";var C=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(n,o){function a(e){try{c(i.next(e))}catch(e){o(e)}}function s(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((i=i.apply(e,t||[])).next())}))},k=function(e){function i(t){void 0===t&&(t={mtu:h.maxPacketLengthWithoutOffset+1});var r=e.call(this)||this;return r.bleOptions=t,r}return p(i,e),i.prototype.onNewLwm2mMessage=function(e){this._readResolve?(b("onNewLwm2mMessage()",t.bufferToHexString(e)),this._readResolve(e)):(console.warn("No listener for new message... 0x"+t.bufferToHexString(e)),this._pendingRead=e)},i.prototype.onNewLwm2mMessageError=function(e){console.error("Error lwm2m response...",e)},i.prototype.onLwm2mDataChunkError=function(e){this._readReject?this._readReject(e):console.warn("No listener for read message error...",e)},i.prototype.getLwm2mResponsePromise=function(){if(b("getLwm2mResponsePromise"),this._pendingRead){var e=this._pendingRead;return this._pendingRead=void 0,Promise.resolve(e)}return this._readPromise||this.createLwm2mResponsePromise(),this._readPromise},i.prototype.createLwm2mResponsePromise=function(){var e=this;return b("createLwm2mResponsePromise"),this._readPromise=new Promise((function(t,r){e._readResolve=t,e._readReject=r})),this._readPromise},i.prototype.read=function(){var e=this;if(b("read()..."),this.packetBuilder){if(this.packetBuilder.hasAllChunks()){var t=this.packetBuilder.getData();return this.packetBuilder=void 0,Promise.resolve(t)}console.warn("AbstractBleProtocol::read() There is already a read operation in progress but a new call to ::read has been made.")}return this.getLwm2mResponsePromise().then((function(t){return e.packetBuilder=void 0,t})).catch((function(t){throw e.packetBuilder=void 0,t}))},i.prototype.write=function(e){return C(this,void 0,void 0,(function(){var t,n,o=this;return f(this,(function(a){return null!=this.packetSplitter&&console.warn("BLEProtocol","write","There are already data being sent but a new call to ::write has been made"),this.packetSplitter=v.wrapWithChecksum(e,this.bleOptions.mtu-1),t=this.packetSplitter.getPackets(),this._pendingRead=void 0,this.packetBuilder=new m(i.RECEIVED_BUFFER_LENGTH),t.length>0?n=r.promiseSerial(t,(function(e,r){return o.writeLwm2mPacketChunk(e).then((function(e){return b("Done sending packet "+(r+1)+"/"+t.length),e}))})):(console.warn("BLEProtocol","write","Nothing to write..."),n=Promise.resolve()),[2,n.then((function(){o.packetSplitter=void 0})).catch((function(e){throw o.packetSplitter=void 0,e}))]}))}))},i.prototype.onNewLwm2mPacket=function(e){if(this.packetBuilder){if(this.packetBuilder.append(e),this.packetBuilder.hasAllChunks())if(this.packetBuilder.isChecksumValid())this.onNewLwm2mMessage(this.packetBuilder.getData());else{var r=y.create(this.packetBuilder);this.onLwm2mDataChunkError(r)}}else b("Ignoring lwm2m packet 0x"+t.bufferToHexString(e)+" as not request has been made yet")},i}(i.QueueComProtocol);k.RECEIVED_BUFFER_LENGTH=255;var P=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(n,o){function a(e){try{c(i.next(e))}catch(e){o(e)}}function s(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((i=i.apply(e,t||[])).next())}))},S={mtu:h.maxPacketLengthWithoutOffset+1,maximumBufferLength:255,waitForWriteAcknowledge:!0,preferedComServiceType:"large-frame",sanitizeUUID:!1},z=function(t){function r(e,r){void 0===r&&(r={});var i=t.call(this)||this;return i.peripheral=e,i._useSplitter=!0,i._unexpectedBleDisconnection=i.peripheral.stateChange.pipe(u.filter((function(e){var t=i.getConnectionState();return e===s.ConnectionState.DISCONNECTED&&t!==s.ConnectionState.DISCONNECTING&&t!==s.ConnectionState.DISCONNECTED})),u.share()),i.bleOptions=Object.assign(Object.assign({},S),r),i.options.connect.timeout=8e3,i.options.send.timeout=4e3,i.options.disconnect.timeout=8e3,i._unexpectedBleDisconnection.subscribe((function(){return P(i,void 0,void 0,(function(){return f(this,(function(e){switch(e.label){case 0:return b("unexpected BLE disconnection detected. Running proper BLE disconnection process"),[4,this.disconnect().toPromise().catch((function(e){b("Proper BLE disconnection process failed with error: "+e.message)}))];case 1:return e.sent(),[2]}}))}))})),i}return p(r,t),Object.defineProperty(r.prototype,"lwm2mCharc",{get:function(){if(!this._lwm2mCharc)throw this.setConnectionState(s.ConnectionState.DISCONNECTED),s.ComProtocol.Errors.notConnected({protocol:this});return this._lwm2mCharc},enumerable:!1,configurable:!0}),r.prototype.sanitizeUUID=function(e){return this.bleOptions.sanitizeUUID?e.replace(/\-/g,""):e},r.prototype._connect=function(){var e=this;return c.defer((function(){return P(e,void 0,void 0,(function(){var e,t,r;return f(this,(function(i){switch(i.label){case 0:return i.trys.push([0,3,,8]),[4,this.peripheral.connect()];case 1:return i.sent(),e=this,[4,this.setupLwm2mCharacteristic()];case 2:return e._lwm2mCharc=i.sent(),[3,8];case 3:t=i.sent(),i.label=4;case 4:return i.trys.push([4,6,,7]),[4,this.peripheral.disconnect()];case 5:return i.sent(),[3,7];case 6:return r=i.sent(),b("Failed to propertly disconnect after connection failed",r.message),[3,7];case 7:throw t;case 8:return[2]}}))}))})).pipe(u.share())},r.prototype._disconnect=function(){var e=this;return c.defer((function(){return P(e,void 0,void 0,(function(){var e;return f(this,(function(t){switch(t.label){case 0:if(!this.peripheral)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.peripheral.disconnect()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Failed to properly disconnect from peripheral",e),[3,4];case 4:return this._lwm2mCharc=void 0,[2]}}))}))})).pipe(u.share())},r.prototype.setupLwm2mCharacteristic=function(){return P(this,void 0,void 0,(function(){var e,t,r;return f(this,(function(i){switch(i.label){case 0:return e=[this.sanitizeUUID(h.services.lwm2m.service)],"large-frame"===this.bleOptions.preferedComServiceType&&e.push(this.sanitizeUUID(h.services.fastLwm2m.service)),[4,this.peripheral.discoverServices(e)];case 1:return t=i.sent(),b("Found services ",Object.keys(t).join(", "),"asked for services: ",e.join(", ")),[4,this._selectLwm2mCharacteristic(t)];case 2:return[4,(r=i.sent()).enableNotifications(!0)];case 3:return i.sent(),[2,r]}}))}))},r.prototype._selectLwm2mCharacteristic=function(t){return P(this,void 0,void 0,(function(){var r,i;return f(this,(function(n){if(r=this.sanitizeUUID(h.services.fastLwm2m.service),i=this.sanitizeUUID(h.services.lwm2m.service),"legacy"===this.bleOptions.preferedComServiceType&&t[i])return b("Force usage of legacy lwm2m characteristic UUID: "+i),[2,this._getLegacyLwm2mCharacteristic(t[i])];if(t[r])return b("Found fast lwm2m characteristic UUID: "+r),[2,this._getLargeFrameLwm2mCharacteristic(t[r])];if(t[i])return b("Found legacy lwm2m characteristic UUID: "+i),[2,this._getLegacyLwm2mCharacteristic(t[i])];throw b("No LwM2M service found. Available services: "+Object.keys(t).join(", ")),e.BleComError.serviceNotFound(i)}))}))},r.prototype._getLargeFrameLwm2mCharacteristic=function(e){return P(this,void 0,void 0,(function(){return f(this,(function(t){switch(t.label){case 0:return this.bleOptions.mtu=255,this._useSplitter=!1,[4,e.getCharacteristic(this.sanitizeUUID(h.services.fastLwm2m.charac))];case 1:return[2,t.sent()]}}))}))},r.prototype._getLegacyLwm2mCharacteristic=function(e){return P(this,void 0,void 0,(function(){return f(this,(function(t){switch(t.label){case 0:return this.bleOptions.mtu=h.maxPacketLengthWithoutOffset+1,this._useSplitter=!0,[4,e.getCharacteristic(this.sanitizeUUID(h.services.lwm2m.charac))];case 1:return[2,t.sent()]}}))}))},r.prototype.read=function(){return P(this,void 0,void 0,(function(){return f(this,(function(e){return this._readPromise||(this._readPromise=this._createReadPromise()),[2,this._readPromise]}))}))},r.prototype.readUnit=function(){return P(this,void 0,void 0,(function(){var e,t;return f(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.lwm2mCharc.data.pipe(u.first(),u.map((function(e){return e.data}))).toPromise()];case 1:return(e=r.sent())?[2,e]:[2,new Uint8Array];case 2:return t=r.sent(),[2,Promise.reject(t)];case 3:return[2]}}))}))},r.prototype.write=function(e){return P(this,void 0,void 0,(function(){var t,r,i,n,o,a,s;return f(this,(function(c){switch(c.label){case 0:if(this._readPromise=this._createReadPromise(),!this.useSplitter)return[3,9];t=v.wrapWithChecksum(e,this.chunkSize).getPackets(),c.label=1;case 1:c.trys.push([1,6,7,8]),r=d(t),i=r.next(),c.label=2;case 2:return i.done?[3,5]:(n=i.value,[4,this.writeUnit(n)]);case 3:c.sent(),c.label=4;case 4:return i=r.next(),[3,2];case 5:return[3,8];case 6:return o=c.sent(),a={error:o},[3,8];case 7:try{i&&!i.done&&(s=r.return)&&s.call(r)}finally{if(a)throw a.error}return[7];case 8:return[3,10];case 9:return[2,this.writeUnit(e)];case 10:return[2]}}))}))},Object.defineProperty(r.prototype,"useSplitter",{get:function(){return this._useSplitter},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"chunkSize",{get:function(){return this.bleOptions.mtu-1},enumerable:!1,configurable:!0}),r.prototype.writeUnit=function(t){return P(this,void 0,void 0,(function(){return f(this,(function(r){try{if(t.length>this.bleOptions.mtu)throw e.BleComError.writeSizeAboveMTU(t,this.bleOptions.mtu);if(this.bleOptions.waitForWriteAcknowledge)return[2,this.lwm2mCharc.write(t,!0)];this.lwm2mCharc.write(t,!0).catch((function(e){console.warn("Write error ignored",e)}))}catch(e){return[2,Promise.reject(e)]}return[2]}))}))},r.prototype._createReadPromise=function(){return P(this,void 0,void 0,(function(){var t,r;return f(this,(function(i){switch(i.label){case 0:if(!this.useSplitter)return[3,4];t=new m(this.bleOptions.maximumBufferLength),i.label=1;case 1:return t.hasAllChunks()?[3,3]:[4,this.readUnit()];case 2:return r=i.sent(),t.append(r),[3,1];case 3:if(t.isChecksumValid())return[2,t.getData()];throw e.BleComError.invalidBleChunkChecksum(t);case 4:return[2,this.readUnit()];case 5:return[2]}}))}))},r}(i.QueueComProtocol);e.AbstractBleProtocol=k,e.BLEPacketBuilder=m,e.BLEPacketSplitter=v,e.BleConfig=h,e.DEFAULT_BLE_OPTIONS=S,e.InvalidBleFrameChecksum=y,e.UniversalBleProtocolAdapter=z,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=iotize-tap-protocol-ble-common.umd.min.js.map