UNPKG

webbluetooth

Version:

Node.js implementation of the Web Bluetooth Specification

678 lines 31.9 kB
"use strict"; /* * Node Web Bluetooth * Copyright (c) 2025 Rob Moran * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SimplebleAdapter = void 0; var events_1 = require("events"); var uuid_1 = require("../uuid"); var simpleble_1 = require("./simpleble"); /** * @hidden */ var PeripheralHandles = /** @class */ (function () { function PeripheralHandles(peripherals) { this.peripherals = peripherals; this.handleCounter = 0; this.peripheralChildren = new Map(); this.children = new Map(); this.parents = new Map(); this.services = new Map(); this.characteristics = new Map(); this.descriptors = new Map(); this.characteristicEvents = new Map(); } PeripheralHandles.prototype.createHandles = function (peripheral) { var e_1, _a, e_2, _b, e_3, _c; var services = []; try { for (var _d = __values(peripheral.services), _e = _d.next(); !_e.done; _e = _d.next()) { var service = _e.value; var serviceHandle = "".concat(this.handleCounter++); this.parents.set(serviceHandle, peripheral.address); this.services.set(serviceHandle, service); services.push(serviceHandle); var characteristics = []; try { for (var _f = (e_2 = void 0, __values(service.characteristics)), _g = _f.next(); !_g.done; _g = _f.next()) { var characteristic = _g.value; var characteristicHandle = "".concat(this.handleCounter++); this.parents.set(characteristicHandle, serviceHandle); this.characteristics.set(characteristicHandle, characteristic); characteristics.push(characteristicHandle); var descriptors = []; try { for (var _h = (e_3 = void 0, __values(characteristic.descriptors)), _j = _h.next(); !_j.done; _j = _h.next()) { var descriptor = _j.value; var descHandle = "".concat(this.handleCounter++); this.parents.set(descHandle, characteristicHandle); this.descriptors.set(descHandle, descriptor); descriptors.push(descHandle); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_j && !_j.done && (_c = _h.return)) _c.call(_h); } finally { if (e_3) throw e_3.error; } } this.children.set(characteristicHandle, descriptors); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_g && !_g.done && (_b = _f.return)) _b.call(_f); } finally { if (e_2) throw e_2.error; } } this.children.set(serviceHandle, characteristics); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_e && !_e.done && (_a = _d.return)) _a.call(_d); } finally { if (e_1) throw e_1.error; } } this.children.set(peripheral.address, services); }; PeripheralHandles.prototype.deleteHandles = function (peripheral) { var e_4, _a; var children = this.peripheralChildren.get(peripheral); try { for (var children_1 = __values(children), children_1_1 = children_1.next(); !children_1_1.done; children_1_1 = children_1.next()) { var child = children_1_1.value; this.children.delete(child); this.parents.delete(child); this.services.delete(child); this.characteristics.delete(child); this.descriptors.delete(child); this.characteristicEvents.delete(child); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (children_1_1 && !children_1_1.done && (_a = children_1.return)) _a.call(children_1); } finally { if (e_4) throw e_4.error; } } this.peripheralChildren.delete(peripheral); }; PeripheralHandles.prototype.getServices = function (deviceHandle) { var e_5, _a; var children = this.children.get(deviceHandle); var services = {}; try { for (var children_2 = __values(children), children_2_1 = children_2.next(); !children_2_1.done; children_2_1 = children_2.next()) { var child = children_2_1.value; services[child] = this.services.get(child); } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (children_2_1 && !children_2_1.done && (_a = children_2.return)) _a.call(children_2); } finally { if (e_5) throw e_5.error; } } return services; }; PeripheralHandles.prototype.getCharacteristics = function (serviceHandle) { var e_6, _a; var children = this.children.get(serviceHandle); var characteristics = {}; try { for (var children_3 = __values(children), children_3_1 = children_3.next(); !children_3_1.done; children_3_1 = children_3.next()) { var child = children_3_1.value; characteristics[child] = this.characteristics.get(child); } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (children_3_1 && !children_3_1.done && (_a = children_3.return)) _a.call(children_3); } finally { if (e_6) throw e_6.error; } } var peripheralHandle = this.parents.get(serviceHandle); return { peripheral: this.peripherals.get(peripheralHandle), service: this.services.get(serviceHandle), characteristics: characteristics }; }; PeripheralHandles.prototype.getDescriptors = function (characteristicHandle) { var e_7, _a; var children = this.children.get(characteristicHandle); var descriptors = {}; try { for (var children_4 = __values(children), children_4_1 = children_4.next(); !children_4_1.done; children_4_1 = children_4.next()) { var child = children_4_1.value; descriptors[child] = this.descriptors.get(child); } } catch (e_7_1) { e_7 = { error: e_7_1 }; } finally { try { if (children_4_1 && !children_4_1.done && (_a = children_4.return)) _a.call(children_4); } finally { if (e_7) throw e_7.error; } } return descriptors; }; PeripheralHandles.prototype.getCharacteristicGraph = function (characteristicHandle) { var serviceHandle = this.parents.get(characteristicHandle); var peripheralHandle = this.parents.get(serviceHandle); return { peripheral: this.peripherals.get(peripheralHandle), service: this.services.get(serviceHandle), characteristic: this.characteristics.get(characteristicHandle) }; }; PeripheralHandles.prototype.getDescriptorGraph = function (descriptorHandle) { var characteristicHandle = this.parents.get(descriptorHandle); var serviceHandle = this.parents.get(characteristicHandle); var peripheralHandle = this.parents.get(serviceHandle); return { peripheral: this.peripherals.get(peripheralHandle), service: this.services.get(serviceHandle), characteristic: this.characteristics.get(characteristicHandle), descriptor: this.descriptors.get(descriptorHandle) }; }; return PeripheralHandles; }()); /** * @hidden */ var SimplebleAdapter = /** @class */ (function (_super) { __extends(SimplebleAdapter, _super); function SimplebleAdapter() { var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this; _this.peripherals = new Map(); _this.handles = new PeripheralHandles(_this.peripherals); return _this; } SimplebleAdapter.prototype.validDevice = function (device, serviceUUIDs) { if (serviceUUIDs.length === 0) { // Match any device return true; } if (!device._serviceUUIDs) { // No advertised services, no match return false; } var advertisedUUIDs = device._serviceUUIDs.map(function (serviceUUID) { return uuid_1.BluetoothUUID.canonicalUUID(serviceUUID); }); // An advertised UUID matches our search UUIDs return serviceUUIDs.some(function (serviceUUID) { return advertisedUUIDs.indexOf(serviceUUID) >= 0; }); }; SimplebleAdapter.prototype.buildBluetoothDevice = function (device) { var e_8, _a; var name = device.identifier; var address = device.address; var rssi = device.rssi; var txPower = device.txPower; var mtu = device.mtu; var id = address || "".concat(name); var serviceUUIDs = []; var serviceData = new Map(); try { for (var _b = __values(device.services), _c = _b.next(); !_c.done; _c = _b.next()) { var service = _c.value; serviceUUIDs.push(service.uuid); if (service.data) { serviceData.set(service.uuid, service.data); } } } catch (e_8_1) { e_8 = { error: e_8_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_8) throw e_8.error; } } var manufacturerData = new Map(); for (var id_1 in device.manufacturerData) { manufacturerData.set(id_1, new DataView(device.manufacturerData[id_1].buffer)); } return { id: id, name: name, _serviceUUIDs: serviceUUIDs, _adData: { rssi: rssi, txPower: txPower, mtu: mtu, serviceData: serviceData, manufacturerData: manufacturerData } }; }; Object.defineProperty(SimplebleAdapter.prototype, "state", { get: function () { var adapterEnabled = (0, simpleble_1.isEnabled)(); return !!adapterEnabled; }, enumerable: false, configurable: true }); SimplebleAdapter.prototype.getEnabled = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.state]; }); }); }; SimplebleAdapter.prototype.getAdapters = function () { var adapters = (0, simpleble_1.getAdapters)(); return adapters.map(function (_a, index) { var address = _a.address, active = _a.active; return ({ index: index, address: address, active: active }); }); }; SimplebleAdapter.prototype.useAdapter = function (index) { var adapters = (0, simpleble_1.getAdapters)(); var selected = adapters[index]; if (!selected) { throw new Error("Adapter ".concat(index, " not found.")); } this.adapter = selected; }; SimplebleAdapter.prototype.startScan = function (serviceUUIDs, foundFn) { return __awaiter(this, void 0, void 0, function () { var foundPeripherals, success; var _this = this; return __generator(this, function (_a) { if (this.state === false) { throw new Error('adapter not enabled'); } if (!this.adapter) { this.adapter = (0, simpleble_1.getAdapters)()[0]; } foundPeripherals = []; this.adapter.setCallbackOnScanFound(function (peripheral) { var device = _this.buildBluetoothDevice(peripheral); if (_this.validDevice(device, serviceUUIDs)) { if (!foundPeripherals.includes(device.id)) { foundPeripherals.push(device.id); _this.peripherals.set(device.id, peripheral); // Only call the found function the first time we find a valid device foundFn(device); } } }); success = this.adapter.scanStart(); if (!success) { throw new Error('scan start failed'); } return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.stopScan = function (_errorFn) { if (this.adapter) { var success = this.adapter.scanStop(); if (!success) { throw new Error('scan stop failed'); } } }; SimplebleAdapter.prototype.connect = function (handle, disconnectFn) { return __awaiter(this, void 0, void 0, function () { var peripheral, success; return __generator(this, function (_a) { peripheral = this.peripherals.get(handle); if (!peripheral) { throw new Error('Peripheral not found'); } if (!peripheral.connectable) { throw new Error('Connection not possible'); } success = peripheral.connect(); if (!success) { throw new Error('Connect failed'); } if (disconnectFn) { peripheral.setCallbackOnDisconnected(function () { return disconnectFn(); }); } this.handles.createHandles(peripheral); return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.disconnect = function (handle) { return __awaiter(this, void 0, void 0, function () { var peripheral, success; return __generator(this, function (_a) { peripheral = this.peripherals.get(handle); if (!peripheral) { throw new Error('Peripheral not found'); } success = peripheral.disconnect(); if (!success) { throw new Error('Disconnect failed'); } this.handles.deleteHandles(peripheral); return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.discoverServices = function (handle, serviceUUIDs) { return __awaiter(this, void 0, void 0, function () { var services, discovered, _a, _b, _c, handle_1, service; var e_9, _d; return __generator(this, function (_e) { services = this.handles.getServices(handle); discovered = []; try { for (_a = __values(Object.entries(services)), _b = _a.next(); !_b.done; _b = _a.next()) { _c = __read(_b.value, 2), handle_1 = _c[0], service = _c[1]; if (!serviceUUIDs || serviceUUIDs.length === 0 || serviceUUIDs.indexOf(service.uuid) >= 0) { discovered.push({ _handle: handle_1, uuid: service.uuid, isPrimary: true }); } } } catch (e_9_1) { e_9 = { error: e_9_1 }; } finally { try { if (_b && !_b.done && (_d = _a.return)) _d.call(_a); } finally { if (e_9) throw e_9.error; } } return [2 /*return*/, discovered]; }); }); }; SimplebleAdapter.prototype.discoverIncludedServices = function (_handle, _serviceUUIDs) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { // Currently not implemented return [2 /*return*/, []]; }); }); }; SimplebleAdapter.prototype.discoverCharacteristics = function (handle, characteristicUUIDs) { return __awaiter(this, void 0, void 0, function () { var _a, peripheral, service, characteristics, discovered, _loop_1, _b, _c, _d, handle_2, characteristic; var e_10, _e; var _this = this; return __generator(this, function (_f) { _a = this.handles.getCharacteristics(handle), peripheral = _a.peripheral, service = _a.service, characteristics = _a.characteristics; discovered = []; _loop_1 = function (handle_2, characteristic) { var charUUID = uuid_1.BluetoothUUID.canonicalUUID(characteristic.uuid); if (!characteristicUUIDs || characteristicUUIDs.length === 0 || characteristicUUIDs.indexOf(charUUID) >= 0) { discovered.push({ _handle: handle_2, uuid: charUUID, properties: { // Not all of these are supported in SimpleBle broadcast: false, // characteristic.capabilities.includes('???'), read: characteristic.canRead, writeWithoutResponse: characteristic.canWriteRequest, write: characteristic.canWriteCommand, notify: characteristic.canNotify, indicate: characteristic.canIndicate, authenticatedSignedWrites: false, // characteristic.capabilities.includes('???'), reliableWrite: false, // characteristic.capabilities.includes('???'), writableAuxiliaries: false // characteristic.capabilities.includes('???'), } }); if (characteristic.canIndicate) { peripheral.indicate(service.uuid, charUUID, function (data) { if (_this.handles.characteristicEvents.has(handle_2)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion _this.handles.characteristicEvents.get(handle_2)(new DataView(data.buffer)); } }); } if (characteristic.canNotify) { peripheral.notify(service.uuid, charUUID, function (data) { if (_this.handles.characteristicEvents.has(handle_2)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion _this.handles.characteristicEvents.get(handle_2)(new DataView(data.buffer)); } }); } } }; try { for (_b = __values(Object.entries(characteristics)), _c = _b.next(); !_c.done; _c = _b.next()) { _d = __read(_c.value, 2), handle_2 = _d[0], characteristic = _d[1]; _loop_1(handle_2, characteristic); } } catch (e_10_1) { e_10 = { error: e_10_1 }; } finally { try { if (_c && !_c.done && (_e = _b.return)) _e.call(_b); } finally { if (e_10) throw e_10.error; } } return [2 /*return*/, discovered]; }); }); }; SimplebleAdapter.prototype.discoverDescriptors = function (handle, descriptorUUIDs) { return __awaiter(this, void 0, void 0, function () { var descriptors, discovered, _a, _b, _c, handle_3, descriptor, descUUID; var e_11, _d; return __generator(this, function (_e) { descriptors = this.handles.getDescriptors(handle); discovered = []; try { for (_a = __values(Object.entries(descriptors)), _b = _a.next(); !_b.done; _b = _a.next()) { _c = __read(_b.value, 2), handle_3 = _c[0], descriptor = _c[1]; descUUID = uuid_1.BluetoothUUID.canonicalUUID(descriptor); if (!descriptorUUIDs || descriptorUUIDs.length === 0 || descriptorUUIDs.indexOf(descUUID) >= 0) { discovered.push({ _handle: handle_3, uuid: descUUID }); } } } catch (e_11_1) { e_11 = { error: e_11_1 }; } finally { try { if (_b && !_b.done && (_d = _a.return)) _d.call(_a); } finally { if (e_11) throw e_11.error; } } return [2 /*return*/, discovered]; }); }); }; SimplebleAdapter.prototype.readCharacteristic = function (handle) { return __awaiter(this, void 0, void 0, function () { var _a, peripheral, service, characteristic, data; return __generator(this, function (_b) { _a = this.handles.getCharacteristicGraph(handle), peripheral = _a.peripheral, service = _a.service, characteristic = _a.characteristic; data = peripheral.read(service.uuid, characteristic.uuid); return [2 /*return*/, new DataView(data.buffer)]; }); }); }; SimplebleAdapter.prototype.writeCharacteristic = function (handle_4, value_1) { return __awaiter(this, arguments, void 0, function (handle, value, withoutResponse) { var _a, peripheral, service, characteristic, success; if (withoutResponse === void 0) { withoutResponse = false; } return __generator(this, function (_b) { _a = this.handles.getCharacteristicGraph(handle), peripheral = _a.peripheral, service = _a.service, characteristic = _a.characteristic; success = false; if (withoutResponse) { success = peripheral.writeCommand(service.uuid, characteristic.uuid, new Uint8Array(value.buffer)); } else { success = peripheral.writeRequest(service.uuid, characteristic.uuid, new Uint8Array(value.buffer)); } if (!success) { throw new Error('Write failed'); } return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.enableNotify = function (handle, notifyFn) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.handles.characteristicEvents.set(handle, notifyFn); return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.disableNotify = function (handle) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.handles.characteristicEvents.delete(handle); return [2 /*return*/]; }); }); }; SimplebleAdapter.prototype.readDescriptor = function (handle) { return __awaiter(this, void 0, void 0, function () { var _a, peripheral, service, characteristic, descriptor, data; return __generator(this, function (_b) { _a = this.handles.getDescriptorGraph(handle), peripheral = _a.peripheral, service = _a.service, characteristic = _a.characteristic, descriptor = _a.descriptor; data = peripheral.readDescriptor(service.uuid, characteristic.uuid, descriptor); if (!data) { throw new Error('Read failed'); } return [2 /*return*/, new DataView(data.buffer)]; }); }); }; SimplebleAdapter.prototype.writeDescriptor = function (handle, value) { return __awaiter(this, void 0, void 0, function () { var _a, peripheral, service, characteristic, descriptor, success; return __generator(this, function (_b) { _a = this.handles.getDescriptorGraph(handle), peripheral = _a.peripheral, service = _a.service, characteristic = _a.characteristic, descriptor = _a.descriptor; success = peripheral.writeDescriptor(service.uuid, characteristic.uuid, descriptor, new Uint8Array(value.buffer)); if (!success) { throw new Error('Write failed'); } return [2 /*return*/]; }); }); }; return SimplebleAdapter; }(events_1.EventEmitter)); exports.SimplebleAdapter = SimplebleAdapter; //# sourceMappingURL=simpleble-adapter.js.map