@neurosity/sdk 6.2.2 → 6.2.3

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.
@@ -55,6 +55,7 @@ export declare class ReactNativeTransport implements BluetoothTransport {
55
55
  scan(options?: {
56
56
  seconds?: number;
57
57
  once?: boolean;
58
+ skipConnectionUpdate?: boolean;
58
59
  }): Observable<Peripheral[]>;
59
60
  connect(peripheral: Peripheral): Promise<void>;
60
61
  disconnect(): Promise<void>;
@@ -134,10 +134,14 @@ class ReactNativeTransport {
134
134
  (0, operators_3.share)());
135
135
  }
136
136
  scan(options) {
137
- var _a, _b;
137
+ var _a, _b, _c;
138
138
  const RESCAN_INTERVAL = 10000; // 10 seconds
139
139
  const seconds = (_a = options === null || options === void 0 ? void 0 : options.seconds) !== null && _a !== void 0 ? _a : RESCAN_INTERVAL / 1000;
140
140
  const once = (_b = options === null || options === void 0 ? void 0 : options.once) !== null && _b !== void 0 ? _b : false;
141
+ // If we are already connected to a peripheral and start scanning,
142
+ // be default, it will set the connection status to SCANNING and not
143
+ // update it back if no device is connected to
144
+ const skipConnectionUpdate = (_c = options === null || options === void 0 ? void 0 : options.skipConnectionUpdate) !== null && _c !== void 0 ? _c : false;
141
145
  const serviceUUIDs = [ipk_1.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING];
142
146
  const allowDuplicates = true;
143
147
  const scanOptions = {};
@@ -161,7 +165,9 @@ class ReactNativeTransport {
161
165
  ? scanOnce$
162
166
  : (0, rxjs_1.timer)(0, RESCAN_INTERVAL).pipe((0, operators_1.switchMap)(() => scanOnce$));
163
167
  const peripherals$ = scan$.pipe((0, operators_1.tap)(() => {
164
- this.connection$.next(types_1.BLUETOOTH_CONNECTION.SCANNING);
168
+ if (!skipConnectionUpdate) {
169
+ this.connection$.next(types_1.BLUETOOTH_CONNECTION.SCANNING);
170
+ }
165
171
  }), (0, operators_1.takeUntil)(this.onDisconnected$), (0, operators_1.switchMap)(() => this.bleEvents.discoverPeripheral$),
166
172
  // Filter out devices that are not Neurosity devices
167
173
  (0, operators_1.filter)((peripheral) => {
@@ -69,7 +69,7 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
69
69
  },{}],"ouKb":[function(require,module,exports) {
70
70
  "use strict";var t=this&&this.__awaiter||function(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(t){try{a(n.next(t))}catch(e){o(e)}}function c(t){try{a(n.throw(t))}catch(e){o(e)}}function a(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,c)}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"),s=require("@neurosity/ipk"),o=require("rxjs"),r=require("rxjs"),c=require("rxjs/operators"),a=require("rxjs/operators"),d=require("rxjs/operators"),h=require("./isWebBluetoothSupported"),u=require("../utils/create6DigitPin"),v=require("../utils/stitch"),l=require("../utils/encoding"),p=require("../types"),g=require("../constants"),f=require("../constants"),E=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class C{constructor(t={}){if(this.type=p.TRANSPORT_TYPE.WEB,this.characteristicsByName={},this.connection$=new o.BehaviorSubject(p.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new o.BehaviorSubject([]),this.logs$=new o.ReplaySubject(10),this.onDisconnected$=this._onDisconnected().pipe((0,d.share)()),this.connectionStream$=this.connection$.asObservable().pipe((0,c.filter)(t=>!!t),(0,a.distinctUntilChanged)(),(0,a.shareReplay)(1)),this._isAutoConnectEnabled$=new o.ReplaySubject(1),this.options=Object.assign(Object.assign({},N),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(p.BLUETOOTH_CONNECTION.DISCONNECTED)})}_getPairedDevices(){return t(this,void 0,void 0,function*(){return yield navigator.bluetooth.getDevices()})}_autoConnect(e){return this._isAutoConnectEnabled$.pipe((0,c.switchMap)(t=>t?(0,o.merge)(e,this.onDisconnected$.pipe((0,c.switchMap)(()=>e))):r.NEVER),(0,c.switchMap)(t=>(0,E.osHasBluetoothSupport)(t)?(0,o.of)(t):r.EMPTY),(0,c.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,s]=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 ${s.length} devices ${s.map(({name:t})=>t).join(", ")}`);const o=s.findLast(t=>t.name===i);if(!o)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`),o})),(0,c.tap)(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.SCANNING)}),(0,c.switchMap)(t=>m(t)),(0,c.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()===p.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 o=n.BLUETOOTH_DEVICE_NAME_PREFIXES.map(t=>({namePrefix:t})),r=i?[{name:i}]:o;return yield window.navigator.bluetooth.requestDevice({filters:[...r,{manufacturerData:[{companyIdentifier:s.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()===p.BLUETOOTH_CONNECTION.CONNECTING||this.connection$.next(p.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=>[f.CHARACTERISTIC_UUIDS_TO_NAMES[t.uuid],t])),this.connection$.next(p.BLUETOOTH_CONNECTION.CONNECTED)}catch(t){return Promise.reject(t)}})}_onDisconnected(){return this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?O(this.device,"gattserverdisconnected"):r.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}){const s=(0,o.defer)(()=>this.getCharacteristicByName(e)).pipe((0,c.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(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}return i})),(0,c.switchMap)(i=>O(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(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}}))),(0,c.map)(t=>{const i=t.target.value,n=(0,l.decode)(this.type,i);return this.addLog(`Received chunk with buffer size of ${i.byteLength} and decoded size ${n.length} for ${e} characteristic: \n${n}`),n}),(0,v.stitchChunks)({delimiter:i.BLUETOOTH_CHUNK_DELIMITER}),(0,c.map)(t=>{var i;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${e} characteristic. Falling back to unparsed string. ${null!==(i=null==n?void 0:n.message)&&void 0!==i?i:n}`),t}}));return this.connection$.pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?s:r.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 s=yield n.readValue(),o=(0,l.decode)(this.type,s),r=i?JSON.parse(o):o;return this.addLog(`Received read data from ${e} characteristic: \n${r}`),r}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=(0,l.encode)(this.type,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(e){return t(this,void 0,void 0,function*(){let i,n=!1;const s=this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?(0,o.defer)(()=>this.getCharacteristicByName("actions")).pipe((0,c.switchMap)(t=>(i=t,this.pendingActions$))):r.NEVER),(0,c.tap)(e=>t(this,void 0,void 0,function*(){var t,s;const o=!!e.length;if(o&&!n){n=!0;try{yield i.startNotifications(),this.addLog("Started notifications for [actions] characteristic")}catch(r){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`)}}if(!o&&n){n=!1;try{yield i.stopNotifications(),this.addLog("Stopped notifications for actions characteristic")}catch(r){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(s=null==r?void 0:r.message)&&void 0!==s?s:r}`)}}})));e.pipe((0,c.switchMap)(t=>(0,E.osHasBluetoothSupport)(t)?s:r.EMPTY)).subscribe()})}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=g.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((r,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&&s){this._addPendingAction(t);const i=(0,o.timer)(s).subscribe(()=>{this._removePendingAction(t),a(`Action with id ${t} timed out after ${s}ms`)});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,c.filter)(e=>(null==e?void 0:e.actionId)===t),(0,d.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),r(e)}),this.writeCharacteristic(e,h).catch(e=>{this._removePendingAction(t),a(e.message)})}else this.writeCharacteristic(e,h).then(()=>{r(null)}).catch(t=>{a(t.message)})}))})}}function O(e,i,n){return(0,r.fromEventPattern)(t=>{e.addEventListener(i,t)},s=>t(this,void 0,void 0,function*(){n&&(yield n()),e.removeEventListener(i,s)}))}function m(t){return new r.Observable(e=>{const i=new AbortController,{signal:n}=i,s=t.addEventListener("advertisementreceived",t=>{i.abort(),e.next(t),e.complete()},{once:!0});try{t.watchAdvertisements({signal:n})}catch(o){e.error(o)}return()=>{i.abort(),t.removeEventListener("advertisementreceived",s)}})}exports.WebBluetoothTransport=C;
71
71
  },{"./isWebBluetoothSupported":"ljun","../utils/create6DigitPin":"UDAB","../utils/stitch":"V73a","../utils/encoding":"jTvL","../types":"iwtf","../constants":"dGLb","../utils/osHasBluetoothSupport":"rH2Y"}],"FtS5":[function(require,module,exports) {
72
- "use strict";var t=this&&this.__awaiter||function(t,i,e,n){return new(e||(e=Promise))(function(r,s){function a(t){try{c(n.next(t))}catch(i){s(i)}}function o(t){try{c(n.throw(t))}catch(i){s(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(a,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"),s=require("rxjs"),a=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=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class m{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,a.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({},N),t);const{BleManager:i,bleManagerEmitter:e,platform:n,autoConnect:s}=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(s),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,a.switchMap)(()=>i));return this._isAutoConnectEnabled$.pipe((0,a.switchMap)(t=>t?(0,r.merge)(i,e):s.NEVER),(0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?this.scan().pipe((0,a.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,r.of)(e):s.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1)):s.NEVER),(0,a.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,s.fromEventPattern)(i=>{this.bleManagerEmitter.addListener(t,i)},()=>{this.bleManagerEmitter.removeAllListeners(t)}).pipe((0,c.share)())}scan(t){var e,d;const h=null!==(e=null==t?void 0:t.seconds)&&void 0!==e?e:10,v=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,p=[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],g={},E=new s.Observable(t=>{var i;try{this.BleManager.scan(p,h,!0,g).then(()=>{this.addLog(`BleManger scanning ${v?"once":"indefintely"}`),t.next()})}catch(e){this.addLog(`BleManger scanning ${v?"once":"indefintely"} failed. ${null!==(i=null==e?void 0:e.message)&&void 0!==i?i:e}`),t.error(e)}return()=>{this.BleManager.stopScan()}});return(v?E:(0,r.timer)(0,1e4).pipe((0,a.switchMap)(()=>E))).pipe((0,a.tap)(()=>{this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,a.takeUntil)(this.onDisconnected$),(0,a.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,a.filter)(t=>{var i,e,r;const s=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!!s&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>s.startsWith(t))}),(0,c.scan)((t,i)=>{var e,n,r,s,a,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===(a=null===(s=null==i?void 0:i.advertising)||void 0===s?void 0:s.manufacturerData)||void 0===a?void 0:a.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,a.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 s=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!s)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(s.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:s,serviceUUID:c,characteristicUUID:d})=>(0,r.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(s,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,a.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(s,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,a.filter)(({characteristic:t})=>t===d),(0,a.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,a.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,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):s.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:s}=this.getCharacteristicByName(i);if(!s)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));try{const o=yield this.BleManager.read(t,r,s),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(a){return Promise.reject(new Error(`readCharacteristic ${i} error. ${null!==(n=null==a?void 0:a.message)&&void 0!==n?n:a}`))}})}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 s=(0,l.encode)(this.type,e);yield this.BleManager.write(t,n,r,s,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(i){return t(this,void 0,void 0,function*(){let e=!1;const n=this.connection$.asObservable().pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:s.NEVER),(0,a.tap)(i=>t(this,void 0,void 0,function*(){var t,n;const{peripheralId:r,serviceUUID:s,characteristicUUID:a}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!e){e=!0;try{yield this.BleManager.startNotification(r,s,a),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,s,a),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}`)}}})));i.pipe((0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?n:s.EMPTY)).subscribe()})}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=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&&s){this._addPendingAction(t);const e=(0,r.timer)(s).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${s}ms`))});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,a.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=m;
72
+ "use strict";var t=this&&this.__awaiter||function(t,i,e,n){return new(e||(e=Promise))(function(r,s){function a(t){try{c(n.next(t))}catch(i){s(i)}}function o(t){try{c(n.throw(t))}catch(i){s(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(a,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"),s=require("rxjs"),a=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=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class m{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,a.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({},N),t);const{BleManager:i,bleManagerEmitter:e,platform:n,autoConnect:s}=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(s),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,a.switchMap)(()=>i));return this._isAutoConnectEnabled$.pipe((0,a.switchMap)(t=>t?(0,r.merge)(i,e):s.NEVER),(0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?this.scan().pipe((0,a.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,r.of)(e):s.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1)):s.NEVER),(0,a.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,s.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 s.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,r.timer)(0,1e4).pipe((0,a.switchMap)(()=>N))).pipe((0,a.tap)(()=>{g||this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,a.takeUntil)(this.onDisconnected$),(0,a.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,a.filter)(t=>{var i,e,r;const s=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!!s&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>s.startsWith(t))}),(0,c.scan)((t,i)=>{var e,n,r,s,a,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===(a=null===(s=null==i?void 0:i.advertising)||void 0===s?void 0:s.manufacturerData)||void 0===a?void 0:a.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,a.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 s=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!s)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(s.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:s,serviceUUID:c,characteristicUUID:d})=>(0,r.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(s,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,a.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(s,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,a.filter)(({characteristic:t})=>t===d),(0,a.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,a.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,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):s.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:s}=this.getCharacteristicByName(i);if(!s)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));try{const o=yield this.BleManager.read(t,r,s),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(a){return Promise.reject(new Error(`readCharacteristic ${i} error. ${null!==(n=null==a?void 0:a.message)&&void 0!==n?n:a}`))}})}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 s=(0,l.encode)(this.type,e);yield this.BleManager.write(t,n,r,s,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(i){return t(this,void 0,void 0,function*(){let e=!1;const n=this.connection$.asObservable().pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:s.NEVER),(0,a.tap)(i=>t(this,void 0,void 0,function*(){var t,n;const{peripheralId:r,serviceUUID:s,characteristicUUID:a}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!e){e=!0;try{yield this.BleManager.startNotification(r,s,a),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,s,a),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}`)}}})));i.pipe((0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?n:s.EMPTY)).subscribe()})}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=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&&s){this._addPendingAction(t);const e=(0,r.timer)(s).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${s}ms`))});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,a.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=m;
73
73
  },{"../utils/create6DigitPin":"UDAB","../utils/stitch":"V73a","../utils/encoding":"jTvL","../types":"iwtf","../constants":"dGLb","../utils/osHasBluetoothSupport":"rH2Y"}],"Oj1i":[function(require,module,exports) {
74
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;
75
75
  },{}],"WTrV":[function(require,module,exports) {