UNPKG

@neurosity/sdk

Version:
406 lines (405 loc) 22.8 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { BLUETOOTH_PRIMARY_SERVICE_UUID_STRING } from "@neurosity/ipk"; import { BLUETOOTH_CHUNK_DELIMITER } from "@neurosity/ipk"; import { BLUETOOTH_DEVICE_NAME_PREFIXES } from "@neurosity/ipk"; import { Observable, BehaviorSubject, ReplaySubject, NEVER } from "rxjs"; import { defer, merge, of, timer, fromEventPattern, identity } from "rxjs"; import { switchMap, map, filter, takeUntil, tap } from "rxjs/operators"; import { shareReplay, distinctUntilChanged, finalize } from "rxjs/operators"; import { take, share, scan, distinct } from "rxjs/operators"; import { create6DigitPin } from "../utils/create6DigitPin"; import { TextCodec } from "../utils/textCodec"; import { TRANSPORT_TYPE, BLUETOOTH_CONNECTION } from "../types"; import { DEFAULT_ACTION_RESPONSE_TIMEOUT } from "../constants"; import { CHARACTERISTIC_UUIDS_TO_NAMES } from "../constants"; import { ANDROID_MAX_MTU } from "../constants"; import { REACT_NATIVE_MAX_BYTE_SIZE } from "../constants"; import { decodeJSONChunks } from "../utils/decodeJSONChunks"; const defaultOptions = { autoConnect: true }; export class ReactNativeTransport { constructor(options) { this.type = TRANSPORT_TYPE.REACT_NATIVE; this.textCodec = new TextCodec(this.type); this.characteristicsByName = {}; this.connection$ = new BehaviorSubject(BLUETOOTH_CONNECTION.DISCONNECTED); this.pendingActions$ = new BehaviorSubject([]); this.logs$ = new ReplaySubject(10); this.connectionStream$ = this.connection$ .asObservable() .pipe(filter((connection) => !!connection), distinctUntilChanged(), shareReplay(1)); this._isAutoConnectEnabled$ = new ReplaySubject(1); if (!options) { const errorMessage = "React Native transport: missing options."; this.addLog(errorMessage); throw new Error(errorMessage); } this.options = Object.assign(Object.assign({}, defaultOptions), options); const { BleManager, bleManagerEmitter, platform, autoConnect } = this.options; if (!BleManager) { const errorMessage = "React Native option: BleManager not provided."; this.addLog(errorMessage); throw new Error(errorMessage); } if (!bleManagerEmitter) { const errorMessage = "React Native option: bleManagerEmitter not provided."; this.addLog(errorMessage); throw new Error(errorMessage); } if (!platform) { const errorMessage = "React Native option: platform not provided."; this.addLog(errorMessage); throw new Error(errorMessage); } this.BleManager = BleManager; this.bleManagerEmitter = bleManagerEmitter; this.platform = platform; this._isAutoConnectEnabled$.next(autoConnect); this._isAutoConnectEnabled$.subscribe((autoConnect) => { this.addLog(`Auto connect: ${autoConnect ? "enabled" : "disabled"}`); }); // We create a single listener per event type to // avoid missing events when multiple listeners are attached. 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(share()); // Initializes the module. This can only be called once. this.BleManager.start({ showAlert: false }) .then(() => { this.addLog(`BleManger started`); }) .catch((error) => { var _a; this.addLog(`BleManger failed to start. ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`); }); this.connection$.asObservable().subscribe((connection) => { this.addLog(`connection status is ${connection}`); }); this.onDisconnected$.subscribe(() => { this.connection$.next(BLUETOOTH_CONNECTION.DISCONNECTED); }); } addLog(log) { this.logs$.next(log); } isConnected() { const connection = this.connection$.getValue(); return connection === BLUETOOTH_CONNECTION.CONNECTED; } _autoConnect(selectedDevice$) { const selectedDeviceAfterDisconnect$ = this.onDisconnected$.pipe(switchMap(() => selectedDevice$)); return this._isAutoConnectEnabled$.pipe(switchMap((isAutoConnectEnabled) => isAutoConnectEnabled ? merge(selectedDevice$, selectedDeviceAfterDisconnect$) : NEVER), switchMap((selectedDevice) => this.scan().pipe(switchMap((peripherals) => { const peripheralMatch = peripherals.find((peripheral) => peripheral.name === (selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.deviceNickname)); return peripheralMatch ? of(peripheralMatch) : NEVER; }), distinct((peripheral) => peripheral.id), take(1))), switchMap((peripheral) => __awaiter(this, void 0, void 0, function* () { return yield this.connect(peripheral); }))); } enableAutoConnect(autoConnect) { this._isAutoConnectEnabled$.next(autoConnect); } connection() { return this.connectionStream$; } _fromEvent(eventName) { return fromEventPattern((addHandler) => { this.bleManagerEmitter.addListener(eventName, addHandler); }, () => { this.bleManagerEmitter.removeAllListeners(eventName); }).pipe( // @important: we need to share the subscription // to avoid missing events share()); } scan(options) { var _a, _b, _c; const RESCAN_INTERVAL = 10000; // 10 seconds const seconds = (_a = options === null || options === void 0 ? void 0 : options.seconds) !== null && _a !== void 0 ? _a : RESCAN_INTERVAL / 1000; const once = (_b = options === null || options === void 0 ? void 0 : options.once) !== null && _b !== void 0 ? _b : false; // If we are already connected to a peripheral and start scanning, // be default, it will set the connection status to SCANNING and not // update it back if no device is connected to const skipConnectionUpdate = (_c = options === null || options === void 0 ? void 0 : options.skipConnectionUpdate) !== null && _c !== void 0 ? _c : false; const serviceUUIDs = [BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]; const allowDuplicates = true; const scanOptions = {}; const scanOnce$ = new Observable((subscriber) => { var _a; try { this.BleManager.scan(serviceUUIDs, seconds, allowDuplicates, scanOptions).then(() => { this.addLog(`BleManger scanning ${once ? "once" : "indefintely"}`); subscriber.next(); }); } catch (error) { this.addLog(`BleManger scanning ${once ? "once" : "indefintely"} failed. ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`); subscriber.error(error); } return () => { this.BleManager.stopScan(); }; }); const scan$ = once ? scanOnce$ : timer(0, RESCAN_INTERVAL).pipe(switchMap(() => scanOnce$)); const peripherals$ = scan$.pipe(tap(() => { if (!skipConnectionUpdate) { this.connection$.next(BLUETOOTH_CONNECTION.SCANNING); } }), takeUntil(this.onDisconnected$), switchMap(() => this.bleEvents.discoverPeripheral$), // Filter out devices that are not Neurosity devices filter((peripheral) => { var _a, _b, _c; const peripheralName = (_c = (_b = (_a = peripheral === null || peripheral === void 0 ? void 0 : peripheral.advertising) === null || _a === void 0 ? void 0 : _a.localName) !== null && _b !== void 0 ? _b : peripheral.name) !== null && _c !== void 0 ? _c : ""; if (!peripheralName) { return false; } const startsWithPrefix = BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex((prefix) => peripheralName.startsWith(prefix)) !== -1; return startsWithPrefix; }), scan((acc, peripheral) => { var _a, _b, _c, _d, _e, _f, _g, _h; // normalized peripheral name for backwards compatibility // Neurosity OS v15 doesn't have peripheral.name as deviceNickname // it only has peripheral.advertising.localName as deviceNickname // and OS v16 has both as deviceNickname const peripheralName = (_c = (_b = (_a = peripheral === null || peripheral === void 0 ? void 0 : peripheral.advertising) === null || _a === void 0 ? void 0 : _a.localName) !== null && _b !== void 0 ? _b : peripheral.name) !== null && _c !== void 0 ? _c : ""; const manufactureDataString = (_h = (_g = this.textCodec .decode((_f = (_e = (_d = peripheral === null || peripheral === void 0 ? void 0 : peripheral.advertising) === null || _d === void 0 ? void 0 : _d.manufacturerData) === null || _e === void 0 ? void 0 : _e.bytes) !== null && _f !== void 0 ? _f : [])) === null || _g === void 0 ? void 0 : _g.slice) === null || _h === void 0 ? void 0 : _h.call(_g, 2); // First 2 bytes are reserved for the Neurosity company code return Object.assign(Object.assign({}, acc), { [peripheral.id]: Object.assign(Object.assign({}, peripheral), { name: peripheralName, manufactureDataString }) }); }, {}), distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)), map((peripheralMap) => Object.values(peripheralMap)), share()); return peripherals$; } connect(peripheral) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { try { if (!peripheral) { this.addLog("Peripheral not found"); return; } this.connection$.next(BLUETOOTH_CONNECTION.CONNECTING); yield this.BleManager.connect(peripheral.id); this.addLog(`Getting service...`); const peripheralInfo = yield this.BleManager.retrieveServices(peripheral.id, [ BLUETOOTH_PRIMARY_SERVICE_UUID_STRING ]); if (!peripheralInfo) { this.addLog("Could not retreive services"); reject(new Error(`Could not retreive services`)); return; } this.addLog(`Got service ${BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`); this.device = peripheral; this.characteristicsByName = Object.fromEntries(peripheralInfo.characteristics.map((characteristic) => [ CHARACTERISTIC_UUIDS_TO_NAMES[characteristic.characteristic.toLowerCase() // react native uses uppercase ], { characteristicUUID: characteristic.characteristic, serviceUUID: characteristic.service, peripheralId: peripheral.id } ])); this.addLog(`Got characteristics.`); if (this.platform === "android") { yield this.BleManager.requestMTU(peripheral.id, ANDROID_MAX_MTU) .then((updatedMTU) => { this.addLog(`Successfully updated Android MTU to ${updatedMTU} bytes. Requested MTU: ${ANDROID_MAX_MTU} bytes.`); }) .catch((error) => { this.addLog(`Failed to set Android MTU of ${ANDROID_MAX_MTU} bytes. Error: ${error}`); }); } this.addLog(`Successfully connected to peripheral ${peripheral.id}`); this.connection$.next(BLUETOOTH_CONNECTION.CONNECTED); resolve(); } catch (error) { reject(error); } })); }); } disconnect() { var _a; return __awaiter(this, void 0, void 0, function* () { try { if (this.isConnected() && ((_a = this === null || this === void 0 ? void 0 : this.device) === null || _a === void 0 ? void 0 : _a.id)) { yield this.BleManager.disconnect(this.device.id); } } catch (error) { return Promise.reject(error); } }); } getCharacteristicByName(characteristicName) { var _a; if (!(characteristicName in this.characteristicsByName)) { throw new Error(`Characteristic by name ${characteristicName} is not found`); } return (_a = this.characteristicsByName) === null || _a === void 0 ? void 0 : _a[characteristicName]; } subscribeToCharacteristic({ characteristicName, manageNotifications = true, skipJSONDecoding = false }) { const getData = ({ peripheralId, serviceUUID, characteristicUUID }) => defer(() => __awaiter(this, void 0, void 0, function* () { var _a; if (manageNotifications) { try { yield this.BleManager.startNotification(peripheralId, serviceUUID, characteristicUUID); this.addLog(`Started notifications for ${characteristicName} characteristic`); } catch (error) { this.addLog(`Attemped to stop notifications for ${characteristicName} characteristic: ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`); } } })).pipe(switchMap(() => this.bleEvents.didUpdateValueForCharacteristic$), finalize(() => __awaiter(this, void 0, void 0, function* () { var _b; if (manageNotifications) { try { yield this.BleManager.stopNotification(peripheralId, serviceUUID, characteristicUUID); this.addLog(`Stopped notifications for ${characteristicName} characteristic`); } catch (error) { this.addLog(`Attemped to stop notifications for ${characteristicName} characteristic: ${(_b = error === null || error === void 0 ? void 0 : error.message) !== null && _b !== void 0 ? _b : error}`); } } })), filter(({ characteristic }) => characteristic === characteristicUUID), map(({ value }) => new Uint8Array(value))); return this.connection$.pipe(switchMap((connection) => connection === BLUETOOTH_CONNECTION.CONNECTED ? getData(this.getCharacteristicByName(characteristicName)).pipe(skipJSONDecoding ? identity // noop : decodeJSONChunks({ textCodec: this.textCodec, characteristicName, delimiter: BLUETOOTH_CHUNK_DELIMITER, addLog: (message) => this.addLog(message) })) : NEVER)); } readCharacteristic(characteristicName, parse = false) { var _a; return __awaiter(this, void 0, void 0, function* () { this.addLog(`Reading characteristic: ${characteristicName}`); const { peripheralId, serviceUUID, characteristicUUID } = this.getCharacteristicByName(characteristicName); if (!characteristicUUID) { return Promise.reject(new Error(`Did not find characteristic matching ${characteristicName}`)); } try { const value = yield this.BleManager.read(peripheralId, serviceUUID, characteristicUUID); const decodedValue = this.textCodec.decode(new Uint8Array(value)); const data = parse ? JSON.parse(decodedValue) : decodedValue; this.addLog(`Received read data from ${characteristicName} characteristic: \n${data}`); return data; } catch (error) { return Promise.reject(new Error(`readCharacteristic ${characteristicName} error. ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`)); } }); } writeCharacteristic(characteristicName, data) { return __awaiter(this, void 0, void 0, function* () { this.addLog(`Writing characteristic: ${characteristicName}`); const { peripheralId, serviceUUID, characteristicUUID } = this.getCharacteristicByName(characteristicName); if (!characteristicUUID) { return Promise.reject(new Error(`Did not find characteristic matching ${characteristicName}`)); } const encoded = this.textCodec.encode(data); yield this.BleManager.write(peripheralId, serviceUUID, characteristicUUID, encoded, REACT_NATIVE_MAX_BYTE_SIZE); }); } _addPendingAction(actionId) { const actions = this.pendingActions$.getValue(); this.pendingActions$.next([...actions, actionId]); } _removePendingAction(actionId) { const actions = this.pendingActions$.getValue(); this.pendingActions$.next(actions.filter((id) => id !== actionId)); } _autoToggleActionNotifications() { let started = false; return this.connection$.asObservable().pipe(switchMap((connection) => connection === BLUETOOTH_CONNECTION.CONNECTED ? this.pendingActions$ : NEVER), tap((pendingActions) => __awaiter(this, void 0, void 0, function* () { var _a, _b; const { peripheralId, serviceUUID, characteristicUUID } = this.getCharacteristicByName("actions"); const hasPendingActions = !!pendingActions.length; if (hasPendingActions && !started) { started = true; try { yield this.BleManager.startNotification(peripheralId, serviceUUID, characteristicUUID); this.addLog(`Started notifications for [actions] characteristic`); } catch (error) { this.addLog(`Attemped to start notifications for [actions] characteristic: ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`); } } if (!hasPendingActions && started) { started = false; try { yield this.BleManager.stopNotification(peripheralId, serviceUUID, characteristicUUID); this.addLog(`Stopped notifications for actions characteristic`); } catch (error) { this.addLog(`Attemped to stop notifications for [actions] characteristic: ${(_b = error === null || error === void 0 ? void 0 : error.message) !== null && _b !== void 0 ? _b : error}`); } } }))); } dispatchAction({ characteristicName, action }) { return __awaiter(this, void 0, void 0, function* () { const { responseRequired = false, responseTimeout = DEFAULT_ACTION_RESPONSE_TIMEOUT } = action; return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const actionId = create6DigitPin(); // use to later identify and filter response const payload = JSON.stringify(Object.assign({ actionId }, action)); // add the response id to the action this.addLog(`Dispatched action with id ${actionId}`); if (responseRequired && responseTimeout) { this._addPendingAction(actionId); const timeout = timer(responseTimeout).subscribe(() => { this._removePendingAction(actionId); reject(new Error(`Action with id ${actionId} timed out after ${responseTimeout}ms`)); }); // listen for a response before writing this.subscribeToCharacteristic({ characteristicName, manageNotifications: false }) .pipe(filter((response) => (response === null || response === void 0 ? void 0 : response.actionId) === actionId), take(1)) .subscribe((response) => { timeout.unsubscribe(); this._removePendingAction(actionId); resolve(response); }); // register action by writing this.writeCharacteristic(characteristicName, payload).catch((error) => { this._removePendingAction(actionId); reject(error); }); } else { this.writeCharacteristic(characteristicName, payload) .then(() => { resolve(null); }) .catch((error) => { reject(error); }); } })); }); } }