@neurosity/sdk
Version:
Neurosity SDK
406 lines (405 loc) • 19.8 kB
JavaScript
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_HEX } from "@neurosity/ipk";
import { BLUETOOTH_CHUNK_DELIMITER } from "@neurosity/ipk";
import { BLUETOOTH_DEVICE_NAME_PREFIXES } from "@neurosity/ipk";
import { BLUETOOTH_COMPANY_IDENTIFIER_HEX } from "@neurosity/ipk";
import { Observable, BehaviorSubject, ReplaySubject, identity } from "rxjs";
import { defer, merge, timer, fromEventPattern, NEVER } from "rxjs";
import { switchMap, map, filter, tap } from "rxjs/operators";
import { shareReplay, distinctUntilChanged } from "rxjs/operators";
import { take, share } from "rxjs/operators";
import { isWebBluetoothSupported } from "./isWebBluetoothSupported";
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 { decodeJSONChunks } from "../utils/decodeJSONChunks";
const defaultOptions = {
autoConnect: true
};
export class WebBluetoothTransport {
constructor(options = {}) {
this.type = TRANSPORT_TYPE.WEB;
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.onDisconnected$ = this._onDisconnected().pipe(share());
this.connectionStream$ = this.connection$
.asObservable()
.pipe(filter((connection) => !!connection), distinctUntilChanged(), shareReplay(1));
this._isAutoConnectEnabled$ = new ReplaySubject(1);
this.options = Object.assign(Object.assign({}, defaultOptions), options);
if (!isWebBluetoothSupported()) {
const errorMessage = "Web Bluetooth is not supported";
this.addLog(errorMessage);
throw new Error(errorMessage);
}
this._isAutoConnectEnabled$.subscribe((autoConnect) => {
this.addLog(`Auto connect: ${autoConnect ? "enabled" : "disabled"}`);
});
this._isAutoConnectEnabled$.next(this.options.autoConnect);
this.connection$.asObservable().subscribe((connection) => {
this.addLog(`connection status is ${connection}`);
});
this.onDisconnected$.subscribe(() => {
this.connection$.next(BLUETOOTH_CONNECTION.DISCONNECTED);
});
}
_getPairedDevices() {
return __awaiter(this, void 0, void 0, function* () {
return yield navigator.bluetooth.getDevices();
});
}
_autoConnect(selectedDevice$) {
return this._isAutoConnectEnabled$.pipe(switchMap((isAutoConnectEnabled) => isAutoConnectEnabled
? merge(selectedDevice$, this.onDisconnected$.pipe(switchMap(() => selectedDevice$)))
: NEVER), switchMap((selectedDevice) => __awaiter(this, void 0, void 0, function* () {
var _a;
const { deviceNickname } = selectedDevice;
if (this.isConnected()) {
this.addLog(`Auto connect: ${deviceNickname} is already connected. Skipping auto connect.`);
return;
}
const [devicesError, devices] = yield this._getPairedDevices()
.then((devices) => [null, devices])
.catch((error) => [error, null]);
if (devicesError) {
throw new Error(`failed to get devices: ${(_a = devicesError === null || devicesError === void 0 ? void 0 : devicesError.message) !== null && _a !== void 0 ? _a : devicesError}`);
}
this.addLog(`Auto connect: found ${devices.length} devices ${devices
.map(({ name }) => name)
.join(", ")}`);
// @important - Using `findLast` instead of `find` because somehow the browser
// is finding multiple peripherals with the same name
const device = devices.findLast((device) => device.name === deviceNickname);
if (!device) {
throw new Error(`couldn't find selected device in the list of paired devices.`);
}
this.addLog(`Auto connect: ${deviceNickname} was detected and previously paired`);
return device;
})), tap(() => {
this.connection$.next(BLUETOOTH_CONNECTION.SCANNING);
}), switchMap((device) => onAdvertisementReceived(device)), switchMap((advertisement) => __awaiter(this, void 0, void 0, function* () {
this.addLog(`Advertisement received for ${advertisement.device.name}`);
return yield this.getServerServiceAndCharacteristics(advertisement.device);
})));
}
enableAutoConnect(autoConnect) {
this._isAutoConnectEnabled$.next(autoConnect);
}
addLog(log) {
this.logs$.next(log);
}
isConnected() {
const connection = this.connection$.getValue();
return connection === BLUETOOTH_CONNECTION.CONNECTED;
}
connection() {
return this.connectionStream$;
}
connect(deviceNickname) {
return __awaiter(this, void 0, void 0, function* () {
try {
// requires user gesture
const device = yield this.requestDevice(deviceNickname);
yield this.getServerServiceAndCharacteristics(device);
}
catch (error) {
return Promise.reject(error);
}
});
}
requestDevice(deviceNickname) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.addLog("Requesting Bluetooth Device...");
const prefixes = BLUETOOTH_DEVICE_NAME_PREFIXES.map((namePrefix) => ({
namePrefix
}));
// Ability to only show selectedDevice if provided
const filters = deviceNickname
? [
{
name: deviceNickname
}
]
: prefixes;
const device = yield window.navigator.bluetooth.requestDevice({
filters: [
...filters,
{
manufacturerData: [
{
companyIdentifier: BLUETOOTH_COMPANY_IDENTIFIER_HEX
}
]
}
],
optionalServices: [BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]
});
return device;
}
catch (error) {
return Promise.reject(error);
}
});
}
getServerServiceAndCharacteristics(device) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.device = device;
const isConnecting = this.connection$.getValue() === BLUETOOTH_CONNECTION.CONNECTING;
if (!isConnecting) {
this.connection$.next(BLUETOOTH_CONNECTION.CONNECTING);
}
this.server = yield device.gatt.connect();
this.addLog(`Getting service...`);
this.service = yield this.server.getPrimaryService(BLUETOOTH_PRIMARY_SERVICE_UUID_HEX);
this.addLog(`Got service ${this.service.uuid}, getting characteristics...`);
const characteristicsList = yield this.service.getCharacteristics();
this.addLog(`Got characteristics`);
this.characteristicsByName = Object.fromEntries(characteristicsList.map((characteristic) => [
CHARACTERISTIC_UUIDS_TO_NAMES[characteristic.uuid],
characteristic
]));
this.connection$.next(BLUETOOTH_CONNECTION.CONNECTED);
}
catch (error) {
return Promise.reject(error);
}
});
}
_onDisconnected() {
return this.connection$
.asObservable()
.pipe(switchMap((connection) => connection === BLUETOOTH_CONNECTION.CONNECTED
? fromDOMEvent(this.device, "gattserverdisconnected")
: NEVER));
}
disconnect() {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
const isDeviceConnected = (_b = (_a = this === null || this === void 0 ? void 0 : this.device) === null || _a === void 0 ? void 0 : _a.gatt) === null || _b === void 0 ? void 0 : _b.connected;
if (isDeviceConnected) {
this.device.gatt.disconnect();
}
});
}
/**
*
* Bluetooth GATT attributes, services, characteristics, etc. are invalidated
* when a device disconnects. This means your code should always retrieve
* (through getPrimaryService(s), getCharacteristic(s), etc.) these attributes
* after reconnecting.
*/
getCharacteristicByName(characteristicName) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
return (_a = this.characteristicsByName) === null || _a === void 0 ? void 0 : _a[characteristicName];
});
}
subscribeToCharacteristic({ characteristicName, manageNotifications = true, skipJSONDecoding = false }) {
const data$ = defer(() => this.getCharacteristicByName(characteristicName)).pipe(switchMap((characteristic) => __awaiter(this, void 0, void 0, function* () {
var _a;
if (this.isConnected() && manageNotifications) {
try {
yield characteristic.startNotifications();
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}`);
}
}
return characteristic;
})), switchMap((characteristic) => {
return fromDOMEvent(characteristic, "characteristicvaluechanged", () => __awaiter(this, void 0, void 0, function* () {
var _a;
if (this.isConnected() && manageNotifications) {
try {
yield characteristic.stopNotifications();
this.addLog(`Stopped 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}`);
}
}
}));
}), map((event) => event.target.value.buffer));
return this.connection$.pipe(switchMap((connection) => connection === BLUETOOTH_CONNECTION.CONNECTED
? data$.pipe(skipJSONDecoding
? identity // noop
: decodeJSONChunks({
textCodec: this.textCodec,
characteristicName,
delimiter: BLUETOOTH_CHUNK_DELIMITER,
addLog: (message) => this.addLog(message)
}))
: NEVER));
}
readCharacteristic(characteristicName, parse = false) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.addLog(`Reading characteristic: ${characteristicName}`);
const characteristic = yield this.getCharacteristicByName(characteristicName);
if (!characteristic) {
this.addLog(`Did not fund ${characteristicName} characteristic`);
return Promise.reject(`Did not find characteristic by the name: ${characteristicName}`);
}
const dataview = yield characteristic.readValue();
const arrayBuffer = dataview.buffer;
const decodedValue = this.textCodec.decode(arrayBuffer);
const data = parse ? JSON.parse(decodedValue) : decodedValue;
this.addLog(`Received read data from ${characteristicName} characteristic: \n${data}`);
return data;
}
catch (error) {
return Promise.reject(`Error reading characteristic: ${error.message}`);
}
});
}
writeCharacteristic(characteristicName, data) {
return __awaiter(this, void 0, void 0, function* () {
this.addLog(`Writing characteristic: ${characteristicName}`);
const characteristic = yield this.getCharacteristicByName(characteristicName);
if (!characteristic) {
this.addLog(`Did not fund ${characteristicName} characteristic`);
return Promise.reject(`Did not find characteristic by the name: ${characteristicName}`);
}
const encoded = this.textCodec.encode(data);
yield characteristic.writeValueWithResponse(encoded);
});
}
_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 actionsCharacteristic;
let started = false;
return this.connection$.asObservable().pipe(switchMap((connection) => connection === BLUETOOTH_CONNECTION.CONNECTED
? defer(() => this.getCharacteristicByName("actions")).pipe(switchMap((characteristic) => {
actionsCharacteristic = characteristic;
return this.pendingActions$;
}))
: NEVER), tap((pendingActions) => __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const hasPendingActions = !!pendingActions.length;
if (hasPendingActions && !started) {
started = true;
try {
yield actionsCharacteristic.startNotifications();
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 actionsCharacteristic.stopNotifications();
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 characteristic = yield this.getCharacteristicByName(characteristicName).catch(() => {
reject(`Did not find characteristic by the name: ${characteristicName}`);
});
if (!characteristic) {
return;
}
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(`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.message);
});
}
else {
this.writeCharacteristic(characteristicName, payload)
.then(() => {
resolve(null);
})
.catch((error) => {
reject(error.message);
});
}
}));
});
}
}
function fromDOMEvent(target, eventName, beforeRemove) {
return fromEventPattern((addHandler) => {
target.addEventListener(eventName, addHandler);
}, (removeHandler) => __awaiter(this, void 0, void 0, function* () {
if (beforeRemove) {
yield beforeRemove();
}
target.removeEventListener(eventName, removeHandler);
}));
}
function onAdvertisementReceived(device) {
return new Observable((subscriber) => {
const abortController = new AbortController();
const { signal } = abortController;
const listener = device.addEventListener("advertisementreceived", (advertisement) => {
abortController.abort();
subscriber.next(advertisement);
subscriber.complete();
}, {
once: true
});
try {
device.watchAdvertisements({ signal });
}
catch (error) {
subscriber.error(error);
}
return () => {
abortController.abort();
device.removeEventListener("advertisementreceived", listener);
};
});
}