@neurosity/sdk 6.4.0 → 6.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/neurosity.iife.js +2590 -105
- package/dist/browser/neurosity.js +129 -113
- package/dist/browser/neurosity.js.map +1 -1
- package/dist/cjs/api/bluetooth/BluetoothClient.d.ts +1 -1
- package/dist/cjs/api/bluetooth/BluetoothClient.js +21 -11
- package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.d.ts +3 -1
- package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.js +17 -17
- package/dist/cjs/api/bluetooth/types/index.d.ts +1 -0
- package/dist/cjs/api/bluetooth/utils/binaryBufferToEpoch.d.ts +51 -0
- package/dist/cjs/api/bluetooth/utils/binaryBufferToEpoch.js +116 -0
- package/dist/cjs/api/bluetooth/utils/decodeJSONChunks.d.ts +15 -0
- package/dist/cjs/api/bluetooth/utils/decodeJSONChunks.js +25 -0
- package/dist/cjs/api/bluetooth/utils/textCodec.d.ts +17 -0
- package/dist/cjs/api/bluetooth/utils/textCodec.js +40 -0
- package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.d.ts +3 -1
- package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.js +19 -34
- package/dist/electron/index.js +15 -13
- package/dist/electron/index.js.map +1 -1
- package/dist/esm/api/bluetooth/BluetoothClient.d.ts +1 -1
- package/dist/esm/api/bluetooth/BluetoothClient.js +21 -11
- package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.d.ts +3 -1
- package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.js +18 -18
- package/dist/esm/api/bluetooth/types/index.d.ts +1 -0
- package/dist/esm/api/bluetooth/utils/binaryBufferToEpoch.d.ts +51 -0
- package/dist/esm/api/bluetooth/utils/binaryBufferToEpoch.js +109 -0
- package/dist/esm/api/bluetooth/utils/decodeJSONChunks.d.ts +15 -0
- package/dist/esm/api/bluetooth/utils/decodeJSONChunks.js +21 -0
- package/dist/esm/api/bluetooth/utils/textCodec.d.ts +17 -0
- package/dist/esm/api/bluetooth/utils/textCodec.js +36 -0
- package/dist/esm/api/bluetooth/web/WebBluetoothTransport.d.ts +3 -1
- package/dist/esm/api/bluetooth/web/WebBluetoothTransport.js +20 -35
- package/dist/esm/neurosity.mjs +2590 -105
- package/dist/examples/neurosity.iife.js +2590 -105
- package/dist/examples/neurosity.js +129 -113
- package/dist/examples/neurosity.mjs +2590 -105
- package/package.json +2 -1
- package/dist/cjs/api/bluetooth/utils/encoding.d.ts +0 -3
- package/dist/cjs/api/bluetooth/utils/encoding.js +0 -22
- package/dist/esm/api/bluetooth/utils/encoding.d.ts +0 -3
- package/dist/esm/api/bluetooth/utils/encoding.js +0 -17
package/dist/electron/index.js
CHANGED
|
@@ -56,25 +56,27 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
|
|
|
56
56
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isWebBluetoothSupported=void 0;const e=require("./isMaybeWebWorkerContext");function o(){var o;return"undefined"!=typeof window&&(null===(o=null===window||void 0===window?void 0:window.navigator)||void 0===o?void 0:o.bluetooth)&&!(0,e.isMaybeWebWorkerContext)()}exports.isWebBluetoothSupported=o;
|
|
57
57
|
},{"./isMaybeWebWorkerContext":"VusC"}],"UDAB":[function(require,module,exports) {
|
|
58
58
|
"use strict";function e(){return Math.floor(1e5+9e5*Math.random())}Object.defineProperty(exports,"__esModule",{value:!0}),exports.create6DigitPin=void 0,exports.create6DigitPin=e;
|
|
59
|
-
},{}],"V73a":[function(require,module,exports) {
|
|
60
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.stitchChunks=void 0;const e=require("rxjs"),t=require("rxjs/operators");function r({delimiter:r}){return(0,e.pipe)((0,t.scan)(([e],t)=>{const s=e+t;if(!s.includes(r))return[s,""];if(s.endsWith(r))return["",s];const i=s.lastIndexOf(r)+r.length,n=s.slice(0,i);return[s.slice(i),n]},["",""]),(0,t.map)(([,e])=>e.slice(0,-r.length)),(0,t.filter)(e=>!!e.length))}exports.stitchChunks=r;
|
|
61
59
|
},{}],"iwtf":[function(require,module,exports) {
|
|
62
60
|
"use strict";var N,e;Object.defineProperty(exports,"__esModule",{value:!0}),exports.TRANSPORT_TYPE=exports.BLUETOOTH_CONNECTION=void 0,function(N){N.SCANNING="scanning",N.CONNECTED="connected",N.CONNECTING="connecting",N.DISCONNECTING="disconnecting",N.DISCONNECTED="disconnected"}(N=exports.BLUETOOTH_CONNECTION||(exports.BLUETOOTH_CONNECTION={})),function(N){N.WEB="web",N.REACT_NATIVE="reactNative"}(e=exports.TRANSPORT_TYPE||(exports.TRANSPORT_TYPE={}));
|
|
63
|
-
},{}],"
|
|
64
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.
|
|
61
|
+
},{}],"mUrw":[function(require,module,exports) {
|
|
62
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextCodec=void 0;const e=require("buffer/index.js"),r=require("../types");class t{constructor(e){this.transportType=e,e===r.TRANSPORT_TYPE.WEB&&(this.webEncoder=new TextEncoder,this.webDecoder=new TextDecoder("utf-8"))}encode(t){if(this.transportType===r.TRANSPORT_TYPE.WEB){return this.webEncoder.encode(t)}if(this.transportType===r.TRANSPORT_TYPE.REACT_NATIVE){return[...e.Buffer.from(t)]}return e.Buffer.from(t)}decode(t){if(this.transportType===r.TRANSPORT_TYPE.WEB){return this.webDecoder.decode(t)}return e.Buffer.from(t).toString("utf-8")}}exports.TextCodec=t;
|
|
65
63
|
},{"../types":"iwtf"}],"dGLb":[function(require,module,exports) {
|
|
66
64
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHARACTERISTIC_UUIDS_TO_NAMES=exports.DEFAULT_ACTION_RESPONSE_TIMEOUT=exports.REACT_NATIVE_MAX_BYTE_SIZE=exports.ANDROID_MAX_MTU=void 0;const e=require("@neurosity/ipk");exports.ANDROID_MAX_MTU=512,exports.REACT_NATIVE_MAX_BYTE_SIZE=512,exports.DEFAULT_ACTION_RESPONSE_TIMEOUT=6e4,exports.CHARACTERISTIC_UUIDS_TO_NAMES=Object.fromEntries(Object.entries(e.BLUETOOTH_CHARACTERISTICS).map(e=>e.reverse()));
|
|
67
|
-
},{}],"
|
|
68
|
-
"use strict";
|
|
69
|
-
},{
|
|
70
|
-
"use strict";var t=this&&this.__awaiter||function(t,i,e,n){return new(e||(e=Promise))(function(r,a){function s(t){try{c(n.next(t))}catch(i){a(i)}}function o(t){try{c(n.throw(t))}catch(i){a(i)}}function c(t){var i;t.done?r(t.value):(i=t.value,i instanceof e?i:new e(function(t){t(i)})).then(s,o)}c((n=n.apply(t,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactNativeTransport=void 0;const i=require("@neurosity/ipk"),e=require("@neurosity/ipk"),n=require("@neurosity/ipk"),r=require("rxjs"),a=require("rxjs"),s=require("rxjs/operators"),o=require("rxjs/operators"),c=require("rxjs/operators"),d=require("../utils/create6DigitPin"),h=require("../utils/stitch"),l=require("../utils/encoding"),u=require("../types"),v=require("../constants"),p=require("../constants"),g=require("../constants"),E=require("../constants"),f={autoConnect:!0};class N{constructor(t){if(this.type=u.TRANSPORT_TYPE.REACT_NATIVE,this.characteristicsByName={},this.connection$=new r.BehaviorSubject(u.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new r.BehaviorSubject([]),this.logs$=new r.ReplaySubject(10),this.connectionStream$=this.connection$.asObservable().pipe((0,s.filter)(t=>!!t),(0,o.distinctUntilChanged)(),(0,o.shareReplay)(1)),this._isAutoConnectEnabled$=new r.ReplaySubject(1),!t){const t="React Native transport: missing options.";throw this.addLog(t),new Error(t)}this.options=Object.assign(Object.assign({},f),t);const{BleManager:i,bleManagerEmitter:e,platform:n,autoConnect:a}=this.options;if(!i){const t="React Native option: BleManager not provided.";throw this.addLog(t),new Error(t)}if(!e){const t="React Native option: bleManagerEmitter not provided.";throw this.addLog(t),new Error(t)}if(!n){const t="React Native option: platform not provided.";throw this.addLog(t),new Error(t)}this.BleManager=i,this.bleManagerEmitter=e,this.platform=n,this._isAutoConnectEnabled$.next(a),this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this.bleEvents={stopScan$:this._fromEvent("BleManagerStopScan"),discoverPeripheral$:this._fromEvent("BleManagerDiscoverPeripheral"),connectPeripheral$:this._fromEvent("BleManagerConnectPeripheral"),disconnectPeripheral$:this._fromEvent("BleManagerDisconnectPeripheral"),didUpdateValueForCharacteristic$:this._fromEvent("BleManagerDidUpdateValueForCharacteristic"),didUpdateState$:this._fromEvent("BleManagerDidUpdateState")},this.onDisconnected$=this.bleEvents.disconnectPeripheral$.pipe((0,c.share)()),this.BleManager.start({showAlert:!1}).then(()=>{this.addLog("BleManger started")}).catch(t=>{var i;this.addLog(`BleManger failed to start. ${null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t}`)}),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(u.BLUETOOTH_CONNECTION.DISCONNECTED)})}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===u.BLUETOOTH_CONNECTION.CONNECTED}_autoConnect(i){const e=this.onDisconnected$.pipe((0,s.switchMap)(()=>i));return this._isAutoConnectEnabled$.pipe((0,s.switchMap)(t=>t?(0,a.merge)(i,e):r.NEVER),(0,s.switchMap)(t=>this.scan().pipe((0,s.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,a.of)(e):r.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1))),(0,s.switchMap)(i=>t(this,void 0,void 0,function*(){return yield this.connect(i)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}connection(){return this.connectionStream$}_fromEvent(t){return(0,a.fromEventPattern)(i=>{this.bleManagerEmitter.addListener(t,i)},()=>{this.bleManagerEmitter.removeAllListeners(t)}).pipe((0,c.share)())}scan(t){var e,d,h;const v=null!==(e=null==t?void 0:t.seconds)&&void 0!==e?e:10,p=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,g=null!==(h=null==t?void 0:t.skipConnectionUpdate)&&void 0!==h&&h,E=[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],f={},N=new r.Observable(t=>{var i;try{this.BleManager.scan(E,v,!0,f).then(()=>{this.addLog(`BleManger scanning ${p?"once":"indefintely"}`),t.next()})}catch(e){this.addLog(`BleManger scanning ${p?"once":"indefintely"} failed. ${null!==(i=null==e?void 0:e.message)&&void 0!==i?i:e}`),t.error(e)}return()=>{this.BleManager.stopScan()}});return(p?N:(0,a.timer)(0,1e4).pipe((0,s.switchMap)(()=>N))).pipe((0,s.tap)(()=>{g||this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,s.takeUntil)(this.onDisconnected$),(0,s.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,s.filter)(t=>{var i,e,r;const a=null!==(r=null!==(e=null===(i=null==t?void 0:t.advertising)||void 0===i?void 0:i.localName)&&void 0!==e?e:t.name)&&void 0!==r?r:"";return!!a&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>a.startsWith(t))}),(0,c.scan)((t,i)=>{var e,n,r,a,s,o,c,d;const h=null!==(r=null!==(n=null===(e=null==i?void 0:i.advertising)||void 0===e?void 0:e.localName)&&void 0!==n?n:i.name)&&void 0!==r?r:"",u=null===(d=null===(c=(0,l.decode)(this.type,null!==(o=null===(s=null===(a=null==i?void 0:i.advertising)||void 0===a?void 0:a.manufacturerData)||void 0===s?void 0:s.bytes)&&void 0!==o?o:[]))||void 0===c?void 0:c.slice)||void 0===d?void 0:d.call(c,2);return Object.assign(Object.assign({},t),{[i.id]:Object.assign(Object.assign({},i),{name:h,manufactureDataString:u})})},{}),(0,o.distinctUntilChanged)((t,i)=>JSON.stringify(t)===JSON.stringify(i)),(0,s.map)(t=>Object.values(t)),(0,c.share)())}connect(e){return t(this,void 0,void 0,function*(){return new Promise((n,r)=>t(this,void 0,void 0,function*(){try{if(!e)return void this.addLog("Peripheral not found");this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTING),yield this.BleManager.connect(e.id),this.addLog("Getting service...");const a=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!a)return this.addLog("Could not retreive services"),void r(new Error("Could not retreive services"));this.addLog(`Got service ${i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`),this.device=e,this.characteristicsByName=Object.fromEntries(a.characteristics.map(t=>[p.CHARACTERISTIC_UUIDS_TO_NAMES[t.characteristic.toLowerCase()],{characteristicUUID:t.characteristic,serviceUUID:t.service,peripheralId:e.id}])),this.addLog("Got characteristics."),"android"===this.platform&&(yield this.BleManager.requestMTU(e.id,g.ANDROID_MAX_MTU).then(t=>{this.addLog(`Successfully updated Android MTU to ${t} bytes. Requested MTU: ${g.ANDROID_MAX_MTU} bytes.`)}).catch(t=>{this.addLog(`Failed to set Android MTU of ${g.ANDROID_MAX_MTU} bytes. Error: ${t}`)})),this.addLog(`Successfully connected to peripheral ${e.id}`),this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTED),n()}catch(t){r(t)}}))})}disconnect(){var i;return t(this,void 0,void 0,function*(){try{this.isConnected()&&(null===(i=null==this?void 0:this.device)||void 0===i?void 0:i.id)&&(yield this.BleManager.disconnect(this.device.id))}catch(t){return Promise.reject(t)}})}getCharacteristicByName(t){var i;if(!(t in this.characteristicsByName))throw new Error(`Characteristic by name ${t} is not found`);return null===(i=this.characteristicsByName)||void 0===i?void 0:i[t]}subscribeToCharacteristic({characteristicName:i,manageNotifications:n=!0}){const c=({peripheralId:r,serviceUUID:c,characteristicUUID:d})=>(0,a.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(r,c,d),this.addLog(`Started notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})).pipe((0,s.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(r,c,d),this.addLog(`Stopped notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})),(0,s.filter)(({characteristic:t})=>t===d),(0,s.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,s.map)(t=>{var e;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${i} characteristic. Falling back to unparsed string. ${null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n}`),t}}));return this.connection$.pipe((0,s.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):r.NEVER))}readCharacteristic(i,e=!1){var n;return t(this,void 0,void 0,function*(){this.addLog(`Reading characteristic: ${i}`);const{peripheralId:t,serviceUUID:r,characteristicUUID:a}=this.getCharacteristicByName(i);if(!a)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));try{const o=yield this.BleManager.read(t,r,a),c=(0,l.decode)(this.type,o),d=e?JSON.parse(c):c;return this.addLog(`Received read data from ${i} characteristic: \n${d}`),d}catch(s){return Promise.reject(new Error(`readCharacteristic ${i} error. ${null!==(n=null==s?void 0:s.message)&&void 0!==n?n:s}`))}})}writeCharacteristic(i,e){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${i}`);const{peripheralId:t,serviceUUID:n,characteristicUUID:r}=this.getCharacteristicByName(i);if(!r)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));const a=(0,l.encode)(this.type,e);yield this.BleManager.write(t,n,r,a,E.REACT_NATIVE_MAX_BYTE_SIZE)})}_addPendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next([...i,t])}_removePendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next(i.filter(i=>i!==t))}_autoToggleActionNotifications(){let i=!1;return this.connection$.asObservable().pipe((0,s.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:r.NEVER),(0,s.tap)(e=>t(this,void 0,void 0,function*(){var t,n;const{peripheralId:r,serviceUUID:a,characteristicUUID:s}=this.getCharacteristicByName("actions"),o=!!e.length;if(o&&!i){i=!0;try{yield this.BleManager.startNotification(r,a,s),this.addLog("Started notifications for [actions] characteristic")}catch(c){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}}if(!o&&i){i=!1;try{yield this.BleManager.stopNotification(r,a,s),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(n=null==c?void 0:c.message)&&void 0!==n?n:c}`)}}})))}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:r=v.DEFAULT_ACTION_RESPONSE_TIMEOUT}=e;return new Promise((o,h)=>t(this,void 0,void 0,function*(){const t=(0,d.create6DigitPin)(),l=JSON.stringify(Object.assign({actionId:t},e));if(this.addLog(`Dispatched action with id ${t}`),n&&r){this._addPendingAction(t);const e=(0,a.timer)(r).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${r}ms`))});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,s.filter)(i=>(null==i?void 0:i.actionId)===t),(0,c.take)(1)).subscribe(i=>{e.unsubscribe(),this._removePendingAction(t),o(i)}),this.writeCharacteristic(i,l).catch(i=>{this._removePendingAction(t),h(i)})}else this.writeCharacteristic(i,l).then(()=>{o(null)}).catch(t=>{h(t)})}))})}}exports.ReactNativeTransport=N;
|
|
71
|
-
},{"
|
|
65
|
+
},{}],"V73a":[function(require,module,exports) {
|
|
66
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.stitchChunks=void 0;const e=require("rxjs"),t=require("rxjs/operators");function r({delimiter:r}){return(0,e.pipe)((0,t.scan)(([e],t)=>{const s=e+t;if(!s.includes(r))return[s,""];if(s.endsWith(r))return["",s];const i=s.lastIndexOf(r)+r.length,n=s.slice(0,i);return[s.slice(i),n]},["",""]),(0,t.map)(([,e])=>e.slice(0,-r.length)),(0,t.filter)(e=>!!e.length))}exports.stitchChunks=r;
|
|
67
|
+
},{}],"MRSy":[function(require,module,exports) {
|
|
68
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.decodeJSONChunks=void 0;const e=require("rxjs"),t=require("./stitch");function r({textCodec:r,characteristicName:i,delimiter:c,addLog:s}){return(0,e.pipe)((0,e.map)(e=>{const t=r.decode(e);return s(`Received chunk with buffer size of ${e.byteLength} and decoded size ${t.length} for ${i} characteristic: \n${t}`),t}),(0,t.stitchChunks)({delimiter:c}),(0,e.map)(e=>{var t;try{return JSON.parse(e)}catch(r){return s(`Failed to parse JSON for ${i} characteristic. Falling back to unparsed string. ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`),e}}))}exports.decodeJSONChunks=r;
|
|
69
|
+
},{"./stitch":"V73a"}],"ouKb":[function(require,module,exports) {
|
|
70
|
+
"use strict";var t=this&&this.__awaiter||function(t,e,i,n){return new(i||(i=Promise))(function(c,s){function o(t){try{a(n.next(t))}catch(e){s(e)}}function r(t){try{a(n.throw(t))}catch(e){s(e)}}function a(t){var e;t.done?c(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,r)}a((n=n.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.WebBluetoothTransport=void 0;const e=require("@neurosity/ipk"),i=require("@neurosity/ipk"),n=require("@neurosity/ipk"),c=require("@neurosity/ipk"),s=require("rxjs"),o=require("rxjs"),r=require("rxjs/operators"),a=require("rxjs/operators"),d=require("rxjs/operators"),h=require("./isWebBluetoothSupported"),u=require("../utils/create6DigitPin"),v=require("../utils/textCodec"),l=require("../types"),g=require("../constants"),p=require("../constants"),N=require("../utils/decodeJSONChunks"),f={autoConnect:!0};class C{constructor(t={}){if(this.type=l.TRANSPORT_TYPE.WEB,this.textCodec=new v.TextCodec(this.type),this.characteristicsByName={},this.connection$=new s.BehaviorSubject(l.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new s.BehaviorSubject([]),this.logs$=new s.ReplaySubject(10),this.onDisconnected$=this._onDisconnected().pipe((0,d.share)()),this.connectionStream$=this.connection$.asObservable().pipe((0,r.filter)(t=>!!t),(0,a.distinctUntilChanged)(),(0,a.shareReplay)(1)),this._isAutoConnectEnabled$=new s.ReplaySubject(1),this.options=Object.assign(Object.assign({},f),t),!(0,h.isWebBluetoothSupported)()){const t="Web Bluetooth is not supported";throw this.addLog(t),new Error(t)}this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this._isAutoConnectEnabled$.next(this.options.autoConnect),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(l.BLUETOOTH_CONNECTION.DISCONNECTED)})}_getPairedDevices(){return t(this,void 0,void 0,function*(){return yield navigator.bluetooth.getDevices()})}_autoConnect(e){return this._isAutoConnectEnabled$.pipe((0,r.switchMap)(t=>t?(0,o.merge)(e,this.onDisconnected$.pipe((0,r.switchMap)(()=>e))):o.NEVER),(0,r.switchMap)(e=>t(this,void 0,void 0,function*(){var t;const{deviceNickname:i}=e;if(this.isConnected())return void this.addLog(`Auto connect: ${i} is already connected. Skipping auto connect.`);const[n,c]=yield this._getPairedDevices().then(t=>[null,t]).catch(t=>[t,null]);if(n)throw new Error(`failed to get devices: ${null!==(t=null==n?void 0:n.message)&&void 0!==t?t:n}`);this.addLog(`Auto connect: found ${c.length} devices ${c.map(({name:t})=>t).join(", ")}`);const s=c.findLast(t=>t.name===i);if(!s)throw new Error("couldn't find selected device in the list of paired devices.");return this.addLog(`Auto connect: ${i} was detected and previously paired`),s})),(0,r.tap)(()=>{this.connection$.next(l.BLUETOOTH_CONNECTION.SCANNING)}),(0,r.switchMap)(t=>O(t)),(0,r.switchMap)(e=>t(this,void 0,void 0,function*(){return this.addLog(`Advertisement received for ${e.device.name}`),yield this.getServerServiceAndCharacteristics(e.device)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===l.BLUETOOTH_CONNECTION.CONNECTED}connection(){return this.connectionStream$}connect(e){return t(this,void 0,void 0,function*(){try{const i=yield this.requestDevice(e);yield this.getServerServiceAndCharacteristics(i)}catch(t){return Promise.reject(t)}})}requestDevice(i){return t(this,void 0,void 0,function*(){try{this.addLog("Requesting Bluetooth Device...");const s=n.BLUETOOTH_DEVICE_NAME_PREFIXES.map(t=>({namePrefix:t})),o=i?[{name:i}]:s;return yield window.navigator.bluetooth.requestDevice({filters:[...o,{manufacturerData:[{companyIdentifier:c.BLUETOOTH_COMPANY_IDENTIFIER_HEX}]}],optionalServices:[e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]})}catch(t){return Promise.reject(t)}})}getServerServiceAndCharacteristics(i){return t(this,void 0,void 0,function*(){try{this.device=i,this.connection$.getValue()===l.BLUETOOTH_CONNECTION.CONNECTING||this.connection$.next(l.BLUETOOTH_CONNECTION.CONNECTING),this.server=yield i.gatt.connect(),this.addLog("Getting service..."),this.service=yield this.server.getPrimaryService(e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX),this.addLog(`Got service ${this.service.uuid}, getting characteristics...`);const n=yield this.service.getCharacteristics();this.addLog("Got characteristics"),this.characteristicsByName=Object.fromEntries(n.map(t=>[p.CHARACTERISTIC_UUIDS_TO_NAMES[t.uuid],t])),this.connection$.next(l.BLUETOOTH_CONNECTION.CONNECTED)}catch(t){return Promise.reject(t)}})}_onDisconnected(){return this.connection$.asObservable().pipe((0,r.switchMap)(t=>t===l.BLUETOOTH_CONNECTION.CONNECTED?E(this.device,"gattserverdisconnected"):o.NEVER))}disconnect(){var e,i;return t(this,void 0,void 0,function*(){(null===(i=null===(e=null==this?void 0:this.device)||void 0===e?void 0:e.gatt)||void 0===i?void 0:i.connected)&&this.device.gatt.disconnect()})}getCharacteristicByName(e){var i;return t(this,void 0,void 0,function*(){return null===(i=this.characteristicsByName)||void 0===i?void 0:i[e]})}subscribeToCharacteristic({characteristicName:e,manageNotifications:n=!0,skipJSONDecoding:c=!1}){const a=(0,o.defer)(()=>this.getCharacteristicByName(e)).pipe((0,r.switchMap)(i=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.startNotifications(),this.addLog(`Started notifications for ${e} characteristic`)}catch(c){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}return i})),(0,r.switchMap)(i=>E(i,"characteristicvaluechanged",()=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.stopNotifications(),this.addLog(`Stopped notifications for ${e} characteristic`)}catch(c){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}}))),(0,r.map)(t=>t.target.value.buffer));return this.connection$.pipe((0,r.switchMap)(t=>t===l.BLUETOOTH_CONNECTION.CONNECTED?a.pipe(c?s.identity:(0,N.decodeJSONChunks)({textCodec:this.textCodec,characteristicName:e,delimiter:i.BLUETOOTH_CHUNK_DELIMITER,addLog:t=>this.addLog(t)})):o.NEVER))}readCharacteristic(e,i=!1){return t(this,void 0,void 0,function*(){try{this.addLog(`Reading characteristic: ${e}`);const n=yield this.getCharacteristicByName(e);if(!n)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const c=(yield n.readValue()).buffer,s=this.textCodec.decode(c),o=i?JSON.parse(s):s;return this.addLog(`Received read data from ${e} characteristic: \n${o}`),o}catch(t){return Promise.reject(`Error reading characteristic: ${t.message}`)}})}writeCharacteristic(e,i){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${e}`);const t=yield this.getCharacteristicByName(e);if(!t)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const n=this.textCodec.encode(i);yield t.writeValueWithResponse(n)})}_addPendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next([...e,t])}_removePendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next(e.filter(e=>e!==t))}_autoToggleActionNotifications(){let e,i=!1;return this.connection$.asObservable().pipe((0,r.switchMap)(t=>t===l.BLUETOOTH_CONNECTION.CONNECTED?(0,o.defer)(()=>this.getCharacteristicByName("actions")).pipe((0,r.switchMap)(t=>(e=t,this.pendingActions$))):o.NEVER),(0,r.tap)(n=>t(this,void 0,void 0,function*(){var t,c;const s=!!n.length;if(s&&!i){i=!0;try{yield e.startNotifications(),this.addLog("Started notifications for [actions] characteristic")}catch(o){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==o?void 0:o.message)&&void 0!==t?t:o}`)}}if(!s&&i){i=!1;try{yield e.stopNotifications(),this.addLog("Stopped notifications for actions characteristic")}catch(o){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(c=null==o?void 0:o.message)&&void 0!==c?c:o}`)}}})))}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:c=g.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((s,a)=>t(this,void 0,void 0,function*(){if(!(yield this.getCharacteristicByName(e).catch(()=>{a(`Did not find characteristic by the name: ${e}`)})))return;const t=(0,u.create6DigitPin)(),h=JSON.stringify(Object.assign({actionId:t},i));if(this.addLog(`Dispatched action with id ${t}`),n&&c){this._addPendingAction(t);const i=(0,o.timer)(c).subscribe(()=>{this._removePendingAction(t),a(`Action with id ${t} timed out after ${c}ms`)});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,r.filter)(e=>(null==e?void 0:e.actionId)===t),(0,d.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),s(e)}),this.writeCharacteristic(e,h).catch(e=>{this._removePendingAction(t),a(e.message)})}else this.writeCharacteristic(e,h).then(()=>{s(null)}).catch(t=>{a(t.message)})}))})}}function E(e,i,n){return(0,o.fromEventPattern)(t=>{e.addEventListener(i,t)},c=>t(this,void 0,void 0,function*(){n&&(yield n()),e.removeEventListener(i,c)}))}function O(t){return new s.Observable(e=>{const i=new AbortController,{signal:n}=i,c=t.addEventListener("advertisementreceived",t=>{i.abort(),e.next(t),e.complete()},{once:!0});try{t.watchAdvertisements({signal:n})}catch(s){e.error(s)}return()=>{i.abort(),t.removeEventListener("advertisementreceived",c)}})}exports.WebBluetoothTransport=C;
|
|
71
|
+
},{"./isWebBluetoothSupported":"ljun","../utils/create6DigitPin":"UDAB","../utils/textCodec":"mUrw","../types":"iwtf","../constants":"dGLb","../utils/decodeJSONChunks":"MRSy"}],"FtS5":[function(require,module,exports) {
|
|
72
|
+
"use strict";var t=this&&this.__awaiter||function(t,e,i,n){return new(i||(i=Promise))(function(r,a){function s(t){try{c(n.next(t))}catch(e){a(e)}}function o(t){try{c(n.throw(t))}catch(e){a(e)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(s,o)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactNativeTransport=void 0;const e=require("@neurosity/ipk"),i=require("@neurosity/ipk"),n=require("@neurosity/ipk"),r=require("rxjs"),a=require("rxjs"),s=require("rxjs/operators"),o=require("rxjs/operators"),c=require("rxjs/operators"),d=require("../utils/create6DigitPin"),h=require("../utils/textCodec"),l=require("../types"),u=require("../constants"),v=require("../constants"),p=require("../constants"),g=require("../constants"),E=require("../utils/decodeJSONChunks"),f={autoConnect:!0};class N{constructor(t){if(this.type=l.TRANSPORT_TYPE.REACT_NATIVE,this.textCodec=new h.TextCodec(this.type),this.characteristicsByName={},this.connection$=new r.BehaviorSubject(l.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new r.BehaviorSubject([]),this.logs$=new r.ReplaySubject(10),this.connectionStream$=this.connection$.asObservable().pipe((0,s.filter)(t=>!!t),(0,o.distinctUntilChanged)(),(0,o.shareReplay)(1)),this._isAutoConnectEnabled$=new r.ReplaySubject(1),!t){const t="React Native transport: missing options.";throw this.addLog(t),new Error(t)}this.options=Object.assign(Object.assign({},f),t);const{BleManager:e,bleManagerEmitter:i,platform:n,autoConnect:a}=this.options;if(!e){const t="React Native option: BleManager not provided.";throw this.addLog(t),new Error(t)}if(!i){const t="React Native option: bleManagerEmitter not provided.";throw this.addLog(t),new Error(t)}if(!n){const t="React Native option: platform not provided.";throw this.addLog(t),new Error(t)}this.BleManager=e,this.bleManagerEmitter=i,this.platform=n,this._isAutoConnectEnabled$.next(a),this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this.bleEvents={stopScan$:this._fromEvent("BleManagerStopScan"),discoverPeripheral$:this._fromEvent("BleManagerDiscoverPeripheral"),connectPeripheral$:this._fromEvent("BleManagerConnectPeripheral"),disconnectPeripheral$:this._fromEvent("BleManagerDisconnectPeripheral"),didUpdateValueForCharacteristic$:this._fromEvent("BleManagerDidUpdateValueForCharacteristic"),didUpdateState$:this._fromEvent("BleManagerDidUpdateState")},this.onDisconnected$=this.bleEvents.disconnectPeripheral$.pipe((0,c.share)()),this.BleManager.start({showAlert:!1}).then(()=>{this.addLog("BleManger started")}).catch(t=>{var e;this.addLog(`BleManger failed to start. ${null!==(e=null==t?void 0:t.message)&&void 0!==e?e:t}`)}),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(l.BLUETOOTH_CONNECTION.DISCONNECTED)})}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===l.BLUETOOTH_CONNECTION.CONNECTED}_autoConnect(e){const i=this.onDisconnected$.pipe((0,s.switchMap)(()=>e));return this._isAutoConnectEnabled$.pipe((0,s.switchMap)(t=>t?(0,a.merge)(e,i):r.NEVER),(0,s.switchMap)(t=>this.scan().pipe((0,s.switchMap)(e=>{const i=e.find(e=>e.name===(null==t?void 0:t.deviceNickname));return i?(0,a.of)(i):r.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1))),(0,s.switchMap)(e=>t(this,void 0,void 0,function*(){return yield this.connect(e)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}connection(){return this.connectionStream$}_fromEvent(t){return(0,a.fromEventPattern)(e=>{this.bleManagerEmitter.addListener(t,e)},()=>{this.bleManagerEmitter.removeAllListeners(t)}).pipe((0,c.share)())}scan(t){var i,d,h;const u=null!==(i=null==t?void 0:t.seconds)&&void 0!==i?i:10,v=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,p=null!==(h=null==t?void 0:t.skipConnectionUpdate)&&void 0!==h&&h,g=[e.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],E={},f=new r.Observable(t=>{var e;try{this.BleManager.scan(g,u,!0,E).then(()=>{this.addLog(`BleManger scanning ${v?"once":"indefintely"}`),t.next()})}catch(i){this.addLog(`BleManger scanning ${v?"once":"indefintely"} failed. ${null!==(e=null==i?void 0:i.message)&&void 0!==e?e:i}`),t.error(i)}return()=>{this.BleManager.stopScan()}});return(v?f:(0,a.timer)(0,1e4).pipe((0,s.switchMap)(()=>f))).pipe((0,s.tap)(()=>{p||this.connection$.next(l.BLUETOOTH_CONNECTION.SCANNING)}),(0,s.takeUntil)(this.onDisconnected$),(0,s.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,s.filter)(t=>{var e,i,r;const a=null!==(r=null!==(i=null===(e=null==t?void 0:t.advertising)||void 0===e?void 0:e.localName)&&void 0!==i?i:t.name)&&void 0!==r?r:"";return!!a&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>a.startsWith(t))}),(0,c.scan)((t,e)=>{var i,n,r,a,s,o,c,d;const h=null!==(r=null!==(n=null===(i=null==e?void 0:e.advertising)||void 0===i?void 0:i.localName)&&void 0!==n?n:e.name)&&void 0!==r?r:"",l=null===(d=null===(c=this.textCodec.decode(null!==(o=null===(s=null===(a=null==e?void 0:e.advertising)||void 0===a?void 0:a.manufacturerData)||void 0===s?void 0:s.bytes)&&void 0!==o?o:[]))||void 0===c?void 0:c.slice)||void 0===d?void 0:d.call(c,2);return Object.assign(Object.assign({},t),{[e.id]:Object.assign(Object.assign({},e),{name:h,manufactureDataString:l})})},{}),(0,o.distinctUntilChanged)((t,e)=>JSON.stringify(t)===JSON.stringify(e)),(0,s.map)(t=>Object.values(t)),(0,c.share)())}connect(i){return t(this,void 0,void 0,function*(){return new Promise((n,r)=>t(this,void 0,void 0,function*(){try{if(!i)return void this.addLog("Peripheral not found");this.connection$.next(l.BLUETOOTH_CONNECTION.CONNECTING),yield this.BleManager.connect(i.id),this.addLog("Getting service...");const a=yield this.BleManager.retrieveServices(i.id,[e.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!a)return this.addLog("Could not retreive services"),void r(new Error("Could not retreive services"));this.addLog(`Got service ${e.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`),this.device=i,this.characteristicsByName=Object.fromEntries(a.characteristics.map(t=>[v.CHARACTERISTIC_UUIDS_TO_NAMES[t.characteristic.toLowerCase()],{characteristicUUID:t.characteristic,serviceUUID:t.service,peripheralId:i.id}])),this.addLog("Got characteristics."),"android"===this.platform&&(yield this.BleManager.requestMTU(i.id,p.ANDROID_MAX_MTU).then(t=>{this.addLog(`Successfully updated Android MTU to ${t} bytes. Requested MTU: ${p.ANDROID_MAX_MTU} bytes.`)}).catch(t=>{this.addLog(`Failed to set Android MTU of ${p.ANDROID_MAX_MTU} bytes. Error: ${t}`)})),this.addLog(`Successfully connected to peripheral ${i.id}`),this.connection$.next(l.BLUETOOTH_CONNECTION.CONNECTED),n()}catch(t){r(t)}}))})}disconnect(){var e;return t(this,void 0,void 0,function*(){try{this.isConnected()&&(null===(e=null==this?void 0:this.device)||void 0===e?void 0:e.id)&&(yield this.BleManager.disconnect(this.device.id))}catch(t){return Promise.reject(t)}})}getCharacteristicByName(t){var e;if(!(t in this.characteristicsByName))throw new Error(`Characteristic by name ${t} is not found`);return null===(e=this.characteristicsByName)||void 0===e?void 0:e[t]}subscribeToCharacteristic({characteristicName:e,manageNotifications:n=!0,skipJSONDecoding:c=!1}){const d=({peripheralId:i,serviceUUID:r,characteristicUUID:c})=>(0,a.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(i,r,c),this.addLog(`Started notifications for ${e} characteristic`)}catch(a){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==a?void 0:a.message)&&void 0!==t?t:a}`)}})).pipe((0,s.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(i,r,c),this.addLog(`Stopped notifications for ${e} characteristic`)}catch(a){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==a?void 0:a.message)&&void 0!==t?t:a}`)}})),(0,s.filter)(({characteristic:t})=>t===c),(0,s.map)(({value:t})=>new Uint8Array(t)));return this.connection$.pipe((0,s.switchMap)(t=>t===l.BLUETOOTH_CONNECTION.CONNECTED?d(this.getCharacteristicByName(e)).pipe(c?a.identity:(0,E.decodeJSONChunks)({textCodec:this.textCodec,characteristicName:e,delimiter:i.BLUETOOTH_CHUNK_DELIMITER,addLog:t=>this.addLog(t)})):r.NEVER))}readCharacteristic(e,i=!1){var n;return t(this,void 0,void 0,function*(){this.addLog(`Reading characteristic: ${e}`);const{peripheralId:t,serviceUUID:r,characteristicUUID:a}=this.getCharacteristicByName(e);if(!a)return Promise.reject(new Error(`Did not find characteristic matching ${e}`));try{const o=yield this.BleManager.read(t,r,a),c=this.textCodec.decode(new Uint8Array(o)),d=i?JSON.parse(c):c;return this.addLog(`Received read data from ${e} characteristic: \n${d}`),d}catch(s){return Promise.reject(new Error(`readCharacteristic ${e} error. ${null!==(n=null==s?void 0:s.message)&&void 0!==n?n:s}`))}})}writeCharacteristic(e,i){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${e}`);const{peripheralId:t,serviceUUID:n,characteristicUUID:r}=this.getCharacteristicByName(e);if(!r)return Promise.reject(new Error(`Did not find characteristic matching ${e}`));const a=this.textCodec.encode(i);yield this.BleManager.write(t,n,r,a,g.REACT_NATIVE_MAX_BYTE_SIZE)})}_addPendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next([...e,t])}_removePendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next(e.filter(e=>e!==t))}_autoToggleActionNotifications(){let e=!1;return this.connection$.asObservable().pipe((0,s.switchMap)(t=>t===l.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:r.NEVER),(0,s.tap)(i=>t(this,void 0,void 0,function*(){var t,n;const{peripheralId:r,serviceUUID:a,characteristicUUID:s}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!e){e=!0;try{yield this.BleManager.startNotification(r,a,s),this.addLog("Started notifications for [actions] characteristic")}catch(c){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}}if(!o&&e){e=!1;try{yield this.BleManager.stopNotification(r,a,s),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(n=null==c?void 0:c.message)&&void 0!==n?n:c}`)}}})))}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:r=u.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((o,h)=>t(this,void 0,void 0,function*(){const t=(0,d.create6DigitPin)(),l=JSON.stringify(Object.assign({actionId:t},i));if(this.addLog(`Dispatched action with id ${t}`),n&&r){this._addPendingAction(t);const i=(0,a.timer)(r).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${r}ms`))});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,s.filter)(e=>(null==e?void 0:e.actionId)===t),(0,c.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),o(e)}),this.writeCharacteristic(e,l).catch(e=>{this._removePendingAction(t),h(e)})}else this.writeCharacteristic(e,l).then(()=>{o(null)}).catch(t=>{h(t)})}))})}}exports.ReactNativeTransport=N;
|
|
73
|
+
},{"../utils/create6DigitPin":"UDAB","../utils/textCodec":"mUrw","../types":"iwtf","../constants":"dGLb","../utils/decodeJSONChunks":"MRSy"}],"Oj1i":[function(require,module,exports) {
|
|
72
74
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.epoch=exports.bufferToEpoch=exports.addInfo=void 0;const e=require("rxjs"),t=require("rxjs/operators"),a="data",o=256,n=e=>e instanceof Object&&e===Object(e),s=e=>"function"==typeof e,i=e=>t=>{var a;return Object.assign(Object.assign({},e),{info:Object.assign(Object.assign({},null!==(a=null==e?void 0:e.info)&&void 0!==a?a:{}),t||{})})},r=a=>(0,e.pipe)((0,t.map)(e=>{if(!n(e)||!n(a)&&!s(a))return e;const t=s(a)?a(e):a;return i(e)(t)}));exports.addInfo=r;const p=(e,t="data")=>e[0][t].map((a,o)=>e.map(e=>e[t][o])),c=({samplingRate:a=256,dataProp:o="data"}={})=>(0,e.pipe)((0,t.map)(e=>({[o]:p(e,o),info:Object.assign(Object.assign({},e[0]&&e[0].info?e[0].info:{}),{startTime:e[0].timestamp,samplingRate:e[0].info&&e[0].info.samplingRate?e[0].info.samplingRate:a})})));exports.bufferToEpoch=c;const f=({duration:a,interval:o,samplingRate:n,dataProp:s="data"})=>(0,e.pipe)((0,t.bufferCount)(o),(0,t.scan)((e,t)=>e.concat(t).slice(e.length<a?0:-a)),(0,t.filter)(e=>e.length===a),(0,exports.bufferToEpoch)({samplingRate:n,dataProp:s}));exports.epoch=f;
|
|
73
|
-
},{}],"
|
|
74
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.
|
|
75
|
+
},{}],"D2Cx":[function(require,module,exports) {
|
|
76
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.encodedSampleSize=exports.decode=exports.binaryBufferToSamples=exports.binaryBufferToEpoch=void 0;const e=require("rxjs"),r=require("rxjs/operators"),n=require("buffer/index.js"),t=require("../../../utils/pipes"),o=16,a=256,i=8,l=2,s=8,p=i+l;function u(r){var n;return(null==r?void 0:r.samplingRate)||console.warn(`Didn't receive a sampling rate, defaulting to ${a}`),(0,e.pipe)(f(r.channels),(0,t.epoch)({duration:o,interval:o,samplingRate:null!==(n=null==r?void 0:r.samplingRate)&&void 0!==n?n:a}),(0,t.addInfo)({channelNames:r.channelNames,samplingRate:r.samplingRate}))}function f(t){return(0,e.pipe)((0,r.mergeMap)(r=>{const o=d(n.Buffer.from(r),t);return(0,e.from)(o)}))}function d(e,r){let n=c(r);if(e.length%n!=0)throw new Error(`buffer.length (${e.length}) for ${r} channels must be multiple of ${n}B)`);let t=e.length/n,o=new Array(t);for(let a=0;a<t;a++){let t=a*n,p=new Array(r),u=e.readBigUInt64BE(t);t+=i;e.readUInt16BE(t);t+=l;for(let n=0;n<r;n++)p[n]=e.readDoubleBE(t),t+=s;o[a]={timestamp:Number(u),data:p}}return o}function c(e){return p+e*s}exports.binaryBufferToEpoch=u,exports.binaryBufferToSamples=f,exports.decode=d,exports.encodedSampleSize=c;
|
|
75
77
|
},{"../../../utils/pipes":"Oj1i"}],"fihV":[function(require,module,exports) {
|
|
76
|
-
"use strict";var t=this&&this.__awaiter||function(t,e,i,s){return new(i||(i=Promise))(function(r,n){function o(t){try{c(s.next(t))}catch(e){n(e)}}function a(t){try{c(s.throw(t))}catch(e){n(e)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}c((s=s.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothClient=void 0;const e=require("rxjs"),i=require("rxjs"),s=require("rxjs/operators"),r=require("./web/WebBluetoothTransport"),n=require("./react-native/ReactNativeTransport"),o=require("./utils/
|
|
77
|
-
},{"./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/
|
|
78
|
+
"use strict";var t=this&&this.__awaiter||function(t,e,i,s){return new(i||(i=Promise))(function(r,n){function o(t){try{c(s.next(t))}catch(e){n(e)}}function a(t){try{c(s.throw(t))}catch(e){n(e)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}c((s=s.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothClient=void 0;const e=require("rxjs"),i=require("rxjs"),s=require("rxjs/operators"),r=require("./web/WebBluetoothTransport"),n=require("./react-native/ReactNativeTransport"),o=require("./utils/binaryBufferToEpoch"),a=require("./types");class c{constructor(t){this.selectedDevice$=new i.ReplaySubject(1),this.osHasBluetoothSupport$=new i.ReplaySubject(1),this.isAuthenticated$=new i.ReplaySubject(1);const{transport:e,selectedDevice$:r,osHasBluetoothSupport$:n,createBluetoothToken:o}=null!=t?t:{};if(!e)throw new Error("No bluetooth transport provided.");this.transport=e,r&&r.subscribe(this.selectedDevice$),n&&n.subscribe(this.osHasBluetoothSupport$),this.osHasBluetoothSupport$.pipe((0,s.switchMap)(t=>t?this.transport._autoConnect(this.selectedDevice$):i.EMPTY)).subscribe({error:t=>{var e;this.transport.addLog(`Auto connect: error -> ${null!==(e=null==t?void 0:t.message)&&void 0!==e?e:t}`)}}),"function"==typeof o?(this.transport.addLog("Auto authentication enabled"),this._autoAuthenticate(o).subscribe()):this.transport.addLog("Auto authentication not enabled"),this.osHasBluetoothSupport$.pipe((0,s.switchMap)(t=>t?this.transport._autoToggleActionNotifications():i.EMPTY)).subscribe(),this._focus$=this._subscribeWhileAuthenticated("focus"),this._calm$=this._subscribeWhileAuthenticated("calm"),this._accelerometer$=this._subscribeWhileAuthenticated("accelerometer"),this._brainwavesRaw$=this._subscribeWhileAuthenticated("raw",!0),this._brainwavesRawUnfiltered$=this._subscribeWhileAuthenticated("rawUnfiltered",!0),this._brainwavesPSD$=this._subscribeWhileAuthenticated("psd"),this._brainwavesPowerByBand$=this._subscribeWhileAuthenticated("powerByBand"),this._signalQuality$=this._subscribeWhileAuthenticated("signalQuality"),this._status$=this._subscribeWhileAuthenticated("status"),this._settings$=this._subscribeWhileAuthenticated("settings"),this._wifiNearbyNetworks$=this._subscribeWhileAuthenticated("wifiNearbyNetworks"),this._wifiConnections$=this._subscribeWhileAuthenticated("wifiConnections")}_autoAuthenticate(r){const n=(0,e.timer)(0,36e5).pipe((0,s.tap)(()=>{this.transport.addLog("Auto authentication in progress...")}));return this.osHasBluetoothSupport$.pipe((0,s.switchMap)(t=>t?this.connection():i.EMPTY),(0,s.switchMap)(t=>t===a.BLUETOOTH_CONNECTION.CONNECTED?n:i.EMPTY),(0,s.switchMap)(()=>t(this,void 0,void 0,function*(){return yield this.isAuthenticated()})),(0,s.tap)(([e])=>t(this,void 0,void 0,function*(){if(e)this.transport.addLog("Already authenticated");else{const t=yield r();yield this.authenticate(t)}})))}enableAutoConnect(t){this.transport.enableAutoConnect(t)}_hasBluetoothSupport(){return t(this,void 0,void 0,function*(){return yield(0,i.firstValueFrom)(this.osHasBluetoothSupport$)})}authenticate(e){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="authenticate method: The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}yield this.transport.writeCharacteristic("auth",e);const t=yield this.isAuthenticated(),[i]=t;return this.transport.addLog(`Authentication ${i?"succeeded":"failed"}`),this.isAuthenticated$.next(i),t})}isAuthenticated(){return t(this,void 0,void 0,function*(){try{const[e,i]=yield this.transport.readCharacteristic("auth",!0);return this.isAuthenticated$.next(e),[e,i]}catch(t){const e=[!1,null];return this.transport.addLog(`Authentication error -> ${t}`),this.isAuthenticated$.next(!1),e}})}scan(t){if(this.transport instanceof n.ReactNativeTransport)return this.transport.scan(t);if(this.transport instanceof r.WebBluetoothTransport)throw new Error("scan method is compatibly with the React Native transport only");throw new Error("unknown transport")}connect(t){return this.transport instanceof n.ReactNativeTransport?this.transport.connect(t):this.transport instanceof r.WebBluetoothTransport?t?this.transport.connect(t):this.transport.connect():void 0}disconnect(){return this.transport.disconnect()}connection(){return this.transport.connection()}logs(){return this.transport.logs$.asObservable()}getDeviceId(){return t(this,void 0,void 0,function*(){return this.transport.readCharacteristic("deviceId")})}_withAuthentication(e){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}if(!(yield(0,i.firstValueFrom)(this.isAuthenticated$))){const t="Authentication required.";return this.transport.addLog(t),Promise.reject(t)}return yield e()})}_subscribeWhileAuthenticated(t,e=!1){return this.osHasBluetoothSupport$.pipe((0,s.switchMap)(t=>t?this.isAuthenticated$:i.EMPTY),(0,s.distinctUntilChanged)(),(0,s.switchMap)(s=>s?this.transport.subscribeToCharacteristic({characteristicName:t,skipJSONDecoding:e}):i.EMPTY),(0,s.share)())}focus(){return this._focus$}calm(){return this._calm$}accelerometer(){return this._accelerometer$}brainwaves(t){switch(t){default:case"raw":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRaw$.pipe((0,o.binaryBufferToEpoch)(t))));case"rawUnfiltered":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRawUnfiltered$.pipe((0,o.binaryBufferToEpoch)(t))));case"psd":return this._brainwavesPSD$;case"powerByBand":return this._brainwavesPowerByBand$}}signalQuality(){return this._signalQuality$}addMarker(e){return t(this,void 0,void 0,function*(){yield this.dispatchAction({action:"marker",command:"add",message:{timestamp:Date.now(),label:e}})})}getInfo(){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>(0,i.firstValueFrom)(this.transport.subscribeToCharacteristic({characteristicName:"deviceInfo"})))})}status(){return this._status$}dispatchAction(e){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>this.transport.dispatchAction({characteristicName:"actions",action:e}))})}settings(){return this._settings$}haptics(t){return this.dispatchAction({action:"haptics",command:"queue",responseRequired:!0,responseTimeout:4e3,message:{effects:t}})}get wifi(){return{nearbyNetworks:()=>this._wifiNearbyNetworks$,connections:()=>this._wifiConnections$,connect:(t,e)=>t?this.dispatchAction({action:"wifi",command:"connect",responseRequired:!0,responseTimeout:12e4,message:{ssid:t,password:null!=e?e:null}}):Promise.reject("Missing ssid"),forgetConnection:t=>t?this.dispatchAction({action:"wifi",command:"forget-connection",responseRequired:!0,responseTimeout:15e3,message:{ssid:t}}):Promise.reject("Missing ssid"),reset:()=>this.dispatchAction({action:"wifi",command:"reset",responseRequired:!0,responseTimeout:3e4,message:{respondOnSuccess:!0}}),speedTest:()=>this.dispatchAction({action:"wifi",command:"speed-test",responseRequired:!0,responseTimeout:6e4})}}}exports.BluetoothClient=c;
|
|
79
|
+
},{"./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/binaryBufferToEpoch":"D2Cx","./types":"iwtf"}],"rH2Y":[function(require,module,exports) {
|
|
78
80
|
"use strict";var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.osHasBluetoothSupport=void 0;const t=e(require("semver/functions/gte"));function o(e,o){if(!e)return!1;return Number(e.modelVersion)>=3&&(!!!(null==e?void 0:e.emulator)&&(0,t.default)(null!=o?o:e.osVersion,"16.0.0"))}exports.osHasBluetoothSupport=o;
|
|
79
81
|
},{}],"TICO":[function(require,module,exports) {
|
|
80
82
|
"use strict";var e=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&("get"in i?t.__esModule:!i.writable&&!i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),t=this&&this.__exportStar||function(t,r){for(var o in t)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||e(r,t,o)};Object.defineProperty(exports,"__esModule",{value:!0}),t(require("./BluetoothClient"),exports),t(require("./web/WebBluetoothTransport"),exports),t(require("./react-native/ReactNativeTransport"),exports),t(require("./utils/osHasBluetoothSupport"),exports),t(require("./types/index"),exports);
|