@clothespin/pi-pippi 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ble.ts ADDED
@@ -0,0 +1,1062 @@
1
+ /**
2
+ * BLE transport over BlueZ, in this process.
3
+ *
4
+ * The pippi speaks Nordic UART: a write characteristic the bridge pushes JSON
5
+ * lines at, and a notify characteristic it answers on. BlueZ exposes both as
6
+ * D-Bus objects, so this file is a client of the system bus -- `bluez.ts` is the
7
+ * wire format, and there is no third language and no child process anywhere in
8
+ * the path from a tool call to the pet.
9
+ *
10
+ * That is deliberate. The alternative that used to live here spawned a Python
11
+ * worker, and the worker bought three things that all had to be paid for again
12
+ * on this side of the pipe: a second claim protocol, because the board in
13
+ * claims.ts is TypeScript and a worker cannot read it; a second copy of every
14
+ * number, because `PI_PIPPI_RECLAIM` means nothing to a process with no idea
15
+ * what a session is; and a process boundary that could die on its own terms,
16
+ * which is a failure mode nobody outside this file can reason about. A crash in
17
+ * here is an ordinary rejected promise.
18
+ *
19
+ * What had to survive from the Python worker is the knowledge, most of it about
20
+ * ownership rather than radio:
21
+ *
22
+ * - A connection belongs to the adapter, not to whoever opened it, and a
23
+ * connected peripheral stops advertising. Another window's pippi is not busy,
24
+ * it is unreachable, so taking it back means disconnecting whoever holds it.
25
+ * - Whether this session may reconnect at all is a question about a directory
26
+ * of stamps, asked before the attempt and never after it.
27
+ * - BlueZ reports a dropped link by signal or not at all, and a write that
28
+ * cannot land is the other half of the news.
29
+ */
30
+
31
+ import { setTimeout as delay } from "node:timers/promises";
32
+
33
+ import { BluezBus, DBusError, type Incoming } from "./bluez.ts";
34
+ import { ClaimBoard } from "./claims.ts";
35
+ import { parseDeviceLine } from "./protocol.ts";
36
+ import {
37
+ ListenerBase,
38
+ WireTap,
39
+ type BridgeTransport,
40
+ type ScanResult,
41
+ type TransportState,
42
+ } from "./transport.ts";
43
+
44
+ // --------------------------------------------------------------------------- ids
45
+
46
+ /** How long ATT flow control is worth waiting out before the frame is abandoned. */
47
+ const WRITE_RETRY_LIMIT = 25;
48
+
49
+ const NUS_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
50
+ const NUS_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
51
+ const NUS_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
52
+
53
+ const ADAPTER = "/org/bluez/hci0";
54
+ const DEVICE_IFACE = "org.bluez.Device1";
55
+ const ADAPTER_IFACE = "org.bluez.Adapter1";
56
+ const SERVICE_IFACE = "org.bluez.GattService1";
57
+ const CHAR_IFACE = "org.bluez.GattCharacteristic1";
58
+ const PROPS_IFACE = "org.freedesktop.DBus.Properties";
59
+ const OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager";
60
+
61
+ /** ATT_MTU before anything is known: three bytes of ATT header. */
62
+ const DEFAULT_MTU = 23;
63
+ /** The floor every BLE stack must answer, so a chunk this size always fits. */
64
+ const MIN_ATT_PAYLOAD = 20;
65
+ /** A link shorter than this never really worked, so the dial after it backs off. */
66
+ const FAST_DROP_MS = 2_000;
67
+ /**
68
+ * How long the dial loop may keep trying without ever getting a link. The backoff
69
+ * below bounds how loud the loop is; this bounds how long it is allowed to be
70
+ * wrong. A host that is powered off is not going to answer the two-hundredth dial,
71
+ * and a transport that asks every fifteen seconds until the process exits is not a
72
+ * policy but a leak -- it also leaves the human looking at "connecting" forever
73
+ * when the truthful answer is "I cannot reach it".
74
+ */
75
+ const DIAL_BUDGET_MS = 90_000;
76
+ /** A device that talks without ever finishing a line is broken; stop buffering. */
77
+ const MAX_RX_BUFFER = 4096;
78
+
79
+ const ADDRESS = /^[0-9A-F]{2}(?::[0-9A-F]{2}){5}$/;
80
+
81
+ const BLUEZ_TIMEOUT = Symbol("bluez timeout");
82
+
83
+ // --------------------------------------------------------------------------- bus
84
+
85
+ export interface BusRequest {
86
+ destination: string;
87
+ path: string;
88
+ interface: string;
89
+ member: string;
90
+ signature?: string;
91
+ args?: unknown[];
92
+ /** ms; the call rejects with a `bluez timeout` sentinel when it runs out. */
93
+ timeoutMs?: number;
94
+ }
95
+
96
+ export interface BusReply {
97
+ body: unknown[];
98
+ }
99
+
100
+ export interface BusSignal {
101
+ path: string;
102
+ interface?: string;
103
+ member?: string;
104
+ body: unknown[];
105
+ }
106
+
107
+ /**
108
+ * The slice of a D-Bus client this transport needs: ask a question, register for
109
+ * signals, hang up. Tests answer these themselves, which is the only way the
110
+ * ownership logic in here is testable without a radio and a system bus.
111
+ */
112
+ export interface BleBus {
113
+ connect(): Promise<void>;
114
+ close(): void;
115
+ call(request: BusRequest): Promise<BusReply>;
116
+ addMatch(rule: string): Promise<void>;
117
+ signals(listener: (signal: BusSignal) => void): () => void;
118
+ /**
119
+ * Fires when the socket goes away on its own -- bluetoothd restarted, say. The
120
+ * match rule went with it, so anything waiting on a signal should give up and the
121
+ * next attempt has to redo the handshake.
122
+ */
123
+ disconnected(listener: () => void): () => void;
124
+ }
125
+
126
+ /** BluezBus, seen through `BleBus`. */
127
+ export class BluezBusAdapter implements BleBus {
128
+ private readonly bus: BluezBus;
129
+
130
+ constructor(bus?: BluezBus) {
131
+ this.bus = bus ?? new BluezBus();
132
+ }
133
+
134
+ connect(): Promise<void> {
135
+ return this.bus.connect();
136
+ }
137
+
138
+ close(): void {
139
+ this.bus.close();
140
+ }
141
+
142
+ async call(request: BusRequest): Promise<BusReply> {
143
+ const call: Promise<Incoming> = this.bus.call({
144
+ destination: request.destination,
145
+ path: request.path,
146
+ interface: request.interface,
147
+ member: request.member,
148
+ signature: request.signature,
149
+ args: request.args,
150
+ });
151
+ // BluezBus reports its own timeout as a rejected Error; making it a distinct
152
+ // value is what lets a caller tell "nobody answered" from "answered no".
153
+ const timeout = request.timeoutMs
154
+ ? new Promise<never>((_, reject) => {
155
+ const timer = setTimeout(() => reject(BLUEZ_TIMEOUT), request.timeoutMs);
156
+ timer.unref?.();
157
+ })
158
+ : undefined;
159
+ const reply = await (timeout ? Promise.race([call, timeout]) : call);
160
+ return { body: reply.body };
161
+ }
162
+
163
+ addMatch(rule: string): Promise<void> {
164
+ return this.bus.addMatch(rule);
165
+ }
166
+
167
+ signals(listener: (signal: BusSignal) => void): () => void {
168
+ const wrapped = (signal: Incoming): void => {
169
+ listener({
170
+ // A D-Bus message always has a path; the wire layer types it optional
171
+ // because a malformed frame might not, and a signal without one is noise
172
+ // rather than something this transport can route.
173
+ path: signal.path ?? "",
174
+ interface: signal.interface,
175
+ member: signal.member,
176
+ body: signal.body,
177
+ });
178
+ };
179
+ this.bus.on("signal", wrapped);
180
+ return () => this.bus.off("signal", wrapped);
181
+ }
182
+
183
+ disconnected(listener: () => void): () => void {
184
+ this.bus.on("disconnected", listener);
185
+ return () => this.bus.off("disconnected", listener);
186
+ }
187
+ }
188
+
189
+ // ---------------------------------------------------------------------- framing
190
+
191
+ /**
192
+ * Notifications are ATT fragments, not messages: one JSON line routinely arrives
193
+ * as two notifications and one notification can finish one line and start the
194
+ * next. Splitting on LF is the whole job, and the ceiling is what stops a device
195
+ * that never sends a newline from growing this buffer until the bridge dies.
196
+ */
197
+ class LineFramer {
198
+ private buffer = "";
199
+ private overflowed = false;
200
+
201
+ /** Complete lines, in order. Empty ones are not returned. */
202
+ push(chunk: string): string[] {
203
+ this.buffer += chunk;
204
+ if (this.buffer.length > MAX_RX_BUFFER) {
205
+ this.buffer = "";
206
+ this.overflowed = true;
207
+ return [];
208
+ }
209
+ this.overflowed = false;
210
+ const lines: string[] = [];
211
+ for (;;) {
212
+ const at = this.buffer.indexOf("\n");
213
+ if (at < 0) break;
214
+ const line = this.buffer.slice(0, at).replace(/\r$/, "");
215
+ this.buffer = this.buffer.slice(at + 1);
216
+ if (line.length > 0) lines.push(line);
217
+ }
218
+ return lines;
219
+ }
220
+
221
+ /** True on the call that dropped a buffer for want of a newline. */
222
+ get didOverflow(): boolean {
223
+ return this.overflowed;
224
+ }
225
+
226
+ reset(): void {
227
+ this.buffer = "";
228
+ }
229
+ }
230
+
231
+ // ------------------------------------------------------------------- transport
232
+
233
+ export interface BleTransportOptions {
234
+ bus?: BleBus;
235
+ /** The shared board that decides which session may hold the radio. */
236
+ board?: ClaimBoard;
237
+ /** Device: address or name. The last thing a human named wins over a default. */
238
+ device?: string;
239
+ connectTimeoutMs?: number;
240
+ scanTimeoutMs?: number;
241
+ /** How long the dial loop may go without a link before it stops and says so. */
242
+ dialBudgetMs?: number;
243
+ /** Every frame in both directions, appended here. $PI_PIPPI_WIRE_LOG by default. */
244
+ wireLogPath?: string;
245
+ /** Only advertise-matches by service UUID unless a name starts with this. */
246
+ namePrefix?: string;
247
+ log?: (level: "info" | "warn" | "error", message: string) => void;
248
+ }
249
+
250
+ interface Peer {
251
+ path: string;
252
+ address: string;
253
+ name: string;
254
+ connected: boolean;
255
+ }
256
+
257
+ /**
258
+ * One pippi, reached over the system bus.
259
+ *
260
+ * `connect()` resolves when a link and a notification subscription exist, and
261
+ * stays resolved: the loop behind it keeps the link up until the board says
262
+ * another window has a better claim, which is the difference between a pet that
263
+ * comes back after a reset and one that waits for a keystroke.
264
+ */
265
+ export class BluezTransport extends ListenerBase implements BridgeTransport {
266
+ readonly kind = "ble";
267
+ state: TransportState = { connected: false };
268
+
269
+ private readonly bus: BleBus;
270
+ private board: ClaimBoard;
271
+ private readonly connectTimeoutMs: number;
272
+ private readonly dialBudgetMs: number;
273
+ private readonly scanTimeoutMs: number;
274
+ private readonly namePrefix: string;
275
+ private readonly logger?: (level: "info" | "warn" | "error", message: string) => void;
276
+ private framer = new LineFramer();
277
+ /** Every frame in both directions, when $PI_PIPPI_WIRE_LOG names a file. */
278
+ private readonly tap: WireTap;
279
+ private attPayload = MIN_ATT_PAYLOAD;
280
+ private target?: string;
281
+ private peer?: Peer;
282
+ private rxChar?: string;
283
+ private txChar?: string;
284
+ private linkTask?: Promise<void>;
285
+ /** Set once per gap in the ATT channel, so a keepalive cannot shout about it. */
286
+ private reportedWriteGap = false;
287
+ private stopLink: (() => void) | undefined;
288
+ /** Set when the bus, not the radio, is what ended the last link. */
289
+ private busGone = false;
290
+ /** Consecutive failed dial attempts, which is what the next wait is drawn from. */
291
+ private dialFails = 0;
292
+ private retryStartedAt = 0;
293
+ private linkUpAt = 0;
294
+ private closing = false;
295
+ private started?: Promise<void>;
296
+ /**
297
+ * One ATT write in flight, in the order the bridge produced them.
298
+ *
299
+ * BlueZ answers a second `WriteValue` on a characteristic while one is still
300
+ * outstanding with `org.bluez.Error.InProgress`, and the bridge writes whenever
301
+ * a snapshot is due -- so without a queue here, an ordinary busy session spends
302
+ * its life tripping over itself and reporting a dead link that is fine.
303
+ */
304
+ private writeQueue: string[] = [];
305
+ private writing = false;
306
+ private unsubscribes: Array<() => void> = [];
307
+
308
+ constructor(options: BleTransportOptions = {}) {
309
+ super();
310
+ this.bus = options.bus ?? new BluezBusAdapter();
311
+ this.board = options.board ?? new ClaimBoard();
312
+ this.target = options.device ?? process.env.PI_PIPPI_DEVICE;
313
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 25_000;
314
+ this.scanTimeoutMs = options.scanTimeoutMs ?? 8_000;
315
+ this.dialBudgetMs = options.dialBudgetMs ?? DIAL_BUDGET_MS;
316
+ this.namePrefix = options.namePrefix ?? "";
317
+ this.tap = new WireTap(options.wireLogPath ?? process.env.PI_PIPPI_WIRE_LOG);
318
+ this.logger = options.log;
319
+ }
320
+
321
+ /**
322
+ * What the transport noticed, said twice: as an event, which is how the bridge
323
+ * (and a test) hears about it, and to whatever logger the caller supplied.
324
+ *
325
+ * Doing only the second is how a real pi session ends up silent about a radio
326
+ * that is misbehaving: `bridgeLog` shows the human `error` level and nothing
327
+ * else, so anything reported out-of-band is invisible unless it also travels on
328
+ * the event channel the bridge reads.
329
+ */
330
+ private log(level: "info" | "warn" | "error", message: string): void {
331
+ this.emit({ type: "log", level, message });
332
+ this.logger?.(level, message);
333
+ }
334
+
335
+ /** The board this transport consults -- exposed so a caller can share its own. */
336
+ get claims(): ClaimBoard {
337
+ return this.board;
338
+ }
339
+
340
+ /**
341
+ * Point this transport at somebody else's board.
342
+ *
343
+ * The bridge owns the board, because a stamp is a fact about a human decision
344
+ * and the bridge is where those arrive; a transport built before the bridge was
345
+ * configured cannot be the one holding it. Two boards in one process would each
346
+ * remember writing the mask, and the point of the mask is that only one session
347
+ * has a question on the pet.
348
+ */
349
+ setClaimBoard(board: ClaimBoard): void {
350
+ this.board = board;
351
+ }
352
+
353
+ async start(): Promise<void> {
354
+ this.closing = false;
355
+ this.started ??= this.startOnce();
356
+ return this.started;
357
+ }
358
+
359
+ private async startOnce(): Promise<void> {
360
+ await this.bus.connect();
361
+ // Without a match rule the bus delivers nothing at all -- not an error, just
362
+ // silence, which is the most confusing failure this file can have.
363
+ await this.bus.addMatch(`type='signal',sender='org.bluez'`);
364
+ this.unsubscribes.push(this.bus.signals((signal) => this.onSignal(signal)));
365
+ // A match rule belongs to a connection, and so does the ACL link: bluetoothd
366
+ // gets restarted by packaging updates, and a transport that kept the memoized
367
+ // handshake would spend the rest of the session asking a closed socket -- which
368
+ // it reports as a missing pippi, the most misleading wrong answer available here.
369
+ this.unsubscribes.push(
370
+ this.bus.disconnected(() => {
371
+ if (this.closing) return;
372
+ this.busGone = true;
373
+ this.started = undefined;
374
+ this.log("warn", "dbus connection lost; the link went with it");
375
+ this.stopLink?.();
376
+ }),
377
+ );
378
+ this.emit({ type: "log", level: "info", message: `BLE ready (bluez, board ${this.board.dirPath})` });
379
+ }
380
+
381
+ /**
382
+ * Re-dial the bus if it died since the last attempt. Called at the top of every
383
+ * link attempt rather than by the failure sites, because the only thing a caller
384
+ * can do about a dead bus is try again with a live one.
385
+ */
386
+ private async ensureBus(): Promise<void> {
387
+ if (this.started) return;
388
+ this.busGone = false;
389
+ await this.start();
390
+ this.log("info", "dbus connection re-established");
391
+ }
392
+
393
+ // -------------------------------------------------------------- connections
394
+
395
+ async connect(target?: string): Promise<void> {
396
+ await this.start();
397
+ await this.begin(target ?? this.target, false);
398
+ }
399
+
400
+ async claim(target?: string): Promise<void> {
401
+ await this.start();
402
+ await this.begin(target ?? this.target, true);
403
+ }
404
+
405
+ /**
406
+ * Point the link loop at a device, optionally taking the link from whoever holds it.
407
+ *
408
+ * Nothing here stamps the board, and that is load-bearing. The board is the whole of
409
+ * who owns the pippi -- a claim is derived from it, not from this method's opinion --
410
+ * so the only thing that may move a stamp is the decision that caused this call:
411
+ * `noteUserInput`, `/pippi connect`, an approval. This method is also how an
412
+ * unattended reconnect arrives, and a loop that dated its own claim would find itself
413
+ * newest every time it looked. Nine hand-overs in 56 seconds was not two windows
414
+ * disagreeing about the board; it was each of them re-awarding itself the pippi
415
+ * between looks, which is what a stamp moved by a retry instead of a human means.
416
+ */
417
+ private async begin(target: string | undefined, takeOver: boolean): Promise<void> {
418
+ // A link we already have is the answer to the same question; re-asking it
419
+ // would tear down a working connection to build the connection we have.
420
+ if (this.state.connected && (!target || this.state.address === target.toUpperCase())) return;
421
+ const found = target ?? (await this.autotarget());
422
+ if (!found) {
423
+ this.fail("no pippi device found; run /pippi scan");
424
+ return;
425
+ }
426
+ this.target = found;
427
+ this.retryStartedAt = 0;
428
+ if (takeOver) await this.releaseLink(found);
429
+ this.restartLink();
430
+ // Return once the link is actually up: a caller that sees success and then
431
+ // reads `connected: false` would conclude the pippi is gone.
432
+ await this.linkUp();
433
+ }
434
+
435
+ /** No device named: look for one, and use it if there is exactly one candidate. */
436
+ private async autotarget(): Promise<string | undefined> {
437
+ const results = await this.scan(4_000, { quiet: true });
438
+ if (results.length === 0) return undefined;
439
+ const first = results[0]!;
440
+ this.log("info", `auto-selected ${first.name || first.address}`);
441
+ return first.address;
442
+ }
443
+
444
+ private waiters = new Set<{ resolve: () => void; reject: (error: Error) => void }>();
445
+
446
+ private linkUp(): Promise<void> {
447
+ if (this.state.connected) return Promise.resolve();
448
+ return new Promise<void>((resolve, reject) => {
449
+ const waiter = {
450
+ resolve: () => {
451
+ this.waiters.delete(waiter);
452
+ resolve();
453
+ },
454
+ reject: (error: Error) => {
455
+ this.waiters.delete(waiter);
456
+ reject(error);
457
+ },
458
+ };
459
+ this.waiters.add(waiter);
460
+ const timer = setTimeout(() => {
461
+ this.waiters.delete(waiter);
462
+ reject(new Error(this.state.error ? `link failed: ${this.state.error}` : "no link"));
463
+ }, this.connectTimeoutMs);
464
+ timer.unref?.();
465
+ });
466
+ }
467
+
468
+ private restartLink(): void {
469
+ this.stopLink?.();
470
+ const task = (async () => {
471
+ while (!this.closing) {
472
+ await this.ensureBus();
473
+ const outcome = await this.holdLink();
474
+ // "bus" is not a human letting go: the socket died under us, and the pippi
475
+ // is almost certainly still advertising. Re-dial both.
476
+ if (this.closing || (outcome === "stopped" && !this.busGone)) return;
477
+ // We held the link, so losing it was ours to answer -- but the board
478
+ // decides whether anyone gets to take it back. After a claim that landed
479
+ // in another window, waiting IS the policy, because a reconnect attempt
480
+ // here would disconnect whoever holds the radio now.
481
+ if (!this.board.check().allowed) {
482
+ this.emit({
483
+ type: "claim_lost",
484
+ holder: this.board.leader(),
485
+ target: this.target,
486
+ });
487
+ this.log("info", "not reconnecting: another session touched the pippi more recently");
488
+ return;
489
+ }
490
+ if (this.outOfBudget()) return;
491
+ }
492
+ })();
493
+ this.linkTask = task;
494
+ }
495
+
496
+ /**
497
+ * Size the ATT writes off the negotiated MTU. 20 bytes is the floor, not the plan:
498
+ * BlueZ reports 23 until the exchange has happened, so this is called again whenever
499
+ * the property moves (see `onSignal`).
500
+ */
501
+ private setAttPayload(raw: unknown): void {
502
+ const next = Math.max(MIN_ATT_PAYLOAD, (Number(raw) || DEFAULT_MTU) - 3);
503
+ if (next === this.attPayload) return;
504
+ this.attPayload = next;
505
+ if (this.state.connected && this.state.mtu !== Number(raw)) {
506
+ this.setState({ ...this.state, mtu: Number(raw) || undefined });
507
+ }
508
+ }
509
+
510
+ /** One connect attempt and the wait until it ends. */
511
+ private async holdLink(): Promise<"dropped" | "stopped" | "bus"> {
512
+ const target = this.target!;
513
+ try {
514
+ if (this.closing) return "stopped";
515
+ const peer = await this.findPeer(target);
516
+ if (!peer) {
517
+ this.fail(`no BlueZ device for ${target}; run /pippi scan`);
518
+ await delay(this.nextDialDelay());
519
+ return "dropped";
520
+ }
521
+ this.peer = peer;
522
+ await this.bus
523
+ .call({ destination: "org.bluez", path: peer.path, interface: DEVICE_IFACE, member: "Connect", timeoutMs: this.connectTimeoutMs })
524
+ .catch((error) => {
525
+ if (!alreadyConnected(error)) throw error;
526
+ });
527
+ const chars = await this.findCharacteristics(peer.path);
528
+ if (!chars.tx || !chars.rx) {
529
+ this.fail(`${peer.address} has no Nordic UART service`);
530
+ await delay(this.nextDialDelay());
531
+ return "dropped";
532
+ }
533
+ this.txChar = chars.tx;
534
+ this.rxChar = chars.rx;
535
+ this.reportedWriteGap = false;
536
+ this.framer = new LineFramer();
537
+ await this.bus
538
+ .call({ destination: "org.bluez", path: chars.tx, interface: CHAR_IFACE, member: "StartNotify" })
539
+ .catch((error) => this.log("warn", `subscribe to TX characteristic failed: ${describe(error)}`));
540
+ // MTU is read after the subscribe rather than before it, and again from signals
541
+ // below, because it is not known when the connect returns: the exchange happens
542
+ // with the first traffic, and a value latched here would be the 23-byte default
543
+ // for the life of a link that ends up carrying 517. That is not cosmetic -- a
544
+ // 200-byte command is ten ATT round trips at 20 bytes and one at 514.
545
+ const mtu = await this.property<number>(CHAR_IFACE, "MTU", chars.tx).catch(() => DEFAULT_MTU);
546
+ this.setAttPayload(mtu);
547
+ this.dialFails = 0;
548
+ this.retryStartedAt = 0;
549
+ this.linkUpAt = Date.now();
550
+ this.setState({
551
+ connected: true,
552
+ address: peer.address,
553
+ name: peer.name || undefined,
554
+ mtu: Number(mtu) || undefined,
555
+ });
556
+ const dropped = await this.waitForDrop(peer.path);
557
+ this.peer = undefined;
558
+ this.framer.reset();
559
+ if (dropped === "stopped") return this.busGone ? "bus" : "stopped";
560
+ this.setState({ connected: false, address: peer.address });
561
+ // A link that died the moment it came up is a failure, not a fresh start: without
562
+ // this, a device that accepts a connection and hangs up again at once yields one
563
+ // connect and one disconnect as fast as BlueZ will answer, forever.
564
+ if (Date.now() - this.linkUpAt < FAST_DROP_MS) await delay(this.nextDialDelay());
565
+ return "dropped";
566
+ } catch (error) {
567
+ if (this.closing) return "stopped";
568
+ if (isAuthFailure(error)) return this.staleBond(this.peer?.address ?? target, error);
569
+ this.setState({ connected: false, address: target, error: describe(error) });
570
+ await delay(this.nextDialDelay());
571
+ return "dropped";
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Stop dialing, and tell the one person who can fix this what to type.
577
+ *
578
+ * Every other failure comes back on its own -- a pippi asleep, out of range,
579
+ * behind a wedged adapter -- and that is what the retry ladder and the dial
580
+ * budget are for. A stale bond does not. The panel discarded its key; we are
581
+ * presenting an old one; pairing is attempted and refused identically forever,
582
+ * and each refusal makes the board print a six-digit passkey into an empty room.
583
+ * Nothing the bridge holds can delete a kernel LTK, so the loop is the bug and
584
+ * the sentence is the fix. Pressing Enter runs `claim` again, which restarts
585
+ * dialing: stopping here costs nothing the human cannot undo.
586
+ */
587
+ private staleBond(address: string, error: unknown): "stopped" {
588
+ const message =
589
+ `pairing with ${address} was refused (${describe(error)}): this host presents a key the panel no ` +
590
+ `longer has. Fix it with \`bluetoothctl remove ${address}\`, pair again, and type the six-digit ` +
591
+ `passkey the panel shows. Not retrying until then.`;
592
+ this.setState({ connected: false, address, error: message });
593
+ this.emit({ type: "bond_stale", address });
594
+ this.log("error", message);
595
+ return "stopped";
596
+ }
597
+
598
+ /**
599
+ * How long before the next dial. A pippi that is asleep or gone fails the same way
600
+ * forever, and a fixed one-second retry is a permanent one-hertz conversation with
601
+ * BlueZ that never thins out; doubling to a ceiling keeps the first tries responsive
602
+ * (a pippi that was reset is back within seconds) and makes the hundredth cheap.
603
+ */
604
+ private nextDialDelay(): number {
605
+ this.dialFails++;
606
+ if (this.retryStartedAt === 0) this.retryStartedAt = Date.now();
607
+ return Math.min(1_000 * 2 ** Math.min(this.dialFails - 1, 4), 15_000);
608
+ }
609
+
610
+ /**
611
+ * Give up, once, out loud. The remedy for a pippi that will not answer is not
612
+ * more dials; it is a human, and the only thing a human can do here is press
613
+ * Enter. So the loop says the bad sentence, leaves the failure in the state for
614
+ * the status line to show, and stops -- and the next Enter finds the retry
615
+ * ladder rebuilt from scratch, because a person who presses it has a reason
616
+ * the last ninety seconds did not have.
617
+ */
618
+ private outOfBudget(): boolean {
619
+ if (this.retryStartedAt === 0) return false;
620
+ const spent = Date.now() - this.retryStartedAt;
621
+ if (spent < this.dialBudgetMs) return false;
622
+ this.retryStartedAt = 0;
623
+ this.setState({
624
+ connected: false,
625
+ address: this.target,
626
+ error: `pippi not reachable after ${Math.round(spent / 1000)}s`,
627
+ });
628
+ this.log("warn", `pippi did not answer in ${Math.round(spent / 1000)}s; press Enter here to try again`);
629
+ return true;
630
+ }
631
+
632
+ /** Resolves when the link goes, or when the loop is told to stop. */
633
+ private waitForDrop(peerPath: string): Promise<"dropped" | "stopped"> {
634
+ return new Promise((resolve) => {
635
+ let done = false;
636
+ const finish = (why: "dropped" | "stopped") => {
637
+ if (done) return;
638
+ done = true;
639
+ off();
640
+ this.stopLink = undefined;
641
+ resolve(why);
642
+ };
643
+ const off = this.bus.signals((signal) => {
644
+ if (signal.interface !== PROPS_IFACE || signal.member !== "PropertiesChanged") return;
645
+ if (signal.path !== peerPath) return;
646
+ const changed = signal.body[1] as Record<string, unknown> | undefined;
647
+ if (changed && "Connected" in changed && !changed.Connected) finish("dropped");
648
+ });
649
+ this.stopLink = () => finish("stopped");
650
+ });
651
+ }
652
+
653
+ private onSignal(signal: BusSignal): void {
654
+ if (signal.interface === PROPS_IFACE && signal.member === "PropertiesChanged") {
655
+ const changed = signal.body[1] as Record<string, unknown> | undefined;
656
+ if (!changed) return;
657
+ // The negotiated MTU arrives here whenever it changes, which on this stack is
658
+ // after the connect that reported 23. Writes are chunked off this, so ignoring it
659
+ // means writing to a 517-byte link as though it were still a 23-byte one.
660
+ if ("MTU" in changed && signal.path === this.txChar) this.setAttPayload(changed.MTU);
661
+ const value = changed["Value"];
662
+ if (value instanceof Buffer || Buffer.isBuffer(value)) {
663
+ for (const line of this.framer.push(String(value))) {
664
+ this.tap.record("rx", line);
665
+ const parsed = parseDeviceLine(line);
666
+ if (parsed) this.emit({ type: "line", line: parsed });
667
+ else this.emit({ type: "log", level: "warn", message: `non-JSON from device: ${line.slice(0, 120)}` });
668
+ }
669
+ if (this.framer.didOverflow) {
670
+ this.log("warn", `rx buffer overflow; dropping ${MAX_RX_BUFFER}+ bytes`);
671
+ }
672
+ return;
673
+ }
674
+ if (DEVICE_IFACE in changed && "Connected" in changed && !this.linkTask) {
675
+ // A link we never asked about: nothing to reconnect, but a stale
676
+ // "connected" would be a lie.
677
+ this.setState({ connected: false, address: this.state.address });
678
+ }
679
+ return;
680
+ }
681
+ if (signal.interface === "org.freedesktop.DBus.ObjectManager" && signal.member === "InterfacesRemoved") {
682
+ const gone = signal.body[1] as string[];
683
+ if (gone.includes(DEVICE_IFACE) && signal.path === this.peer?.path) {
684
+ this.setState({ connected: false, address: this.peer.address });
685
+ }
686
+ }
687
+ }
688
+
689
+ // -------------------------------------------------------------- discovery
690
+
691
+ async scan(timeoutMs?: number, options: { quiet?: boolean } = {}): Promise<ScanResult[]> {
692
+ await this.start().catch(() => undefined);
693
+ const ms = timeoutMs ?? this.scanTimeoutMs;
694
+ const found = new Map<string, ScanResult>();
695
+ const collect = async () => {
696
+ for (const peer of await this.peersWithUart()) {
697
+ if (!this.matchesName(peer)) continue;
698
+ found.set(peer.address, { address: peer.address, name: peer.name });
699
+ }
700
+ };
701
+ // A device already known to BlueZ is reported without a radio scan, which is
702
+ // how a pippi that is merely asleep is found; `Discovering` only tells us
703
+ // about advertisers, and this one is often paired and remembered.
704
+ await collect().catch(() => undefined);
705
+ const watcher = this.bus.signals((signal) => {
706
+ if (signal.interface !== "org.freedesktop.DBus.ObjectManager") return;
707
+ if (signal.member !== "InterfacesAdded" && signal.member !== "PropertiesChanged") return;
708
+ void collect().catch(() => undefined);
709
+ });
710
+ let discovering = true;
711
+ try {
712
+ await this.bus.call({ destination: "org.bluez", path: ADAPTER, interface: ADAPTER_IFACE, member: "StartDiscovery" });
713
+ } catch (error) {
714
+ if (!isError(error, "org.bluez.Error.InProgress")) {
715
+ discovering = false;
716
+ this.setState({ connected: false, error: `scan failed: ${describe(error)}` });
717
+ } else {
718
+ // The adapter is still discovering from a scan that never finished --
719
+ // ours or another process's. Clear it and try once.
720
+ this.log("warn", "adapter busy with an old discovery; clearing and retrying once");
721
+ await this.stopDiscovery();
722
+ await delay(300);
723
+ try {
724
+ await this.bus.call({ destination: "org.bluez", path: ADAPTER, interface: ADAPTER_IFACE, member: "StartDiscovery" });
725
+ } catch (retry) {
726
+ discovering = false;
727
+ this.setState({ connected: false, error: `scan failed: ${describe(retry)}` });
728
+ }
729
+ }
730
+ }
731
+ await delay(ms);
732
+ watcher();
733
+ if (discovering) await this.stopDiscovery();
734
+ await collect().catch(() => undefined);
735
+ const results = [...found.values()];
736
+ for (const result of results) this.emit({ type: "scan", results: [result] });
737
+ if (results.length === 0 && !options.quiet) {
738
+ this.log(
739
+ "info",
740
+ "no NUS device found: wake the pippi (button press), check settings -> bluetooth, " +
741
+ "and on Linux make sure BlueZ is up and this process may access it",
742
+ );
743
+ }
744
+ return results;
745
+ }
746
+
747
+ private async stopDiscovery(): Promise<void> {
748
+ await this.bus
749
+ .call({ destination: "org.bluez", path: ADAPTER, interface: ADAPTER_IFACE, member: "StopDiscovery" })
750
+ .catch(() => undefined);
751
+ }
752
+
753
+ /**
754
+ * Ask BlueZ to drop a connection to `target`, whoever owns it.
755
+ *
756
+ * A connection belongs to the adapter, not to the process that opened it, and a
757
+ * connected peripheral stops advertising -- so when another pi window holds the
758
+ * pippi it is not busy, it is unreachable, and retrying here can never win.
759
+ *
760
+ * Best effort: when nobody holds the link the call simply fails, which is the
761
+ * common case and not worth reporting. Only a human pressing Enter ends up here,
762
+ * so a takeover is always something the operator asked for.
763
+ */
764
+ private async releaseLink(target: string): Promise<void> {
765
+ if (!ADDRESS.test(target.toUpperCase())) return;
766
+ const path = devicePath(target.toUpperCase());
767
+ // Ask before hanging anybody up. Every claim used to put a `Disconnect` on the bus,
768
+ // and a session whose pippi is unreachable issues a claim on every gated tool call,
769
+ // so BlueZ and the device saw a connect/disconnect storm of exactly the kind this
770
+ // bridge exists to prevent. A device that reports no link has none to take over.
771
+ const held = await this.property<boolean>(DEVICE_IFACE, "Connected", path).catch(() => undefined);
772
+ if (held === false) return;
773
+ await this.bus
774
+ .call({ destination: "org.bluez", path, interface: DEVICE_IFACE, member: "Disconnect" })
775
+ .then(() => this.log("info", `released ${target}`))
776
+ .catch(() => undefined);
777
+ // BlueZ removes the object when a link was actually torn down; give the
778
+ // adapter a moment before the reconnect races it.
779
+ await delay(200);
780
+ }
781
+
782
+ // ------------------------------------------------------------------ writing
783
+
784
+ write(line: string): void {
785
+ this.tap.record("tx", line);
786
+ this.writeQueue.push(line);
787
+ void this.drainWrites();
788
+ }
789
+
790
+ private async drainWrites(): Promise<void> {
791
+ if (this.writing) return;
792
+ this.writing = true;
793
+ try {
794
+ while (this.writeQueue.length > 0 && !this.closing) {
795
+ await this.writeLine(this.writeQueue.shift()!);
796
+ }
797
+ } finally {
798
+ this.writing = false;
799
+ }
800
+ }
801
+
802
+ private async writeLine(line: string): Promise<void> {
803
+ if (!this.state.connected || !this.rxChar) {
804
+ // Say so in the one channel the bridge reads. A transport whose ATT channel
805
+ // went away still accepts writes, so a bridge watching only link events can
806
+ // push snapshots at a pet it is not attached to forever -- which is how a
807
+ // session ends up with a green status light and prompts nobody will see.
808
+ if (!this.reportedWriteGap) {
809
+ this.reportedWriteGap = true;
810
+ this.log("warn", "write dropped: not connected");
811
+ this.setState({ connected: false, address: this.target, error: "write dropped: not connected" });
812
+ }
813
+ return;
814
+ }
815
+ const payload = Buffer.from(`${line}\n`, "utf8");
816
+ let offset = 0;
817
+ let chunk = this.attPayload;
818
+ let attempts = 0;
819
+ while (offset < payload.length) {
820
+ const piece = payload.subarray(offset, offset + chunk);
821
+ try {
822
+ // Write-with-response: every ATT write is confirmed, which is what the
823
+ // device's 2048-byte receive ring needs to not drop a frame.
824
+ await this.bus.call({
825
+ destination: "org.bluez",
826
+ path: this.rxChar,
827
+ interface: CHAR_IFACE,
828
+ member: "WriteValue",
829
+ signature: "aya{sv}",
830
+ args: [piece, {}],
831
+ });
832
+ offset += piece.length;
833
+ } catch (error) {
834
+ // "InProgress" is BlueZ saying the ATT channel is still busy with the
835
+ // frame before this one. It is flow control, and the only honest answer is
836
+ // to wait and send the same bytes again -- a link that refuses a write for
837
+ // a moment is not a link that is gone, and saying otherwise turns a busy
838
+ // session into a reconnect storm.
839
+ if (isError(error, "org.bluez.Error.InProgress") && !this.closing) {
840
+ await delay(120);
841
+ // The same piece again, not the frame from the start: the bytes before
842
+ // this one are already in the device's ring, and sending them twice
843
+ // corrupts the very line the retry exists to deliver.
844
+ if (++attempts <= WRITE_RETRY_LIMIT) continue;
845
+ this.log("warn", `write still refused after ${WRITE_RETRY_LIMIT} tries; dropping frame`);
846
+ this.writeQueue.length = 0;
847
+ return;
848
+ }
849
+ if (chunk > MIN_ATT_PAYLOAD) {
850
+ chunk = MIN_ATT_PAYLOAD;
851
+ this.log("warn", `write failed (${describe(error)}); retrying at ${chunk} byte chunks`);
852
+ continue;
853
+ }
854
+ this.setState({ connected: false, error: `write failed: ${describe(error)}` });
855
+ return;
856
+ }
857
+ }
858
+ }
859
+
860
+ // -------------------------------------------------------------- shutdown
861
+
862
+ async close(): Promise<void> {
863
+ this.closing = true;
864
+ this.stopLink?.();
865
+ for (const off of this.unsubscribes) off();
866
+ this.unsubscribes = [];
867
+ for (const waiter of [...this.waiters]) waiter.reject(new Error("transport closed"));
868
+ // Deliberately no `board.retire()`. The stamp means "a human asked for the
869
+ // pippi in this session", which outlives a transport: this session may be
870
+ // reconnecting in a second, and a transport that deleted its own way back in
871
+ // on shutdown would leave the bridge standing down over a pet nobody holds.
872
+ if (this.peer) {
873
+ await this.bus
874
+ .call({ destination: "org.bluez", path: this.peer.path, interface: DEVICE_IFACE, member: "Disconnect" })
875
+ .catch(() => undefined);
876
+ }
877
+ this.bus.close();
878
+ this.linkTask = undefined;
879
+ // A transport that has been closed and is asked to start again has to actually
880
+ // reconnect: the bridge closes the link on a reclaim and opens it again a moment
881
+ // later, and a memoised start() on a dead socket is how a pippi disappears for
882
+ // the rest of the session with "scan failed: dbus: not connected" in the log.
883
+ this.started = undefined;
884
+ this.setState({ connected: false });
885
+ }
886
+
887
+ // ------------------------------------------------------------------ lookups
888
+
889
+ /** Every object BlueZ knows that has a Device1 interface. */
890
+ private async peers(): Promise<Peer[]> {
891
+ const reply = await this.bus.call({
892
+ destination: "org.bluez",
893
+ path: "/",
894
+ interface: OBJECT_MANAGER,
895
+ member: "GetManagedObjects",
896
+ });
897
+ return peersFrom(reply.body[0]);
898
+ }
899
+
900
+ /** Peers exposing the Nordic UART service, found by walking the object tree. */
901
+ private async peersWithUart(): Promise<Peer[]> {
902
+ const objects = await this.objects();
903
+ // Filter on the service UUID, not the advertised name: name prefixes change
904
+ // (the firmware advertises "Pi-XXXX") and a headset is not a pippi.
905
+ const held = new Set(
906
+ Object.values(objects)
907
+ .filter((ifaces) => String(ifaces[SERVICE_IFACE]?.UUID ?? "").toLowerCase() === NUS_SERVICE)
908
+ .map((ifaces) => parentOf(ifaces[SERVICE_IFACE], SERVICE_PARENT_KEYS) ?? ""),
909
+ );
910
+ return peersFrom(objects).filter((peer) => held.has(peer.path));
911
+ }
912
+
913
+ private async findPeer(target: string): Promise<Peer | undefined> {
914
+ const wanted = target.toUpperCase();
915
+ const all = await this.peers();
916
+ return (
917
+ all.find((peer) => peer.address.toUpperCase() === wanted) ??
918
+ all.find((peer) => peer.name.toLowerCase() === target.toLowerCase())
919
+ );
920
+ }
921
+
922
+ private async findCharacteristics(peerPath: string): Promise<{ tx?: string; rx?: string }> {
923
+ const objects = await this.objects();
924
+ const uartServices = new Set(
925
+ Object.entries(objects)
926
+ .filter(([, ifaces]) => {
927
+ const service = ifaces[SERVICE_IFACE];
928
+ if (!service) return false;
929
+ // BlueZ renamed the service's parent from `Service` to `Device`; a tree
930
+ // with only one of the two names has to be read by both, because the
931
+ // version doing the publishing is the user's, not ours.
932
+ const parent = parentOf(service, SERVICE_PARENT_KEYS);
933
+ return parent === peerPath && String(service.UUID ?? "").toLowerCase() === NUS_SERVICE;
934
+ })
935
+ .map(([path]) => path),
936
+ );
937
+ let tx: string | undefined;
938
+ let rx: string | undefined;
939
+ for (const [path, ifaces] of Object.entries(objects)) {
940
+ const char = ifaces[CHAR_IFACE];
941
+ if (!char) continue;
942
+ if (!uartServices.has(String(parentOf(char, ["Service"]) ?? ""))) continue;
943
+ const uuid = String(char.UUID ?? "").toLowerCase();
944
+ if (uuid === NUS_TX) tx = path;
945
+ if (uuid === NUS_RX) rx = path;
946
+ }
947
+ return { tx, rx };
948
+ }
949
+
950
+ /** BlueZ's whole tree in one reply, as an object keyed by path. */
951
+ private async objects(): Promise<Record<string, Record<string, Record<string, unknown>>>> {
952
+ const reply = await this.bus.call({
953
+ destination: "org.bluez",
954
+ path: "/",
955
+ interface: OBJECT_MANAGER,
956
+ member: "GetManagedObjects",
957
+ });
958
+ return (reply.body[0] ?? {}) as Record<string, Record<string, Record<string, unknown>>>;
959
+ }
960
+
961
+ private async property<T>(iface: string, name: string, path: string): Promise<T> {
962
+ const reply = await this.bus.call({
963
+ destination: "org.bluez",
964
+ path,
965
+ interface: PROPS_IFACE,
966
+ member: "Get",
967
+ signature: "ss",
968
+ args: [iface, name],
969
+ });
970
+ return reply.body[0] as T;
971
+ }
972
+
973
+ private matchesName(peer: Peer): boolean {
974
+ return this.namePrefix === "" || peer.name.startsWith(this.namePrefix);
975
+ }
976
+
977
+ // ------------------------------------------------------------------- report
978
+
979
+ private setState(state: TransportState): void {
980
+ this.state = state;
981
+ this.emit({ type: "state", state });
982
+ if (state.connected) {
983
+ for (const waiter of [...this.waiters]) waiter.resolve();
984
+ } else if (state.error) {
985
+ for (const waiter of [...this.waiters]) waiter.reject(new Error(state.error));
986
+ }
987
+ }
988
+
989
+ private fail(message: string): void {
990
+ this.setState({ connected: false, address: this.target, error: message });
991
+ }
992
+ }
993
+
994
+ // --------------------------------------------------------------------- helpers
995
+
996
+ /**
997
+ * The property naming a GATT object's parent. `Device` is what current BlueZ
998
+ * publishes on a service; `Service` is what older ones did, and what still names
999
+ * a characteristic's service today -- so a service is read by either name and a
1000
+ * characteristic only by `Service`, per tests/fixtures/bluez_gatt_tree.json.
1001
+ * Getting this wrong is not a crash: the pippi simply appears to have no Nordic
1002
+ * UART service, and every connect fails on a working radio.
1003
+ */
1004
+ const SERVICE_PARENT_KEYS = ["Device", "Service"];
1005
+
1006
+ function parentOf(props: Record<string, unknown> | undefined, keys: string[]): string | undefined {
1007
+ if (!props) return undefined;
1008
+ for (const key of keys) {
1009
+ const value = props[key];
1010
+ if (typeof value === "string" && value !== "") return value;
1011
+ }
1012
+ return undefined;
1013
+ }
1014
+
1015
+ function peersFrom(managed: unknown): Peer[] {
1016
+ const objects = (managed ?? {}) as Record<string, Record<string, Record<string, unknown>>>;
1017
+ const peers: Peer[] = [];
1018
+ for (const [path, ifaces] of Object.entries(objects)) {
1019
+ const device = ifaces[DEVICE_IFACE];
1020
+ if (!device) continue;
1021
+ peers.push({
1022
+ path,
1023
+ address: String(device.Address ?? ""),
1024
+ name: String(device.Name ?? device.Alias ?? ""),
1025
+ connected: Boolean(device.Connected),
1026
+ });
1027
+ }
1028
+ return peers;
1029
+ }
1030
+
1031
+ /** The object path BlueZ uses for a peer: the address, punctuated. */
1032
+ export function devicePath(address: string): string {
1033
+ return `/org/bluez/hci0/dev_${address.toUpperCase().replace(/:/g, "_")}`;
1034
+ }
1035
+
1036
+ function alreadyConnected(error: unknown): boolean {
1037
+ return isError(error, "org.bluez.Error.AlreadyConnected");
1038
+ }
1039
+
1040
+ /**
1041
+ * BlueZ refused the authentication an encrypted link needs, as opposed to failing
1042
+ * for a reason that might pass on its own. `org.bluez.Error.Rejected` is left out:
1043
+ * GATT writes answer with that for reasons as transient as an unwritten descriptor,
1044
+ * and stopping the dial loop for one of those would be worse than retrying it.
1045
+ */
1046
+ function isAuthFailure(error: unknown): boolean {
1047
+ return (
1048
+ isError(error, "org.bluez.Error.AuthenticationFailed") ||
1049
+ isError(error, "org.bluez.Error.AuthenticationRejected") ||
1050
+ isError(error, "org.bluez.Error.AuthenticationCanceled")
1051
+ );
1052
+ }
1053
+
1054
+ function isError(error: unknown, name: string): boolean {
1055
+ if (error instanceof DBusError) return error.matches(name);
1056
+ return error instanceof Error && error.message.includes(name);
1057
+ }
1058
+
1059
+ function describe(error: unknown): string {
1060
+ if (error === BLUEZ_TIMEOUT) return "BlueZ did not answer in time";
1061
+ return error instanceof Error ? error.message : String(error);
1062
+ }