Files
unkernel/test/bluetooth-host.test.ts

675 lines
34 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// kwbt's host side without a kernel: the wasm_driver_bt_* imports
// (js/core/bluetooth.ts) driven directly on a memory of their own, as
// drivers/bluetooth/kwbt.c calls them, with BluetoothDevice and
// BluetoothHost joined as createKernel joins them inline (and once across a
// MessageChannel, as in worker mode), and VirtualLeController
// (js/core/bluetooth-le.ts) answering real HCI, L2CAP, ATT and SMP byte
// sequences against FakeGattCentral (js/core/bluetooth-gatt.ts). Also
// H4StreamController over an in-memory byte stream. test/bluetooth.test.ts
// is the end-to-end test with the kernel.
//
// node --test test/bluetooth-host.test.ts (pnpm test:bluetooth-host; pnpm test:bluetooth runs both)
import { afterEach, test } from "node:test";
import assert from "node:assert/strict";
import {
BT_EV_CHANGE, BT_EV_RX, BT_EV_TX, BT_RX_WINDOW, BT_TX_WINDOW, BluetoothDevice, BluetoothHost, H4Framer, H4StreamController,
btTransfer, type BluetoothController, type BluetoothSink, type BtDown,
} from "../js/core/bluetooth.ts";
import { ATT_MTU, VirtualLeController, advertisingData } from "../js/core/bluetooth-le.ts";
import {
FAKE_LOOPBACK_CHAR, FakeGattCentral, canonicalUuid, deviceAddress, fakeDemoPeripheral, formatAddress, parseAddress, uuidBytes, uuidFromBytes,
type FakePeripheral,
} from "../js/core/bluetooth-gatt.ts";
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
async function until(what: string, cond: () => boolean, ms = 2000): Promise<void> {
const end = performance.now() + ms;
while (!cond()) {
if (performance.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(2);
}
}
const le16 = (v: number) => [v & 0xff, (v >> 8) & 0xff];
const rd16 = (b: Uint8Array, at: number) => b[at]! | (b[at + 1]! << 8);
const BUF = 0x1000, OUT = 0x10000;
type Imports = {
wasm_driver_bt_init(): number;
wasm_driver_bt_status(): number;
wasm_driver_bt_info(id: number): number;
wasm_driver_bt_open(id: number): number;
wasm_driver_bt_close(id: number): void;
wasm_driver_bt_send(id: number, buf: bigint, len: number): number;
wasm_driver_bt_rx_len(id: number): number;
wasm_driver_bt_recv(id: number, buf: bigint, max: number): number;
};
const hosts: BluetoothHost[] = [];
afterEach(() => {
for (const h of hosts.splice(0)) h.shutdown();
});
/** A parsed packet from the controller. */
type Pkt =
| { t: "event"; code: number; p: Uint8Array }
| { t: "acl"; handle: number; pb: number; data: Uint8Array };
/**
* The kernel's end of a machine: a device and a host joined as inline mode
* joins them, on a memory of 2 MiB, and the driver's side of the imports
* (send H4, read everything received) with an HCI host's helpers on top.
*/
function machine(opts: { enabled?: boolean } = {}) {
const memory = new WebAssembly.Memory({ initial: 32 });
const u8 = () => new Uint8Array(memory.buffer);
let irqs = 0;
let dev!: BluetoothDevice;
const logs: string[] = [];
const host = new BluetoothHost({ send: (ops) => { for (const m of ops) dev.receive(m); }, log: (m) => logs.push(m) });
dev = new BluetoothDevice({ enabled: opts.enabled ?? true, memory: () => memory, raise: () => irqs++, send: (m) => host.receive(m) });
hosts.push(host);
const k = dev.imports() as unknown as Imports;
const pkts: Pkt[] = [];
let id = 0;
const m = {
dev, host, k, logs, pkts,
get irqs() { return irqs; },
get id() { return id; },
/** Read the status as the driver does; remember the attached id. */
status(): number {
const s = k.wasm_driver_bt_status();
id = s >>> 16;
return s;
},
sendRaw(bytes: ArrayLike<number>, as = id): number {
u8().set(bytes, BUF);
return k.wasm_driver_bt_send(as, BigInt(BUF), bytes.length);
},
/** Take every packet waiting, parsed. */
drain(): Pkt[] {
const got: Pkt[] = [];
for (let n; (n = k.wasm_driver_bt_rx_len(id)) > 0; ) {
assert.equal(k.wasm_driver_bt_recv(id, BigInt(OUT), n), n);
const b = u8().slice(OUT, OUT + n);
if (b[0] === 4) got.push({ t: "event", code: b[1]!, p: b.slice(3, 3 + b[2]!) });
else if (b[0] === 2) got.push({ t: "acl", handle: rd16(b, 1) & 0xfff, pb: rd16(b, 1) >> 12, data: b.slice(5, 5 + rd16(b, 3)) });
}
pkts.push(...got);
return got;
},
/** Wait for a packet matching `pred` (taking the ones before it into pkts). */
async expect<T extends Pkt>(what: string, pred: (p: Pkt) => p is T, ms = 2000): Promise<T> {
let found: T | undefined;
const end = performance.now() + ms;
for (;;) {
const i = pkts.findIndex(pred);
if (i >= 0) {
found = pkts.splice(i, 1)[0] as T;
return found;
}
if (performance.now() > end) throw new Error(`timed out waiting for ${what}; have ${JSON.stringify(pkts.map((x) => (x.t === "event" ? `ev 0x${x.code.toString(16)}` : `acl ${x.data.length}`)))}`);
m.drain();
if (!pkts.some(pred)) await sleep(2);
}
},
/** An HCI command and its Command Complete (or Status) parameters. */
async cmd(op: number, params: ArrayLike<number> = []): Promise<Uint8Array> {
assert.equal(m.sendRaw([1, ...le16(op), params.length, ...Array.from(params)]), 0);
const ev = await m.expect(`the answer to 0x${op.toString(16)}`, (p): p is Pkt & { t: "event" } =>
p.t === "event" && ((p.code === 0x0e && rd16(p.p, 1) === op) || (p.code === 0x0f && rd16(p.p, 2) === op)));
return ev.code === 0x0e ? ev.p.slice(3) : Uint8Array.of(ev.p[0]!);
},
/** An LE meta event with this subevent. */
le(sub: number, ms?: number) {
return m.expect(`LE subevent 0x${sub.toString(16)}`, (p): p is Pkt & { t: "event" } => p.t === "event" && p.code === 0x3e && p.p[0] === sub, ms);
},
event(code: number, ms?: number) {
return m.expect(`event 0x${code.toString(16)}`, (p): p is Pkt & { t: "event" } => p.t === "event" && p.code === code, ms);
},
/** An L2CAP PDU on a link, fragmented to `mtu`-byte ACL packets. */
l2cap(handle: number, cid: number, payload: ArrayLike<number>, mtu = 27): number {
const pdu = [...le16(payload.length), ...le16(cid), ...Array.from(payload)];
let n = 0;
for (let at = 0; at < pdu.length; at += mtu) {
const frag = pdu.slice(at, at + mtu);
assert.equal(m.sendRaw([2, ...le16(handle | ((at ? 1 : 0) << 12)), ...le16(frag.length), ...frag]), 0);
n++;
}
return n;
},
/** The next L2CAP PDU from a link on `cid` (reassembled). */
async l2capIn(handle: number, cid: number, ms?: number): Promise<Uint8Array> {
const first = await m.expect(`L2CAP on CID ${cid}`, (p): p is Pkt & { t: "acl" } => p.t === "acl" && p.handle === handle && p.pb === 2 && rd16(p.data, 2) === cid, ms);
let pdu = first.data;
const want = rd16(pdu, 0) + 4;
while (pdu.length < want) {
const c = await m.expect("a continuation", (p): p is Pkt & { t: "acl" } => p.t === "acl" && p.handle === handle && p.pb === 1, ms);
const n = new Uint8Array(pdu.length + c.data.length);
n.set(pdu);
n.set(c.data, pdu.length);
pdu = n;
}
return pdu.slice(4, want);
},
/** An ATT request and its response. */
async att(handle: number, req: ArrayLike<number>): Promise<Uint8Array> {
m.l2cap(handle, 4, req);
return m.l2capIn(handle, 4);
},
};
return m;
}
/** Init as kwbt does at boot, attach `ctl`, open, and reset it. */
async function ready(m: ReturnType<typeof machine>, ctl: BluetoothController) {
assert.equal(m.k.wasm_driver_bt_init(), 1);
await m.host.attach(ctl);
await until("the attach", () => (m.status() >>> 16) !== 0);
assert.equal(m.k.wasm_driver_bt_info(m.id), 0, "a virtual controller");
assert.equal(m.k.wasm_driver_bt_open(m.id), 0);
assert.deepEqual([...(await m.cmd(0x0c03))], [0], "Reset");
}
/** Connect to the device with `id`; returns the link's handle. */
async function connect(m: ReturnType<typeof machine>, id: string): Promise<number> {
const addr = deviceAddress(id);
const p = [...le16(0x60), ...le16(0x30), 0, 1, ...addr, 0, ...le16(24), ...le16(40), ...le16(0), ...le16(500), 0, 0, 0, 0];
assert.deepEqual([...(await m.cmd(0x200d, p))], [0], "LE Create Connection: Command Status success");
const cc = await m.le(0x01);
assert.equal(cc.p[1], 0, "LE Connection Complete: success");
assert.deepEqual([...cc.p.subarray(6, 12)], [...addr], "the peer's address");
assert.equal(cc.p[4], 0, "central role");
return rd16(cc.p, 2);
}
/** Every attribute: Find Information from 1 on. */
async function findAll(m: ReturnType<typeof machine>, h: number): Promise<Array<{ handle: number; uuid: string }>> {
const out: Array<{ handle: number; uuid: string }> = [];
for (let start = 1; ; ) {
const r = await m.att(h, [0x04, ...le16(start), ...le16(0xffff)]);
if (r[0] === 0x01) {
assert.equal(r[4], 0x0a, "Attribute Not Found at the end");
return out;
}
assert.equal(r[0], 0x05);
const step = r[1] === 1 ? 4 : 18;
for (let i = 2; i < r.length; i += step) out.push({ handle: rd16(r, i), uuid: uuidFromBytes(r.subarray(i + 2, i + step)) });
start = out[out.length - 1]!.handle + 1;
}
}
test("UUIDs, addresses, H4 framing", () => {
assert.equal(canonicalUuid(0x180d), "0000180d-0000-1000-8000-00805f9b34fb");
assert.equal(canonicalUuid("0x2A37"), "00002a37-0000-1000-8000-00805f9b34fb");
assert.deepEqual([...uuidBytes("180f")], [0x0f, 0x18]);
assert.equal(uuidFromBytes(uuidBytes(FAKE_LOOPBACK_CHAR)), FAKE_LOOPBACK_CHAR);
const a = deviceAddress("some device id==");
assert.equal(a[5]! & 0xc0, 0xc0, "a static random address");
assert.deepEqual(deviceAddress("some device id=="), a, "stable");
assert.notDeepEqual(deviceAddress("another id"), a);
assert.deepEqual(parseAddress(formatAddress(a)), a);
const f = new H4Framer();
const evt = [4, 0x0e, 4, 1, 3, 0x0c, 0];
const acl = [2, 0x40, 0x20, 3, 0, 9, 8, 7];
assert.deepEqual(f.push(Uint8Array.from([...evt, ...acl.slice(0, 4)])).map((p) => [...p]), [evt]);
assert.deepEqual(f.push(Uint8Array.from(acl.slice(4))).map((p) => [...p]), [acl]);
assert.throws(() => f.push(Uint8Array.of(9, 1, 2)), /unknown packet type/);
// Advertising data: flags, the 16-bit UUIDs, the name; a long name goes to the scan response.
const ad = advertisingData({ id: "x", name: "a rather long device name!", uuids: [canonicalUuid(0x180f), canonicalUuid(0x180d)] });
assert.deepEqual([...ad.adv.subarray(0, 3)], [2, 1, 6]);
assert.deepEqual([...ad.adv.subarray(3, 9)], [5, 3, 0x0f, 0x18, 0x0d, 0x18]);
assert.ok(ad.adv.length <= 31 && ad.rsp.length <= 31);
assert.equal(ad.rsp[1], 0x09, "the name in the scan response");
});
test("the transport: probe, attach, ids, open, detach, a stale id", async () => {
const off = machine({ enabled: false });
assert.equal(off.k.wasm_driver_bt_init(), -19, "no device without the option");
assert.ok(off.dev.probed);
const m = machine();
assert.equal(m.k.wasm_driver_bt_init(), 1);
assert.equal(m.status(), 0, "nothing attached");
assert.equal(m.k.wasm_driver_bt_info(1), -19);
const central = new FakeGattCentral([]);
const ctl = new VirtualLeController({ central, address: "02:00:00:00:00:01", log: () => {} });
const changes: boolean[] = [];
m.host.onChange((s) => changes.push(s.attached));
await m.host.attach(ctl);
await until("the attach", () => m.irqs > 0);
const st = m.status();
assert.ok(st & BT_EV_CHANGE);
const first = st >>> 16;
assert.ok(first > 0);
assert.equal(m.status() & BT_EV_CHANGE, 0, "events are cleared by the read");
assert.equal(m.k.wasm_driver_bt_open(first), 0);
await until("open", () => m.host.state.open);
const v = await m.cmd(0x1001);
assert.deepEqual([...v], [0, 8, 0, 0, 8, 0xf1, 0x05, 0, 0], "Read Local Version: 4.2, The Linux Foundation");
assert.deepEqual([...(await m.cmd(0x1009))], [0, 1, 0, 0, 0, 0, 2], "Read BD_ADDR");
// Another controller: the id changes, and the old id is refused everywhere.
const ctl2 = new VirtualLeController({ central, address: "02:00:00:00:00:02", log: () => {} });
await m.host.attach(ctl2);
await until("the second attach", () => (m.status() >>> 16) !== first);
const second = m.id;
assert.equal(m.sendRaw([1, 3, 0x0c, 0], first), -19);
assert.equal(m.k.wasm_driver_bt_open(first), -19);
assert.equal(m.k.wasm_driver_bt_info(first), -19);
assert.equal(m.k.wasm_driver_bt_rx_len(first), 0);
assert.deepEqual([...(await m.cmd(0x1009))], [0, 2, 0, 0, 0, 0, 2], "the new controller answers");
await m.host.detach();
await until("the detach", () => (m.status() >>> 16) === 0);
assert.equal(m.sendRaw([1, 3, 0x0c, 0], second), -19);
assert.equal(m.host.state.attached, false);
await sleep(5);
assert.deepEqual(changes.slice(-1), [false]);
// A snapshot keeps the last id: the restored machine's controller is a new one.
const snap = m.dev.saveState();
const m2 = machine();
m2.dev.restoreState(snap);
await m2.host.attach(new VirtualLeController({ central, log: () => {} }));
await until("the attach after restore", () => (m2.status() >>> 16) !== 0);
assert.equal(m2.id, second + 1);
});
test("the transport's windows: TX refused past the window, RX held past it, nothing lost", async () => {
const m = machine();
assert.equal(m.k.wasm_driver_bt_init(), 1);
let sink!: BluetoothSink;
const got: Uint8Array[] = [];
let hold = true;
const held: Uint8Array[] = [];
const ctl: BluetoothController = { attach: (s) => (sink = s), send: (p) => (hold ? held : got).push(p), detach: () => {} };
// A host whose acks are delayed until we let them through.
const acks: Array<() => void> = [];
let dev!: BluetoothDevice;
const host = new BluetoothHost({ send: (ops) => { for (const op of ops) op.op === "sent" ? acks.push(() => dev.receive(op)) : dev.receive(op); }, log: () => {} });
hosts.push(host);
dev = m.dev;
(dev as { send: (x: BtDown) => void }).send = (x) => host.receive(x);
await host.attach(ctl);
await until("attach", () => (m.status() >>> 16) !== 0);
let refused = 0;
for (let i = 0; i < BT_TX_WINDOW + 5; i++) if (m.sendRaw([1, 1, 0x10, 1, i]) === -11) refused++;
assert.equal(refused, 5, "-EAGAIN past the window");
assert.equal(m.dev.stats.refused, 5);
await sleep(5);
for (const a of acks.splice(0)) a();
assert.ok(m.status() & BT_EV_TX, "room again");
assert.equal(m.sendRaw([1, 1, 0x10, 1, 99]), 0);
hold = false;
assert.equal(got.length, 0);
assert.deepEqual(held.map((p) => p[4]), [...Array.from({ length: BT_TX_WINDOW }, (_, i) => i), 99], "every packet taken was handed over, in order");
// RX: more than the window while the kernel does not read; all arrive, in order.
const N = BT_RX_WINDOW + 50;
for (let i = 0; i < N; i++) sink.packet(Uint8Array.of(4, 0xff, 2, i & 0xff, i >> 8));
await sleep(5);
assert.equal(m.dev.rxPending, BT_RX_WINDOW, "the host holds the rest");
assert.ok(m.status() & BT_EV_RX);
const seen: number[] = [];
for (let round = 0; round < 50 && seen.length < N; round++) {
for (const p of m.drain()) if (p.t === "event") seen.push(p.p[0]! | (p.p[1]! << 8));
await sleep(2);
}
assert.deepEqual(seen, Array.from({ length: N }, (_, i) => i));
// A lost controller is detached.
sink.lost("unplugged");
await until("detached", () => (m.status() >>> 16) === 0);
assert.equal(host.state.error, "unplugged");
});
test("the virtual controller: init commands, the feature set, unknown commands", async () => {
const m = machine();
const logs: string[] = [];
await ready(m, new VirtualLeController({ central: new FakeGattCentral([]), log: (x) => logs.push(x) }));
const feat = await m.cmd(0x1003);
assert.equal(feat[5], 0x60, "LMP features: LE supported, BR/EDR not supported");
const cmds = await m.cmd(0x1002);
assert.equal(cmds.length, 65);
const has = (o: number, b: number) => !!(cmds[1 + o]! & (1 << b));
assert.ok(has(5, 7) && has(5, 6) && has(0, 5) && has(26, 3) && has(26, 4), "Reset, Set Event Mask, Disconnect, scan enable, create connection");
assert.ok(!has(25, 7) && !has(26, 1), "no advertising");
assert.deepEqual([...(await m.cmd(0x2002))], [0, 251, 0, 16], "LE Read Buffer Size");
assert.deepEqual([...(await m.cmd(0x2003))], [0, 0, 0, 0, 0, 0, 0, 0, 0], "no LE features");
assert.deepEqual([...(await m.cmd(0x201c))].slice(0, 2), [0, 0x70], "LE states: scanning and initiating");
assert.deepEqual([...(await m.cmd(0x200f))], [0, 16], "accept list size");
assert.deepEqual([...(await m.cmd(0x2008, new Array(32).fill(0)))], [1], "LE Set Advertising Data: Unknown HCI Command");
assert.deepEqual([...(await m.cmd(0x2008, new Array(32).fill(0)))], [1]);
assert.equal(logs.filter((l) => l.includes("0x2008")).length, 1, "logged once");
assert.equal((await m.cmd(0x2018)).length, 9, "LE Rand");
});
test("scanning: reports for known devices, scan responses, duplicates, the accept list", async () => {
const m = machine();
const central = new FakeGattCentral([fakeDemoPeripheral(), { id: "other", name: "Other", services: [] }]);
const ctl = new VirtualLeController({ central, log: () => {} });
const activity: boolean[] = [];
ctl.onActivity((a) => activity.push(a.scanning));
await ready(m, ctl);
assert.deepEqual([...(await m.cmd(0x200b, [1, ...le16(0x10), ...le16(0x10), 0, 0]))], [0], "active scan");
assert.deepEqual([...(await m.cmd(0x200c, [1, 1]))], [0], "enable, filter duplicates");
const reports = new Map<string, number[]>();
const take = async (n: number) => {
for (let i = 0; i < n; i++) {
const ev = await m.le(0x02);
const key = formatAddress(ev.p.subarray(4, 10));
reports.set(key, [...(reports.get(key) ?? []), ev.p[2]!]);
}
};
await take(4);
const fake = formatAddress(deviceAddress("unkernel-fake-peripheral"));
assert.deepEqual(reports.get(fake), [0x00, 0x04], "ADV_IND, then SCAN_RSP");
assert.equal(reports.size, 2);
assert.ok(central.scanning, "the central watches advertisements meanwhile");
assert.deepEqual(activity, [true]);
// With duplicate filtering, nothing more within a repeat period.
await sleep(1100);
m.drain();
assert.ok(!m.pkts.some((p) => p.t === "event" && p.code === 0x3e && p.p[0] === 2), "no duplicates");
// A new device is reported at once.
central.add({ id: "late", name: "Late", services: [] });
const late = await m.le(0x02);
assert.equal(formatAddress(late.p.subarray(4, 10)), formatAddress(deviceAddress("late")));
assert.deepEqual([...(await m.cmd(0x200c, [0, 0]))], [0]);
assert.equal(central.scanning, false);
m.drain();
m.pkts.length = 0;
// The accept list: only listed devices, with passive scanning (no scan responses).
assert.deepEqual([...(await m.cmd(0x2011, [1, ...deviceAddress("other")]))], [0]);
assert.deepEqual([...(await m.cmd(0x200b, [0, ...le16(0x10), ...le16(0x10), 0, 1]))], [0]);
assert.deepEqual([...(await m.cmd(0x200c, [1, 0]))], [0]);
const only = await m.le(0x02);
assert.equal(formatAddress(only.p.subarray(4, 10)), formatAddress(deviceAddress("other")));
assert.equal(only.p[2], 0x00);
await sleep(20);
m.drain();
assert.ok(!m.pkts.some((p) => p.t === "event" && p.code === 0x3e && p.p[0] === 2), "nothing else");
// Without duplicate filtering it repeats.
await m.le(0x02, 2500);
assert.deepEqual([...(await m.cmd(0x200c, [0, 0]))], [0]);
});
/** A peripheral with every kind of attribute the GATT server must handle. */
function testPeripheral(): FakePeripheral {
const long = Uint8Array.from({ length: 300 }, (_, i) => i & 0xff);
return {
id: "test-peripheral",
name: "Test",
services: [
{ uuid: 0x1800, characteristics: [{ uuid: 0x2a00, properties: ["read"], value: new TextEncoder().encode("remote GAP, hidden") }] },
{ uuid: 0x180f, characteristics: [{ uuid: 0x2a19, properties: ["read", "notify"], value: Uint8Array.of(50) }] },
{
uuid: "12345678-1234-5678-1234-56789abcdef0",
characteristics: [
{ uuid: "12345678-1234-5678-1234-56789abcdef1", properties: ["read", "write"], value: long, descriptors: [{ uuid: 0x2901, value: new TextEncoder().encode("long") }] },
{ uuid: "12345678-1234-5678-1234-56789abcdef2", properties: ["indicate"] },
{ uuid: "12345678-1234-5678-1234-56789abcdef3", properties: ["read"], readError: "insufficient-authentication" },
{ uuid: "12345678-1234-5678-1234-56789abcdef4", properties: ["writeWithoutResponse", "notify"], onWrite: (v) => v },
],
},
],
};
}
test("a connection: GATT discovery, reads, long reads and writes, errors, notifications, indications", async () => {
const m = machine();
const central = new FakeGattCentral([testPeripheral()]);
await ready(m, new VirtualLeController({ central, log: () => {} }));
const h = await connect(m, "test-peripheral");
assert.ok(central.connected("test-peripheral"));
// Read Remote Features and Version, as Linux asks after the connection.
assert.deepEqual([...(await m.cmd(0x2016, le16(h)))], [0]);
assert.equal((await m.le(0x04)).p[1], 0);
assert.deepEqual([...(await m.cmd(0x041d, le16(h)))], [0]);
assert.equal((await m.event(0x0c)).p[0], 0);
let r = await m.att(h, [0x02, ...le16(517)]);
assert.deepEqual([...r], [0x03, ...le16(ATT_MTU)], "Exchange MTU");
// Primary services: the synthesized GAP and GATT (the remote's GAP left out), then the remote's.
const groups: Array<{ start: number; end: number; uuid: string }> = [];
for (let start = 1; ; ) {
r = await m.att(h, [0x10, ...le16(start), ...le16(0xffff), ...le16(0x2800)]);
if (r[0] === 0x01) break;
const len = r[1]!;
for (let i = 2; i < r.length; i += len) groups.push({ start: rd16(r, i), end: rd16(r, i + 2), uuid: uuidFromBytes(r.subarray(i + 4, i + len)) });
start = groups[groups.length - 1]!.end + 1;
}
assert.deepEqual(groups.map((g) => g.uuid), [0x1800, 0x1801, 0x180f].map(canonicalUuid).concat(["12345678-1234-5678-1234-56789abcdef0"]));
assert.deepEqual(groups.slice(0, 2).map((g) => [g.start, g.end]), [[1, 5], [6, 9]]);
// Find By Type Value finds a service by its UUID.
r = await m.att(h, [0x06, ...le16(1), ...le16(0xffff), ...le16(0x2800), ...le16(0x180f)]);
assert.deepEqual([...r], [0x07, ...le16(groups[2]!.start), ...le16(groups[2]!.end)]);
const all = await findAll(m, h);
const handleOf = (u: string | number, after = 0) => all.find((a) => a.uuid === canonicalUuid(u) && a.handle > after)!.handle;
// Characteristic declarations of the custom service.
const custom = groups[3]!;
r = await m.att(h, [0x08, ...le16(custom.start), ...le16(custom.end), ...le16(0x2803)]);
assert.equal(r[0], 0x09);
assert.equal(r[1], 2 + 1 + 2 + 16);
assert.equal(r[4], 0x0a, "read | write");
// GAP's device name is the device's, local.
r = await m.att(h, [0x0a, ...le16(3)]);
assert.equal(new TextDecoder().decode(r.subarray(1)), "Test");
// Battery level (a remote read), and by UUID (Read By Type).
const battery = handleOf(0x2a19);
assert.deepEqual([...(await m.att(h, [0x0a, ...le16(battery)]))], [0x0b, 50]);
assert.deepEqual([...(await m.att(h, [0x08, ...le16(1), ...le16(0xffff), ...le16(0x2a19)]))], [0x09, 3, ...le16(battery), 50]);
// A long value: Read, then Read Blob from the offset (the cached value).
const longH = handleOf("12345678-1234-5678-1234-56789abcdef1");
r = await m.att(h, [0x0a, ...le16(longH)]);
assert.equal(r.length, 1 + 300, "a 300-byte value fits the 517 MTU");
r = await m.att(h, [0x0c, ...le16(longH), ...le16(290)]);
assert.deepEqual([...r.subarray(1)], [290, 291, 292, 293, 294, 295, 296, 297, 298, 299].map((x) => x & 0xff));
r = await m.att(h, [0x0c, ...le16(longH), ...le16(301)]);
assert.deepEqual([...r], [0x01, 0x0c, ...le16(longH), 0x07], "Invalid Offset");
// A descriptor (remote) and a write, then a long write through Prepare and Execute.
assert.equal(new TextDecoder().decode((await m.att(h, [0x0a, ...le16(longH + 1)])).subarray(1)), "long");
assert.deepEqual([...(await m.att(h, [0x12, ...le16(longH), 1, 2, 3]))], [0x13]);
assert.deepEqual([...central.peripheral("test-peripheral")!.services[2]!.characteristics[0]!.value!], [1, 2, 3]);
r = await m.att(h, [0x16, ...le16(longH), ...le16(0), 9, 9]);
assert.deepEqual([...r], [0x17, ...le16(longH), ...le16(0), 9, 9]);
await m.att(h, [0x16, ...le16(longH), ...le16(2), 8]);
assert.deepEqual([...(await m.att(h, [0x18, 1]))], [0x19]);
assert.deepEqual([...central.peripheral("test-peripheral")!.services[2]!.characteristics[0]!.value!], [9, 9, 8]);
// Errors: insufficient authentication from the remote; writes to a read-only value; a bad handle.
const auth = handleOf("12345678-1234-5678-1234-56789abcdef3");
assert.deepEqual([...(await m.att(h, [0x0a, ...le16(auth)]))], [0x01, 0x0a, ...le16(auth), 0x05]);
assert.deepEqual([...(await m.att(h, [0x12, ...le16(battery), 1]))], [0x01, 0x12, ...le16(battery), 0x03]);
assert.deepEqual([...(await m.att(h, [0x0a, ...le16(0x0fff)]))], [0x01, 0x0a, ...le16(0x0fff), 0x01]);
assert.deepEqual([...(await m.att(h, [0x30]))], [0x01, 0x30, 0, 0, 0x06], "Request Not Supported");
// Notifications: the CCCD write subscribes; a write without response loops back as a notification.
const loop = handleOf("12345678-1234-5678-1234-56789abcdef4");
const loopCccd = all.find((a) => a.uuid === canonicalUuid(0x2902) && a.handle > loop)!.handle;
assert.deepEqual([...(await m.att(h, [0x12, ...le16(loopCccd), 1, 0]))], [0x13]);
assert.deepEqual([...(await m.att(h, [0x0a, ...le16(loopCccd)]))], [0x0b, 1, 0]);
assert.ok(central.calls.some((c) => c.op === "subscribe" && c.on));
m.l2cap(h, 4, [0x52, ...le16(loop), 0x41, 0x42]);
assert.deepEqual([...(await m.l2capIn(h, 4))], [0x1b, ...le16(loop), 0x41, 0x42], "Handle Value Notification");
// The remote notifies a battery level nobody subscribed to: nothing.
central.notify("test-peripheral", 0x2a19, Uint8Array.of(49));
// Indications: one at a time, the next after the confirmation.
const ind = handleOf("12345678-1234-5678-1234-56789abcdef2");
const indCccd = all.find((a) => a.uuid === canonicalUuid(0x2902) && a.handle > ind)!.handle;
assert.deepEqual([...(await m.att(h, [0x12, ...le16(indCccd), 1, 0]))], [0x01, 0x12, ...le16(indCccd), 0xfd], "notify on an indicate-only value");
assert.deepEqual([...(await m.att(h, [0x12, ...le16(indCccd), 2, 0]))], [0x13]);
central.notify("test-peripheral", "12345678-1234-5678-1234-56789abcdef2", Uint8Array.of(1));
central.notify("test-peripheral", "12345678-1234-5678-1234-56789abcdef2", Uint8Array.of(2));
assert.deepEqual([...(await m.l2capIn(h, 4))], [0x1d, ...le16(ind), 1]);
await sleep(20);
m.drain();
assert.ok(!m.pkts.some((p) => p.t === "acl"), "the second indication waits");
m.l2cap(h, 4, [0x1e]);
assert.deepEqual([...(await m.l2capIn(h, 4))], [0x1d, ...le16(ind), 2]);
m.l2cap(h, 4, [0x1e]);
// SMP: pairing is the host OS's; L2CAP: no credit-based channels.
m.l2cap(h, 6, [0x01, 0x03, 0x00, 0x01, 0x10, 0x07, 0x07]);
assert.deepEqual([...(await m.l2capIn(h, 6))], [0x05, 0x05], "Pairing Failed: Pairing Not Supported");
m.l2cap(h, 5, [0x14, 7, ...le16(10), ...le16(0x0080), ...le16(0x40), ...le16(247), ...le16(247), ...le16(10)]);
r = await m.l2capIn(h, 5);
assert.equal(r[0], 0x15);
assert.equal(r[1], 7);
assert.equal(rd16(r, 12), 0x0002, "SPSM not supported");
m.l2cap(h, 5, [0x0a, 8, ...le16(2), 1, 0]);
assert.deepEqual([...(await m.l2capIn(h, 5))], [0x01, 8, ...le16(2), 0, 0], "Command Reject");
});
test("flow control: Number of Completed Packets for every ACL packet", async () => {
const m = machine();
const central = new FakeGattCentral([testPeripheral()]);
await ready(m, new VirtualLeController({ central, log: () => {} }));
const h = await connect(m, "test-peripheral");
// A 300-byte write in 27-byte fragments: 12 ACL packets.
let sent = m.l2cap(h, 4, [0x12, ...le16(14), ...new Array(300).fill(7)], 27);
sent += m.l2cap(h, 4, [0x52, ...le16(14), 1], 27);
await m.l2capIn(h, 4);
let counted = 0;
for (let i = 0; i < 50 && counted < sent; i++) {
m.drain();
for (let j = m.pkts.length - 1; j >= 0; j--) {
const p = m.pkts[j]!;
if (p.t === "event" && p.code === 0x13) {
for (let k = 0; k < p.p[0]!; k++) {
assert.equal(rd16(p.p, 1 + k * 4), h);
counted += rd16(p.p, 3 + k * 4);
}
m.pkts.splice(j, 1);
}
}
await sleep(2);
}
assert.equal(counted, sent);
});
test("disconnects: the host's, the remote's, a failed connect, a cancel, a reset", async () => {
const m = machine();
const central = new FakeGattCentral([fakeDemoPeripheral(), { id: "bad", services: [], connectError: "out of range" }]);
const logs: string[] = [];
const ctl = new VirtualLeController({ central, log: (x) => logs.push(x) });
await ready(m, ctl);
let h = await connect(m, "unkernel-fake-peripheral");
assert.deepEqual(ctl.activity.connected, ["unkernel-fake-peripheral"]);
assert.deepEqual([...(await m.cmd(0x0406, [...le16(h), 0x13]))], [0]);
let dc = await m.event(0x05);
assert.deepEqual([...dc.p], [0, ...le16(h), 0x16], "Disconnection Complete: terminated by the local host");
assert.equal(central.connected("unkernel-fake-peripheral"), false);
assert.deepEqual([...(await m.cmd(0x0406, [...le16(h), 0x13]))], [0x02], "Unknown Connection Identifier");
// The remote drops the link.
h = await connect(m, "unkernel-fake-peripheral");
central.disconnectRemote("unkernel-fake-peripheral");
dc = await m.event(0x05);
assert.deepEqual([...dc.p], [0, ...le16(h), 0x13], "Remote User Terminated Connection");
// A device that cannot be reached.
const addr = deviceAddress("bad");
const p = [...le16(0x60), ...le16(0x30), 0, 1, ...addr, 0, ...le16(24), ...le16(40), ...le16(0), ...le16(500), 0, 0, 0, 0];
assert.deepEqual([...(await m.cmd(0x200d, p))], [0]);
assert.equal((await m.le(0x01)).p[1], 0x3e, "Connection Failed to be Established");
assert.ok(logs.some((l) => l.includes("out of range")));
// An unknown device: the request waits until cancelled.
const q = [...le16(0x60), ...le16(0x30), 0, 1, 1, 2, 3, 4, 5, 0xc6, 0, ...le16(24), ...le16(40), ...le16(0), ...le16(500), 0, 0, 0, 0];
assert.deepEqual([...(await m.cmd(0x200d, q))], [0]);
assert.deepEqual([...(await m.cmd(0x200d, q))], [0x0c], "one at a time");
assert.deepEqual([...(await m.cmd(0x200e))], [0]);
assert.equal((await m.le(0x01)).p[1], 0x02, "cancelled: Unknown Connection Identifier");
assert.deepEqual([...(await m.cmd(0x200e))], [0x0c], "nothing to cancel");
// A reset drops links without events.
h = await connect(m, "unkernel-fake-peripheral");
await m.cmd(0x0c03);
assert.equal(central.connected("unkernel-fake-peripheral"), false);
await sleep(20);
m.drain();
assert.ok(!m.pkts.some((x) => x.t === "event" && x.code === 0x05));
// So does a detach (the guest's hci0 goes with its connections).
h = await connect(m, "unkernel-fake-peripheral");
await m.host.detach();
assert.equal(central.connected("unkernel-fake-peripheral"), false);
});
test("worker split: the kernel's end and the controller across a MessageChannel", async () => {
const memory = new WebAssembly.Memory({ initial: 32 });
const u8 = () => new Uint8Array(memory.buffer);
const { port1: kernelSide, port2: ownerSide } = new MessageChannel();
const host = new BluetoothHost({ send: (ops) => ownerSide.postMessage({ t: "bt", ops }) });
hosts.push(host);
// The worker's batching: one message per microtask, packet data transferred.
let out: BtDown[] = [];
const dev = new BluetoothDevice({
enabled: true, memory: () => memory, raise: () => {},
send: (m) => {
if (out.push(m) === 1) queueMicrotask(() => {
const batch = out;
out = [];
kernelSide.postMessage({ t: "bt", ops: batch }, btTransfer(batch));
});
},
});
ownerSide.onmessage = (e: MessageEvent) => { for (const m of e.data.ops) host.receive(m); };
kernelSide.onmessage = (e: MessageEvent) => { for (const m of e.data.ops) dev.receive(m); };
const k = dev.imports() as unknown as Imports;
try {
assert.equal(k.wasm_driver_bt_init(), 1);
const central = new FakeGattCentral([fakeDemoPeripheral()]);
await host.attach(new VirtualLeController({ central, log: () => {} }));
let id = 0;
await until("the attach crossed", () => (id = k.wasm_driver_bt_status() >>> 16) !== 0);
assert.equal(k.wasm_driver_bt_open(id), 0);
const send = (b: number[]) => {
u8().set(b, BUF);
return k.wasm_driver_bt_send(id, BigInt(BUF), b.length);
};
const recv = async (): Promise<Uint8Array> => {
let n = 0;
await until("a packet", () => (n = k.wasm_driver_bt_rx_len(id)) > 0);
k.wasm_driver_bt_recv(id, BigInt(OUT), n);
return u8().slice(OUT, OUT + n);
};
assert.equal(send([1, 3, 0x0c, 0]), 0);
assert.deepEqual([...(await recv())], [4, 0x0e, 4, 1, 3, 0x0c, 0], "Reset's Command Complete crossed back");
assert.equal(send([1, 9, 0x10, 0]), 0);
const bd = await recv();
assert.equal(bd[6], 0, "Read BD_ADDR: success");
assert.equal(host.stats.packetsIn, 2);
} finally {
kernelSide.close();
ownerSide.close();
}
});
test("H4StreamController: a controller's H4 over a byte stream (here a VirtualLeController behind it)", async () => {
// The far end: a VirtualLeController fed by an H4 parser, as a UART controller would answer.
const central = new FakeGattCentral([fakeDemoPeripheral()]);
const far = new VirtualLeController({ central, log: () => {} });
let toHost!: ReadableStreamDefaultController<Uint8Array>;
const framer = new H4Framer();
far.attach({
packet: (p) => {
// Split each packet across chunks, as a serial port delivers bytes.
const cut = Math.max(1, p.length >> 1);
toHost.enqueue(p.slice(0, cut));
toHost.enqueue(p.slice(cut));
},
lost: () => {},
});
let closed = false;
const stream = {
readable: new ReadableStream<Uint8Array>({ start: (c) => { toHost = c; } }),
writable: new WritableStream<Uint8Array>({ write: (chunk) => { for (const p of framer.push(chunk)) far.send(p); } }),
};
const ctl = new H4StreamController({ open: async () => stream, close: async () => { closed = true; }, label: "test UART" });
assert.equal(ctl.bus, "uart");
const m = machine();
assert.equal(m.k.wasm_driver_bt_init(), 1);
await m.host.attach(ctl);
await until("attach", () => (m.status() >>> 16) !== 0);
assert.equal(m.k.wasm_driver_bt_info(m.id), 3, "HCI_UART");
assert.deepEqual([...(await m.cmd(0x0c03))], [0]);
assert.equal((await m.cmd(0x1002)).length, 65, "a 68-byte event across two chunks");
const h = await connect(m, "unkernel-fake-peripheral");
const r = await m.att(h, [0x0a, ...le16(3)]);
assert.equal(new TextDecoder().decode(r.subarray(1)), "unkernel fake");
await m.host.detach();
assert.ok(closed, "the stream was closed");
});