mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 02:49:31 +08:00
644 lines
24 KiB
TypeScript
644 lines
24 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Web Bluetooth (navigator.bluetooth: Chromium-based browsers, in a secure
|
|
// context) as a GattCentral (js/core/bluetooth-gatt.ts), for the guest's
|
|
// emulated LE controller (VirtualLeController, js/core/bluetooth-le.ts).
|
|
//
|
|
// const central = new WebBluetoothCentral();
|
|
// await central.init(); // the devices allowed before, where getDevices() exists
|
|
// await vm.bluetooth.attach(new VirtualLeController({ central }));
|
|
// await central.requestDevice(); // in a click handler: the browser's chooser
|
|
//
|
|
// The devices are the ones the user picked in the chooser (requestDevice()
|
|
// with acceptAllDevices) and, where the browser has getDevices() (behind a
|
|
// flag in Chrome in places), the ones allowed before. Web Bluetooth gives a
|
|
// page only the GATT services named at the request: the SIG's standard
|
|
// services (WEB_BLUETOOTH_SERVICES: 0x1800 to 0x185f, and a few vendor ones
|
|
// common on hobby boards) minus Chrome's blocklist, plus the caller's own.
|
|
// While the guest scans, each known device's advertisements are watched
|
|
// (watchAdvertisements(), also behind a flag in places), which adds RSSI,
|
|
// TX power and the advertised data; without it the controller reports the
|
|
// known devices from what it has.
|
|
//
|
|
// The objects stay on the thread that got them (a BluetoothDevice cannot be
|
|
// posted), so in worker mode the kernel reaches them through BluetoothHost
|
|
// on this thread. A connection keeps the discovered services,
|
|
// characteristics and descriptors in discover()'s order, which GattPath
|
|
// indexes. Every failure out of a connection is a GattError, its kind from
|
|
// the DOMException's name and Chrome's message (gattErrorFromDom()).
|
|
|
|
import { GATT_PROP_BROADCAST, GATT_PROP_EXTENDED, GATT_PROP_INDICATE, GATT_PROP_NOTIFY, GATT_PROP_READ, GATT_PROP_SIGNED_WRITE, GATT_PROP_WRITE, GATT_PROP_WRITE_NO_RESPONSE, GattError, canonicalUuid } from "../core/bluetooth-gatt.ts";
|
|
import type { GattCentral, GattConnection, GattDeviceInfo, GattPath, GattServiceInfo } from "../core/bluetooth-gatt.ts";
|
|
|
|
// The parts of Web Bluetooth this uses (TypeScript's DOM library has no Web Bluetooth).
|
|
|
|
/** BluetoothCharacteristicProperties. */
|
|
export interface WebBluetoothProperties {
|
|
readonly broadcast: boolean;
|
|
readonly read: boolean;
|
|
readonly writeWithoutResponse: boolean;
|
|
readonly write: boolean;
|
|
readonly notify: boolean;
|
|
readonly indicate: boolean;
|
|
readonly authenticatedSignedWrites: boolean;
|
|
readonly reliableWrite: boolean;
|
|
readonly writableAuxiliaries: boolean;
|
|
}
|
|
|
|
/** BluetoothRemoteGATTDescriptor. */
|
|
export interface WebBluetoothDescriptor {
|
|
readonly uuid: string;
|
|
readValue(): Promise<DataView>;
|
|
writeValue(value: BufferSource): Promise<void>;
|
|
}
|
|
|
|
/** BluetoothRemoteGATTCharacteristic. */
|
|
export interface WebBluetoothCharacteristic extends EventTarget {
|
|
readonly uuid: string;
|
|
readonly properties: WebBluetoothProperties;
|
|
readonly value?: DataView | null;
|
|
getDescriptors(): Promise<WebBluetoothDescriptor[]>;
|
|
readValue(): Promise<DataView>;
|
|
writeValue?(value: BufferSource): Promise<void>;
|
|
writeValueWithResponse?(value: BufferSource): Promise<void>;
|
|
writeValueWithoutResponse?(value: BufferSource): Promise<void>;
|
|
startNotifications(): Promise<WebBluetoothCharacteristic>;
|
|
stopNotifications(): Promise<WebBluetoothCharacteristic>;
|
|
}
|
|
|
|
/** BluetoothRemoteGATTService. */
|
|
export interface WebBluetoothService {
|
|
readonly uuid: string;
|
|
readonly isPrimary: boolean;
|
|
getCharacteristics(): Promise<WebBluetoothCharacteristic[]>;
|
|
getIncludedServices?(): Promise<WebBluetoothService[]>;
|
|
}
|
|
|
|
/** BluetoothRemoteGATTServer. */
|
|
export interface WebBluetoothServer {
|
|
readonly connected: boolean;
|
|
connect(): Promise<WebBluetoothServer>;
|
|
disconnect(): void;
|
|
getPrimaryServices(): Promise<WebBluetoothService[]>;
|
|
}
|
|
|
|
/** BluetoothDevice. */
|
|
export interface WebBluetoothDevice extends EventTarget {
|
|
readonly id: string;
|
|
readonly name?: string | null;
|
|
readonly gatt?: WebBluetoothServer | null;
|
|
watchAdvertisements?(options?: { signal?: AbortSignal }): Promise<void>;
|
|
readonly watchingAdvertisements?: boolean;
|
|
forget?(): Promise<void>;
|
|
}
|
|
|
|
/** BluetoothAdvertisingEvent ("advertisementreceived"). */
|
|
export interface WebBluetoothAdvertisingEvent extends Event {
|
|
readonly device: WebBluetoothDevice;
|
|
readonly uuids: ReadonlyArray<string>;
|
|
readonly name?: string | null;
|
|
readonly rssi?: number | null;
|
|
readonly txPower?: number | null;
|
|
readonly manufacturerData?: ReadonlyMap<number, DataView>;
|
|
readonly serviceData?: ReadonlyMap<string, DataView>;
|
|
}
|
|
|
|
/** navigator.bluetooth. */
|
|
export interface WebBluetooth extends EventTarget {
|
|
requestDevice(options: { acceptAllDevices?: boolean; filters?: unknown[]; optionalServices?: Array<string | number>; optionalManufacturerData?: number[] }): Promise<WebBluetoothDevice>;
|
|
getAvailability?(): Promise<boolean>;
|
|
getDevices?(): Promise<WebBluetoothDevice[]>;
|
|
}
|
|
|
|
/** navigator.bluetooth where there is one. */
|
|
export function webBluetooth(): WebBluetooth | undefined {
|
|
const nav = (globalThis as { navigator?: { bluetooth?: WebBluetooth } }).navigator;
|
|
return nav?.bluetooth ?? undefined;
|
|
}
|
|
|
|
/**
|
|
* Why Web Bluetooth cannot be used here, or undefined: not a secure context
|
|
* (https or localhost), no navigator.bluetooth (Firefox, Safari), or a
|
|
* permissions policy that blocks `bluetooth`. Whether the computer has an
|
|
* adapter is webBluetoothAvailable()'s (asynchronous).
|
|
*/
|
|
export function webBluetoothBlocker(): string | undefined {
|
|
const g = globalThis as { isSecureContext?: boolean; document?: { featurePolicy?: { allowsFeature(f: string): boolean }; permissionsPolicy?: { allowsFeature(f: string): boolean } } };
|
|
if (g.isSecureContext === false) return "Web Bluetooth needs a secure context (https, or http://localhost)";
|
|
if (!webBluetooth()) return "this browser has no Web Bluetooth (Chrome, Edge and other Chromium-based browsers have it)";
|
|
const policy = g.document?.permissionsPolicy ?? g.document?.featurePolicy;
|
|
try {
|
|
if (policy && !policy.allowsFeature("bluetooth")) return "the page's permissions policy does not allow bluetooth";
|
|
} catch {}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* navigator.bluetooth.getAvailability(): false where the browser sees no
|
|
* Bluetooth adapter (none, or one it cannot use); true where it does or
|
|
* cannot say.
|
|
*/
|
|
export async function webBluetoothAvailable(): Promise<boolean> {
|
|
const b = webBluetooth();
|
|
if (!b) return false;
|
|
try {
|
|
return b.getAvailability ? await b.getAvailability() : true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Chrome's blocklisted GATT services (WebBluetoothCG/registries,
|
|
* gatt_blocklist.txt, as of 2026-06: HID, FIDO, firmware updaters that do
|
|
* not check signatures). A page cannot reach them; requestDevice() drops
|
|
* them from optionalServices.
|
|
*/
|
|
export const WEB_BLUETOOTH_BLOCKLIST: ReadonlySet<string> = new Set([
|
|
canonicalUuid(0x1812), // Human Interface Device
|
|
canonicalUuid(0xfffd), // FIDO
|
|
canonicalUuid(0xfe59), // Nordic Secure DFU
|
|
"00001530-1212-efde-1523-785feabcd123", // Nordic legacy DFU
|
|
"f000ffc0-0451-4000-b000-000000000000", // TI OAD
|
|
"00060000-f8ce-11e4-abf4-0002a5d5c51b", // Cypress bootloader
|
|
]);
|
|
|
|
/**
|
|
* The services requestDevice() asks for by default: every 16-bit UUID from
|
|
* 0x1800 to 0x185f (the SIG's GATT services, assigned up to 0x185c as of
|
|
* 2026-06; an unassigned one costs nothing), plus vendor services common
|
|
* on hobby boards (Nordic UART, the HM-10 and similar modules' 0xffe0 and
|
|
* 0xfff0), minus the blocklist.
|
|
*/
|
|
export const WEB_BLUETOOTH_SERVICES: ReadonlyArray<string> = [
|
|
...Array.from({ length: 0x60 }, (_, i) => canonicalUuid(0x1800 + i)),
|
|
"6e400001-b5a3-f393-e0a9-e50e24dcca9e", // Nordic UART Service
|
|
canonicalUuid(0xffe0),
|
|
canonicalUuid(0xfff0),
|
|
].filter((u) => !WEB_BLUETOOTH_BLOCKLIST.has(u));
|
|
|
|
/**
|
|
* A rejection of Web Bluetooth as a GattError. `op` picks the not-permitted
|
|
* kind (Chrome's NotSupportedError "GATT operation not permitted." is a
|
|
* read or a write the characteristic does not allow).
|
|
*/
|
|
export function gattErrorFromDom(e: unknown, op: "read" | "write" | "other"): GattError {
|
|
if (e instanceof GattError) return e;
|
|
const name = (e as { name?: string } | null)?.name ?? "";
|
|
const msg = String((e as Error | null)?.message ?? e);
|
|
const m = msg.toLowerCase();
|
|
const denied = op === "read" ? "read-not-permitted" : op === "write" ? "write-not-permitted" : "not-supported";
|
|
if (m.includes("server is disconnected") || m.includes("no longer in range") || (name === "NetworkError" && m.includes("disconnected"))) return new GattError("disconnected", msg);
|
|
if (name === "SecurityError") {
|
|
if (m.includes("exclude-reads")) return new GattError("read-not-permitted", msg);
|
|
if (m.includes("exclude-writes")) return new GattError("write-not-permitted", msg);
|
|
if (m.includes("not authorized")) return new GattError("insufficient-authorization", msg);
|
|
return new GattError(denied, msg);
|
|
}
|
|
if (m.includes("not permitted")) return new GattError(denied, msg);
|
|
if (m.includes("encrypt")) return new GattError("insufficient-encryption", msg);
|
|
if (m.includes("not paired") || m.includes("authenticat")) return new GattError("insufficient-authentication", msg);
|
|
if (m.includes("not authorized") || m.includes("authoriz")) return new GattError("insufficient-authorization", msg);
|
|
if (name === "InvalidModificationError" || m.includes("invalid attribute length") || m.includes("can't exceed")) return new GattError("invalid-length", msg);
|
|
if (m.includes("invalid offset")) return new GattError("invalid-offset", msg);
|
|
if (name === "NotSupportedError" || m.includes("not supported")) return new GattError("not-supported", msg);
|
|
return new GattError("failed", msg);
|
|
}
|
|
|
|
const copy = (v: DataView): Uint8Array => new Uint8Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength));
|
|
const same = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
const notFound = (e: unknown) => (e as { name?: string } | null)?.name === "NotFoundError";
|
|
|
|
function uuidOf(u: string): string | undefined {
|
|
try { return canonicalUuid(u); } catch { return undefined; }
|
|
}
|
|
|
|
function propertyBits(p: WebBluetoothProperties): number {
|
|
return (p.broadcast ? GATT_PROP_BROADCAST : 0) | (p.read ? GATT_PROP_READ : 0) | (p.writeWithoutResponse ? GATT_PROP_WRITE_NO_RESPONSE : 0)
|
|
| (p.write ? GATT_PROP_WRITE : 0) | (p.notify ? GATT_PROP_NOTIFY : 0) | (p.indicate ? GATT_PROP_INDICATE : 0)
|
|
| (p.authenticatedSignedWrites ? GATT_PROP_SIGNED_WRITE : 0) | (p.reliableWrite || p.writableAuxiliaries ? GATT_PROP_EXTENDED : 0);
|
|
}
|
|
|
|
interface Known {
|
|
device: WebBluetoothDevice;
|
|
info: GattDeviceInfo;
|
|
/** Watching advertisements while the guest scans. */
|
|
watch?: AbortController;
|
|
onAdvert?: (e: Event) => void;
|
|
conn?: WebGattConnection;
|
|
}
|
|
|
|
export interface WebBluetoothCentralOptions {
|
|
/** Services to ask for besides WEB_BLUETOOTH_SERVICES (16-bit numbers, "ffe0" or full UUIDs). */
|
|
services?: Array<string | number>;
|
|
label?: string;
|
|
log?: (msg: string) => void;
|
|
}
|
|
|
|
/** Web Bluetooth as a GattCentral: the devices the user picked (requestDevice()) or allowed before. */
|
|
export class WebBluetoothCentral implements GattCentral {
|
|
readonly label: string;
|
|
services: Array<string | number>;
|
|
#log: (msg: string) => void;
|
|
#known = new Map<string, Known>();
|
|
#onDevice = new Set<(d: GattDeviceInfo) => void>();
|
|
#onRemove = new Set<(id: string) => void>();
|
|
#scanning = false;
|
|
#watchWarned = false;
|
|
|
|
constructor(opts: WebBluetoothCentralOptions = {}) {
|
|
this.label = opts.label ?? "Web Bluetooth";
|
|
this.services = opts.services ?? [];
|
|
this.#log = opts.log ?? ((m) => console.warn(m));
|
|
}
|
|
|
|
/** The devices allowed before (getDevices(), where the browser has it); resolves with how many there are. */
|
|
async init(): Promise<number> {
|
|
const b = webBluetooth();
|
|
if (!b?.getDevices || webBluetoothBlocker()) return this.#known.size;
|
|
try {
|
|
for (const d of await b.getDevices()) this.#add(d);
|
|
} catch (e) {
|
|
this.#log(`[bluetooth] getDevices(): ${(e as Error)?.message ?? e}`);
|
|
}
|
|
return this.#known.size;
|
|
}
|
|
|
|
/** The services requestDevice() asks for: the built-in ones, this.services and `extra`, as canonical UUIDs, the blocklisted ones left out. */
|
|
optionalServices(extra: Array<string | number> = []): string[] {
|
|
const out = new Set(WEB_BLUETOOTH_SERVICES);
|
|
for (const u of [...this.services, ...extra]) {
|
|
let c: string;
|
|
try {
|
|
c = canonicalUuid(u);
|
|
} catch {
|
|
this.#log(`[bluetooth] not a service UUID: ${u}`);
|
|
continue;
|
|
}
|
|
if (WEB_BLUETOOTH_BLOCKLIST.has(c)) this.#log(`[bluetooth] ${c} is on Web Bluetooth's blocklist: a page cannot use it`);
|
|
else out.add(c);
|
|
}
|
|
return [...out];
|
|
}
|
|
|
|
/**
|
|
* The browser's chooser (call it from a user gesture: a click handler,
|
|
* before anything is awaited). Resolves with the device picked, which
|
|
* is added; rejects with NotFoundError when the chooser is closed.
|
|
*/
|
|
requestDevice(opts: { optionalServices?: Array<string | number> } = {}): Promise<GattDeviceInfo> {
|
|
const b = webBluetooth();
|
|
const why = webBluetoothBlocker();
|
|
if (!b || why) return Promise.reject(new Error(why ?? "no Web Bluetooth"));
|
|
return b.requestDevice({ acceptAllDevices: true, optionalServices: this.optionalServices(opts.optionalServices) }).then((d) => this.#add(d).info);
|
|
}
|
|
|
|
#add(device: WebBluetoothDevice): Known {
|
|
let k = this.#known.get(device.id);
|
|
if (k) {
|
|
if (k.device !== device) {
|
|
this.#unwatch(k);
|
|
k.device = device;
|
|
}
|
|
if (device.name) k.info = { ...k.info, name: device.name };
|
|
} else {
|
|
k = { device, info: { id: device.id, name: device.name ?? undefined, seen: false } };
|
|
this.#known.set(device.id, k);
|
|
}
|
|
if (this.#scanning) this.#watch(k);
|
|
this.#emit(k.info);
|
|
return k;
|
|
}
|
|
|
|
#emit(d: GattDeviceInfo): void {
|
|
for (const l of this.#onDevice) try { l(d); } catch {}
|
|
}
|
|
|
|
devices(): GattDeviceInfo[] {
|
|
return [...this.#known.values()].map((k) => k.info);
|
|
}
|
|
|
|
/** The guest has a link to the device (a connection open). */
|
|
connected(id: string): boolean {
|
|
return !!this.#known.get(id)?.conn?.open;
|
|
}
|
|
|
|
onDevice(listener: (d: GattDeviceInfo) => void): () => void {
|
|
this.#onDevice.add(listener);
|
|
return () => this.#onDevice.delete(listener);
|
|
}
|
|
|
|
onRemove(listener: (id: string) => void): () => void {
|
|
this.#onRemove.add(listener);
|
|
return () => this.#onRemove.delete(listener);
|
|
}
|
|
|
|
/** The guest scans: watch every known device's advertisements meanwhile (where the browser can). */
|
|
scan(on: boolean): void {
|
|
if (on === this.#scanning) return;
|
|
this.#scanning = on;
|
|
for (const k of this.#known.values()) {
|
|
if (on) this.#watch(k);
|
|
else {
|
|
this.#unwatch(k);
|
|
k.info = { ...k.info, seen: false };
|
|
}
|
|
}
|
|
}
|
|
|
|
#watch(k: Known): void {
|
|
const dev = k.device;
|
|
if (k.watch || !dev.watchAdvertisements) return;
|
|
const ac = new AbortController();
|
|
k.watch = ac;
|
|
k.onAdvert = (e) => this.#advert(k, e as WebBluetoothAdvertisingEvent);
|
|
dev.addEventListener("advertisementreceived", k.onAdvert);
|
|
dev.watchAdvertisements({ signal: ac.signal }).catch((e: unknown) => {
|
|
if (ac.signal.aborted || (e as { name?: string })?.name === "AbortError") return;
|
|
if (!this.#watchWarned) this.#log(`[bluetooth] watchAdvertisements(): ${(e as Error)?.message ?? e} (devices are reported without their advertisements)`);
|
|
this.#watchWarned = true;
|
|
if (k.watch === ac) this.#unwatch(k);
|
|
});
|
|
}
|
|
|
|
#unwatch(k: Known): void {
|
|
k.watch?.abort();
|
|
k.watch = undefined;
|
|
if (k.onAdvert) k.device.removeEventListener("advertisementreceived", k.onAdvert);
|
|
k.onAdvert = undefined;
|
|
}
|
|
|
|
#advert(k: Known, e: WebBluetoothAdvertisingEvent): void {
|
|
if (!this.#scanning || this.#known.get(k.info.id) !== k) return;
|
|
const uuids = (e.uuids ?? []).map(uuidOf).filter((u): u is string => !!u);
|
|
const info: GattDeviceInfo = { ...k.info, seen: true, uuids: uuids.length ? uuids : k.info.uuids };
|
|
const name = e.name ?? e.device?.name;
|
|
if (name) info.name = name;
|
|
if (typeof e.rssi === "number") info.rssi = e.rssi;
|
|
if (typeof e.txPower === "number") info.txPower = e.txPower;
|
|
if (e.manufacturerData?.size) info.manufacturerData = new Map([...e.manufacturerData].map(([id, v]) => [id, copy(v)]));
|
|
if (e.serviceData?.size) {
|
|
const sd = new Map<string, Uint8Array>();
|
|
for (const [u, v] of e.serviceData) {
|
|
const c = uuidOf(u);
|
|
if (c) sd.set(c, copy(v));
|
|
}
|
|
info.serviceData = sd;
|
|
}
|
|
k.info = info;
|
|
this.#emit(info);
|
|
}
|
|
|
|
/** Forget a device (device.forget() where the browser has it: the page's permission goes) and drop it. */
|
|
async forget(id: string): Promise<void> {
|
|
const k = this.#known.get(id);
|
|
if (!k) return;
|
|
this.#unwatch(k);
|
|
k.conn?.end(true);
|
|
this.#known.delete(id);
|
|
for (const l of this.#onRemove) try { l(id); } catch {}
|
|
try {
|
|
await k.device.forget?.();
|
|
} catch (e) {
|
|
this.#log(`[bluetooth] forget(): ${(e as Error)?.message ?? e}`);
|
|
}
|
|
}
|
|
|
|
async connect(id: string): Promise<GattConnection> {
|
|
const k = this.#known.get(id);
|
|
if (!k) throw new GattError("failed", `no device ${id}`);
|
|
const gatt = k.device.gatt;
|
|
if (!gatt) throw new GattError("not-supported", "the device has no GATT server");
|
|
let server: WebBluetoothServer;
|
|
try {
|
|
server = await gatt.connect();
|
|
} catch (e) {
|
|
throw gattErrorFromDom(e, "other");
|
|
}
|
|
if (this.#known.get(id) !== k) {
|
|
try { gatt.disconnect(); } catch {}
|
|
throw new GattError("failed", "the device was forgotten");
|
|
}
|
|
// One GATT server per device: a connection still open is over (the controller sees its link drop).
|
|
k.conn?.end(true);
|
|
const conn = new WebGattConnection(k.device, server, () => {
|
|
if (k.conn === conn) k.conn = undefined;
|
|
});
|
|
k.conn = conn;
|
|
return conn;
|
|
}
|
|
}
|
|
|
|
interface Svc {
|
|
service: WebBluetoothService;
|
|
chars: WebBluetoothCharacteristic[];
|
|
descs: WebBluetoothDescriptor[][];
|
|
}
|
|
|
|
/** One GATT connection on Web Bluetooth (WebBluetoothCentral.connect()). */
|
|
class WebGattConnection implements GattConnection {
|
|
open = true;
|
|
#device: WebBluetoothDevice;
|
|
#server: WebBluetoothServer;
|
|
#done: () => void;
|
|
#svcs: Svc[] = [];
|
|
#notify = new Set<(path: GattPath, value: Uint8Array) => void>();
|
|
#disc = new Set<() => void>();
|
|
#subscribed = new Set<WebBluetoothCharacteristic>();
|
|
/** Value-changed events held while a read of the characteristic is pending (readValue() fires one too). */
|
|
#reading = new Map<WebBluetoothCharacteristic, Uint8Array[]>();
|
|
#off: Array<() => void> = [];
|
|
|
|
constructor(device: WebBluetoothDevice, server: WebBluetoothServer, done: () => void) {
|
|
this.#device = device;
|
|
this.#server = server;
|
|
this.#done = done;
|
|
const lost = () => this.end(true);
|
|
device.addEventListener("gattserverdisconnected", lost);
|
|
this.#off.push(() => device.removeEventListener("gattserverdisconnected", lost));
|
|
}
|
|
|
|
async #op<T>(op: "read" | "write" | "other", run: () => Promise<T>): Promise<T> {
|
|
if (!this.open) throw new GattError("disconnected", "GATT Server is disconnected");
|
|
try {
|
|
return await run();
|
|
} catch (e) {
|
|
if (!this.open) throw new GattError("disconnected", "GATT Server is disconnected");
|
|
throw gattErrorFromDom(e, op);
|
|
}
|
|
}
|
|
|
|
#char(path: GattPath): WebBluetoothCharacteristic {
|
|
const c = this.#svcs[path.service]?.chars[path.char];
|
|
if (!c) throw new GattError("failed", "no such characteristic");
|
|
return c;
|
|
}
|
|
|
|
#desc(path: GattPath): WebBluetoothDescriptor {
|
|
const d = this.#svcs[path.service]?.descs[path.char]?.[path.desc ?? -1];
|
|
if (!d) throw new GattError("failed", "no such descriptor");
|
|
return d;
|
|
}
|
|
|
|
discover(): Promise<GattServiceInfo[]> {
|
|
return this.#op("other", async () => {
|
|
const primaries = await this.#server.getPrimaryServices().catch((e: unknown) => {
|
|
if (notFound(e)) return [] as WebBluetoothService[];
|
|
throw e;
|
|
});
|
|
const svcs: Svc[] = [];
|
|
const index = new Map<WebBluetoothService, number>();
|
|
const queue = [...primaries];
|
|
const includes: Array<WebBluetoothService[]> = [];
|
|
for (const s of primaries) index.set(s, index.size);
|
|
// Included services the primaries do not list are appended (and discovered) after them.
|
|
for (let i = 0; i < queue.length; i++) {
|
|
const service = queue[i]!;
|
|
const chars = await service.getCharacteristics().catch((e: unknown) => {
|
|
if (notFound(e)) return [] as WebBluetoothCharacteristic[];
|
|
throw e;
|
|
});
|
|
const descs: WebBluetoothDescriptor[][] = [];
|
|
for (const c of chars) {
|
|
descs.push(await c.getDescriptors().catch((e: unknown) => {
|
|
if (notFound(e)) return [] as WebBluetoothDescriptor[];
|
|
throw e;
|
|
}));
|
|
}
|
|
let inc: WebBluetoothService[] = [];
|
|
if (service.getIncludedServices) {
|
|
try {
|
|
inc = await service.getIncludedServices();
|
|
} catch {}
|
|
}
|
|
for (const s of inc) {
|
|
if (index.has(s)) continue;
|
|
const byUuid = queue.findIndex((q) => q.uuid === s.uuid);
|
|
if (byUuid >= 0) index.set(s, byUuid);
|
|
else {
|
|
index.set(s, queue.length);
|
|
queue.push(s);
|
|
}
|
|
}
|
|
svcs.push({ service, chars, descs });
|
|
includes.push(inc);
|
|
}
|
|
if (!this.open) throw new GattError("disconnected", "GATT Server is disconnected");
|
|
this.#listen(svcs);
|
|
return svcs.map((s, i) => {
|
|
const out: GattServiceInfo = {
|
|
uuid: uuidOf(s.service.uuid) ?? s.service.uuid,
|
|
primary: s.service.isPrimary ?? true,
|
|
characteristics: s.chars.map((c, j) => ({
|
|
uuid: uuidOf(c.uuid) ?? c.uuid,
|
|
properties: propertyBits(c.properties),
|
|
descriptors: s.descs[j]!.map((d) => ({ uuid: uuidOf(d.uuid) ?? d.uuid })),
|
|
})),
|
|
};
|
|
const inc = includes[i]!.map((x) => index.get(x)).filter((n): n is number => n !== undefined && n !== i);
|
|
if (inc.length) out.includes = inc;
|
|
return out;
|
|
});
|
|
});
|
|
}
|
|
|
|
/** Value-changed listeners on the discovered characteristics (the previous discovery's go). */
|
|
#listen(svcs: Svc[]): void {
|
|
for (const s of this.#svcs) for (const c of s.chars) this.#subscribed.delete(c);
|
|
this.#svcs = svcs;
|
|
svcs.forEach((s, si) => s.chars.forEach((c, ci) => {
|
|
const path: GattPath = { service: si, char: ci };
|
|
const on = () => {
|
|
const v = c.value;
|
|
if (!v || !this.open) return;
|
|
const bytes = copy(v);
|
|
const held = this.#reading.get(c);
|
|
if (held) held.push(bytes);
|
|
else if (this.#subscribed.has(c)) this.#emit(path, bytes);
|
|
};
|
|
c.addEventListener("characteristicvaluechanged", on);
|
|
this.#off.push(() => c.removeEventListener("characteristicvaluechanged", on));
|
|
}));
|
|
}
|
|
|
|
#emit(path: GattPath, value: Uint8Array): void {
|
|
for (const l of this.#notify) try { l(path, value.slice()); } catch {}
|
|
}
|
|
|
|
read(path: GattPath): Promise<Uint8Array> {
|
|
return this.#op("read", async () => {
|
|
if (path.desc !== undefined) return copy(await this.#desc(path).readValue());
|
|
const c = this.#char(path);
|
|
// readValue() fires characteristicvaluechanged too: that event is the read's, not a notification.
|
|
this.#reading.set(c, []);
|
|
let value: Uint8Array | undefined;
|
|
try {
|
|
value = copy(await c.readValue());
|
|
return value;
|
|
} finally {
|
|
const held = this.#reading.get(c) ?? [];
|
|
this.#reading.delete(c);
|
|
let skipped = false;
|
|
for (const v of held) {
|
|
if (!skipped && value && same(v, value)) skipped = true;
|
|
else if (this.#subscribed.has(c) && this.open) this.#emit({ service: path.service, char: path.char }, v);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
write(path: GattPath, value: Uint8Array, withResponse: boolean): Promise<void> {
|
|
return this.#op("write", async () => {
|
|
const data = value.slice();
|
|
if (path.desc !== undefined) return this.#desc(path).writeValue(data);
|
|
const c = this.#char(path);
|
|
const w = withResponse ? c.writeValueWithResponse ?? c.writeValue : c.writeValueWithoutResponse ?? c.writeValue;
|
|
if (!w) throw new GattError("not-supported", "the browser cannot write characteristics");
|
|
await w.call(c, data);
|
|
});
|
|
}
|
|
|
|
subscribe(path: GattPath, on: boolean): Promise<void> {
|
|
return this.#op("other", async () => {
|
|
const c = this.#char(path);
|
|
if (on) {
|
|
await c.startNotifications();
|
|
this.#subscribed.add(c);
|
|
} else {
|
|
this.#subscribed.delete(c);
|
|
await c.stopNotifications();
|
|
}
|
|
});
|
|
}
|
|
|
|
onNotify(listener: (path: GattPath, value: Uint8Array) => void): () => void {
|
|
this.#notify.add(listener);
|
|
return () => this.#notify.delete(listener);
|
|
}
|
|
|
|
onDisconnect(listener: () => void): () => void {
|
|
this.#disc.add(listener);
|
|
return () => this.#disc.delete(listener);
|
|
}
|
|
|
|
/** The connection is over; `remote`: the device's side (or another connection) ended it, so the listeners hear it. */
|
|
end(remote: boolean): void {
|
|
if (!this.open) return;
|
|
this.open = false;
|
|
for (const off of this.#off) try { off(); } catch {}
|
|
this.#off = [];
|
|
this.#subscribed.clear();
|
|
this.#reading.clear();
|
|
this.#done();
|
|
if (remote) for (const l of this.#disc) try { l(); } catch {}
|
|
this.#disc.clear();
|
|
this.#notify.clear();
|
|
}
|
|
|
|
disconnect(): void {
|
|
if (!this.open) return;
|
|
this.end(false);
|
|
try { this.#device.gatt?.disconnect(); } catch {}
|
|
}
|
|
}
|