@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/CHANGELOG.md +13 -0
- package/README.md +415 -2
- package/approvals.ts +552 -0
- package/ble.ts +1062 -0
- package/bluez.ts +962 -0
- package/bridge.ts +1759 -0
- package/claims.ts +453 -0
- package/index.ts +827 -0
- package/package.json +53 -4
- package/protocol.ts +593 -0
- package/simulate.ts +249 -0
- package/state.ts +91 -0
- package/transport.ts +183 -0
- package/usage.ts +959 -0
package/simulate.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pippi that is not there.
|
|
3
|
+
*
|
|
4
|
+
* The bridge is mostly a state machine about ownership, prompts and file
|
|
5
|
+
* transfer, and none of that needs a radio to be wrong or right. This transport
|
|
6
|
+
* answers the device protocol itself -- the same acks, the same prompt behaviour,
|
|
7
|
+
* the same counters -- so `npm test` covers the bridge end to end and
|
|
8
|
+
* `dev-run.mjs --simulate` can drive a full session on a laptop with the BLE
|
|
9
|
+
* switched off.
|
|
10
|
+
*
|
|
11
|
+
* It is a stand-in, not a simulator of the device's bugs: it never fragments a
|
|
12
|
+
* line, never runs out of heap, and always answers. Radio behaviour -- MTU,
|
|
13
|
+
* fragmentation, drops, the claim board's timing -- only `ble.ts` exercises, and
|
|
14
|
+
* only a real pippi settles those.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { parseDeviceLine } from "./protocol.ts";
|
|
18
|
+
import { ListenerBase, WireTap, type BridgeTransport, type ScanResult, type TransportState } from "./transport.ts";
|
|
19
|
+
|
|
20
|
+
export interface SimTransportOptions {
|
|
21
|
+
/** Answer every prompt this way, as if a human were quick: "once" | "always" | "deny". */
|
|
22
|
+
autoDecision?: string;
|
|
23
|
+
autoDelayMs?: number;
|
|
24
|
+
address?: string;
|
|
25
|
+
name?: string;
|
|
26
|
+
wireLogPath?: string;
|
|
27
|
+
log?: (level: "info" | "warn", message: string) => void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The pet's side of the protocol, minus the pet. */
|
|
31
|
+
class FakePippi {
|
|
32
|
+
readonly address = "SIM-000000";
|
|
33
|
+
readonly name = "Pippi-SIM";
|
|
34
|
+
readonly secure = true;
|
|
35
|
+
readonly mtu = 23;
|
|
36
|
+
|
|
37
|
+
private up = 0;
|
|
38
|
+
private charBytes = 0;
|
|
39
|
+
private fileBytes = 0;
|
|
40
|
+
private currentFile = "";
|
|
41
|
+
private currentSize = 0;
|
|
42
|
+
private pendingPrompt?: string;
|
|
43
|
+
// Plain fields, assigned in the constructor: node's type stripping rejects
|
|
44
|
+
// TypeScript parameter properties, and this file is imported by the tests.
|
|
45
|
+
private readonly autoDecision: string | undefined;
|
|
46
|
+
private readonly autoDelayMs: number;
|
|
47
|
+
private readonly emitLine: (line: Record<string, unknown>) => void;
|
|
48
|
+
|
|
49
|
+
constructor(
|
|
50
|
+
autoDecision: string | undefined,
|
|
51
|
+
autoDelayMs: number,
|
|
52
|
+
emitLine: (line: Record<string, unknown>) => void,
|
|
53
|
+
) {
|
|
54
|
+
this.autoDecision = autoDecision;
|
|
55
|
+
this.autoDelayMs = autoDelayMs;
|
|
56
|
+
this.emitLine = emitLine;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private status(): Record<string, unknown> {
|
|
60
|
+
this.up += 1;
|
|
61
|
+
return {
|
|
62
|
+
name: this.name,
|
|
63
|
+
owner: "Sim",
|
|
64
|
+
sec: this.secure,
|
|
65
|
+
bat: { pct: 87, mV: 4012, mA: -120, usb: true },
|
|
66
|
+
sys: { up: 8412 + this.up, heap: 84200, fsFree: 1_200_000, fsTotal: 4_194_304 },
|
|
67
|
+
stats: { appr: 42, deny: 3, vel: 8, nap: 12, lvl: 5 },
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The replies this write earns, in order. */
|
|
72
|
+
handle(line: Record<string, unknown>): Array<Record<string, unknown>> {
|
|
73
|
+
const ack = (name: string, extra: Record<string, unknown> = {}) => [{ ack: name, ok: true, n: 0, ...extra }];
|
|
74
|
+
switch (line.cmd) {
|
|
75
|
+
case "status":
|
|
76
|
+
return ack("status", { data: this.status() });
|
|
77
|
+
case "name":
|
|
78
|
+
case "owner":
|
|
79
|
+
case "unpair":
|
|
80
|
+
return ack(String(line.cmd));
|
|
81
|
+
case "char_begin":
|
|
82
|
+
this.charBytes = 0;
|
|
83
|
+
this.fileBytes = 0;
|
|
84
|
+
return ack("char_begin");
|
|
85
|
+
case "file":
|
|
86
|
+
this.currentFile = String(line.path ?? "");
|
|
87
|
+
this.currentSize = Number(line.size ?? 0);
|
|
88
|
+
this.fileBytes = 0;
|
|
89
|
+
return ack("file");
|
|
90
|
+
case "chunk": {
|
|
91
|
+
const raw = decodeChunk(String(line.d ?? ""));
|
|
92
|
+
if (raw === undefined) {
|
|
93
|
+
return [{ ack: "chunk", ok: false, n: this.fileBytes, error: "chunk: not base64" }];
|
|
94
|
+
}
|
|
95
|
+
this.fileBytes += raw;
|
|
96
|
+
return [{ ack: "chunk", ok: true, n: this.fileBytes }];
|
|
97
|
+
}
|
|
98
|
+
case "file_end": {
|
|
99
|
+
const ok = this.currentSize === 0 || this.fileBytes === this.currentSize;
|
|
100
|
+
const reply: Record<string, unknown> = { ack: "file_end", ok, n: this.fileBytes };
|
|
101
|
+
if (!ok) reply.error = `wrote ${this.fileBytes} of ${this.currentSize}`;
|
|
102
|
+
this.charBytes += this.fileBytes;
|
|
103
|
+
this.fileBytes = 0;
|
|
104
|
+
return [reply];
|
|
105
|
+
}
|
|
106
|
+
case "char_end":
|
|
107
|
+
return [{ ack: "char_end", ok: true, n: this.charBytes }];
|
|
108
|
+
case "permission":
|
|
109
|
+
// A bridge should not send decisions; ignore quietly.
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
if (line.prompt !== undefined) {
|
|
113
|
+
const prompt = line.prompt as Record<string, unknown>;
|
|
114
|
+
const id = prompt.id === undefined ? undefined : String(prompt.id);
|
|
115
|
+
// Any question still owed that is not this one has been replaced on the panel, and
|
|
116
|
+
// a pippi that answers a question nobody is asking is a bug in the toy.
|
|
117
|
+
this.cancelOwed(id);
|
|
118
|
+
if (this.autoDecision && id && id !== this.pendingPrompt) {
|
|
119
|
+
this.pendingPrompt = id;
|
|
120
|
+
this.scheduleDecision(id, this.autoDecision);
|
|
121
|
+
}
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
// A snapshot with no prompt means the panel cleared the question. Whatever answer was
|
|
125
|
+
// counted out for it belongs to a screen that no longer shows it, and sending it would
|
|
126
|
+
// let the toy invent a decision the human never made.
|
|
127
|
+
this.pendingPrompt = undefined;
|
|
128
|
+
this.cancelOwed();
|
|
129
|
+
// Time sync and the rest of a plain snapshot need no reply.
|
|
130
|
+
return [];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Answers this stand-in has promised and not yet sent, by the prompt they answer. */
|
|
134
|
+
private readonly owed = new Map<string, ReturnType<typeof setTimeout>>();
|
|
135
|
+
|
|
136
|
+
private scheduleDecision(id: string, decision: string): void {
|
|
137
|
+
const timer = setTimeout(() => {
|
|
138
|
+
this.owed.delete(id);
|
|
139
|
+
this.emitLine({ cmd: "permission", id, decision });
|
|
140
|
+
}, this.autoDelayMs);
|
|
141
|
+
// Never hold the process open for a prompt nobody answered.
|
|
142
|
+
timer.unref?.();
|
|
143
|
+
this.owed.set(id, timer);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Forget every promised answer except `keep` -- which is nothing at all when the panel
|
|
148
|
+
* has cleared the question. Pairs with the device's own behaviour: a real panel erases
|
|
149
|
+
* the dialog the moment a snapshot arrives without a prompt in it.
|
|
150
|
+
*/
|
|
151
|
+
private cancelOwed(keep?: string): void {
|
|
152
|
+
for (const [id, timer] of [...this.owed]) {
|
|
153
|
+
if (id === keep) continue;
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
this.owed.delete(id);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function decodeChunk(text: string): number | undefined {
|
|
161
|
+
try {
|
|
162
|
+
return Buffer.from(text, "base64").length;
|
|
163
|
+
} catch {
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A transport whose pippi is a few lines of TypeScript.
|
|
170
|
+
*
|
|
171
|
+
* There is no link to keep and nobody to claim it from, so `connect()` cannot
|
|
172
|
+
* fail and `claim()` is `connect()`: the ownership rules live above this, in
|
|
173
|
+
* bridge.ts, and are the thing worth testing here.
|
|
174
|
+
*/
|
|
175
|
+
export class SimTransport extends ListenerBase implements BridgeTransport {
|
|
176
|
+
readonly kind = "simulate";
|
|
177
|
+
state: TransportState = { connected: false };
|
|
178
|
+
|
|
179
|
+
private readonly fake: FakePippi;
|
|
180
|
+
private readonly tap: WireTap;
|
|
181
|
+
private log: (level: "info" | "warn", message: string) => void;
|
|
182
|
+
private scanning = false;
|
|
183
|
+
|
|
184
|
+
constructor(options: SimTransportOptions = {}) {
|
|
185
|
+
super();
|
|
186
|
+
this.log = options.log ?? (() => {});
|
|
187
|
+
this.tap = new WireTap(options.wireLogPath ?? process.env.PI_PIPPI_WIRE_LOG);
|
|
188
|
+
this.fake = new FakePippi(
|
|
189
|
+
options.autoDecision ?? process.env.PI_PIPPI_AUTO_ANSWER,
|
|
190
|
+
options.autoDelayMs ?? numberFromEnv(process.env.PI_PIPPI_AUTO_DELAY_MS, 200),
|
|
191
|
+
(line) => {
|
|
192
|
+
this.tap.record("rx", JSON.stringify(line));
|
|
193
|
+
this.emit({ type: "line", line });
|
|
194
|
+
},
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async start(): Promise<void> {
|
|
199
|
+
this.emit({ type: "log", level: "info", message: "simulated pippi ready" });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async connect(): Promise<void> {
|
|
203
|
+
this.state = {
|
|
204
|
+
connected: true,
|
|
205
|
+
address: this.fake.address,
|
|
206
|
+
name: this.fake.name,
|
|
207
|
+
mtu: this.fake.mtu,
|
|
208
|
+
secure: this.fake.secure,
|
|
209
|
+
};
|
|
210
|
+
this.emit({ type: "state", state: this.state });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async claim(target?: string): Promise<void> {
|
|
214
|
+
await this.connect();
|
|
215
|
+
void target;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async scan(): Promise<ScanResult[]> {
|
|
219
|
+
this.scanning = true;
|
|
220
|
+
const results = [{ address: this.fake.address, name: this.fake.name, rssi: -50 }];
|
|
221
|
+
this.emit({ type: "scan", results });
|
|
222
|
+
this.scanning = false;
|
|
223
|
+
return results;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
write(line: string): void {
|
|
227
|
+
this.tap.record("tx", line);
|
|
228
|
+
const parsed = parseDeviceLine(line);
|
|
229
|
+
if (!parsed) {
|
|
230
|
+
this.log("warn", "write: dropping unparsable frame");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
for (const reply of this.fake.handle(parsed)) this.emit({ type: "line", line: reply });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
get isScanning(): boolean {
|
|
237
|
+
return this.scanning;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async close(): Promise<void> {
|
|
241
|
+
this.state = { connected: false };
|
|
242
|
+
this.emit({ type: "state", state: this.state });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function numberFromEnv(value: string | undefined, fallback: number): number {
|
|
247
|
+
const parsed = Number(value);
|
|
248
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
249
|
+
}
|
package/state.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk bridge state: which pippi to reconnect to, and the daily output
|
|
3
|
+
* token counter (REFERENCE.md requires tokens_today to survive restarts and
|
|
4
|
+
* reset at local midnight).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { execFileSync } from "node:child_process";
|
|
8
|
+
import * as fs from "node:fs";
|
|
9
|
+
import * as os from "node:os";
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
|
|
12
|
+
import type { PersistedState, StateStore } from "./bridge.ts";
|
|
13
|
+
import { sanitizeTag } from "./protocol.ts";
|
|
14
|
+
|
|
15
|
+
export function defaultStateDir(): string {
|
|
16
|
+
const base =
|
|
17
|
+
process.env.PI_PIPPI_STATE_DIR ??
|
|
18
|
+
// "pi-buddy" is a storage key, not a brand: the directory holds state.json with
|
|
19
|
+
// the remembered device, the local-midnight token counter, the approvals policy
|
|
20
|
+
// and the /pippi off flag, and a renamed directory silently resets all of it.
|
|
21
|
+
path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"), "pi-buddy");
|
|
22
|
+
return base;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class FileStateStore implements StateStore {
|
|
26
|
+
private readonly file: string;
|
|
27
|
+
private cache?: PersistedState;
|
|
28
|
+
|
|
29
|
+
constructor(file: string = path.join(defaultStateDir(), "state.json")) {
|
|
30
|
+
this.file = file;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get path(): string {
|
|
34
|
+
return this.file;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
load(): PersistedState {
|
|
38
|
+
if (this.cache) return { ...this.cache };
|
|
39
|
+
try {
|
|
40
|
+
const raw = fs.readFileSync(this.file, "utf8");
|
|
41
|
+
const parsed = JSON.parse(raw) as PersistedState;
|
|
42
|
+
this.cache = parsed && typeof parsed === "object" ? parsed : {};
|
|
43
|
+
} catch {
|
|
44
|
+
this.cache = {};
|
|
45
|
+
}
|
|
46
|
+
return { ...this.cache };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
save(patch: PersistedState): void {
|
|
50
|
+
const next = { ...this.load(), ...patch };
|
|
51
|
+
this.cache = next;
|
|
52
|
+
try {
|
|
53
|
+
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
|
54
|
+
// Write-then-rename so a crash mid-save cannot leave truncated JSON.
|
|
55
|
+
const temp = `${this.file}.${process.pid}.tmp`;
|
|
56
|
+
fs.writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
|
57
|
+
fs.renameSync(temp, this.file);
|
|
58
|
+
} catch {
|
|
59
|
+
// State persistence is best-effort: never break a session over it.
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Owner first name: explicit env, then git identity, then the login name. */
|
|
65
|
+
export function guessOwner(): string | undefined {
|
|
66
|
+
const explicit = process.env.PI_PIPPI_OWNER;
|
|
67
|
+
if (explicit) return explicit.trim().split(/\s+/)[0];
|
|
68
|
+
try {
|
|
69
|
+
const name = execFileSync("git", ["config", "--get", "user.name"], {
|
|
70
|
+
encoding: "utf8",
|
|
71
|
+
timeout: 1000,
|
|
72
|
+
}).trim();
|
|
73
|
+
if (name) return name.split(/\s+/)[0];
|
|
74
|
+
} catch {
|
|
75
|
+
// no git / no identity
|
|
76
|
+
}
|
|
77
|
+
const user = process.env.USER ?? process.env.USERNAME ?? os.userInfo?.().username;
|
|
78
|
+
return user ? user.replace(/^\/?home\/?/, "").split(/[\\/]/).pop() : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Which pi window this is, as the pet can spell it: the working directory's
|
|
83
|
+
* name, since that is what a person running several windows thinks in. Two
|
|
84
|
+
* windows open in the same project get the same tag, which is honest -- the wire
|
|
85
|
+
* has nothing better to say about them -- and PI_PIPPI_TAG / `/pippi tag <name>`
|
|
86
|
+
* is how you tell them apart. Falls back to "pi" for a directory the device font
|
|
87
|
+
* cannot draw (/ or a CJK path).
|
|
88
|
+
*/
|
|
89
|
+
export function guessSessionTag(): string {
|
|
90
|
+
return sanitizeTag(process.env.PI_PIPPI_TAG ?? path.basename(process.cwd())) || "pi";
|
|
91
|
+
}
|
package/transport.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contract between the bridge and whatever is carrying the pippi.
|
|
3
|
+
*
|
|
4
|
+
* Two implementations ship here: `BluezTransport` (ble.ts) talks to the pet over
|
|
5
|
+
* BlueZ and the system bus, and `SimTransport` (simulate.ts) answers the
|
|
6
|
+
* protocol itself so the bridge, its tests, and anyone demoing it can run with no
|
|
7
|
+
* radio. Both report the same events, which is the only reason `bridge.ts` can be
|
|
8
|
+
* tested at all: nothing above this file knows or cares how the bytes travel.
|
|
9
|
+
*
|
|
10
|
+
* A transport is not a socket with a `connected` flag. The interesting questions
|
|
11
|
+
* it has to answer are about ownership -- whose session may hold the link, what
|
|
12
|
+
* happens when the link drops by itself, and what the bridge is told when the
|
|
13
|
+
* answer turns out to be "someone else" -- and those answers are why this
|
|
14
|
+
* interface has a `claim` distinct from `connect` and a `claim_lost` event with no
|
|
15
|
+
* equivalent on any socket.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { appendFile } from "node:fs";
|
|
19
|
+
|
|
20
|
+
export interface TransportState {
|
|
21
|
+
connected: boolean;
|
|
22
|
+
address?: string;
|
|
23
|
+
name?: string;
|
|
24
|
+
/** ATT_MTU as BlueZ reports it, once known. */
|
|
25
|
+
mtu?: number;
|
|
26
|
+
/** Whether the link is encrypted -- only the device's own ack knows for sure. */
|
|
27
|
+
secure?: boolean;
|
|
28
|
+
/** Why it is not connected, in the words a human should read. */
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ScanResult {
|
|
33
|
+
address: string;
|
|
34
|
+
name: string;
|
|
35
|
+
rssi?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type TransportListener = (event: TransportEvent) => void;
|
|
39
|
+
|
|
40
|
+
export type TransportEvent =
|
|
41
|
+
| { type: "state"; state: TransportState }
|
|
42
|
+
| { type: "line"; line: Record<string, unknown> }
|
|
43
|
+
| { type: "scan"; results: ScanResult[] }
|
|
44
|
+
| {
|
|
45
|
+
/**
|
|
46
|
+
* The transport looked at the shared claim board before reconnecting and
|
|
47
|
+
* found a stamp newer than ours: a human asked for the pippi in another
|
|
48
|
+
* window, and waiting there is the policy now. There is no other way to
|
|
49
|
+
* learn this -- the link under us is the adapter's, not ours, and never had
|
|
50
|
+
* to drop.
|
|
51
|
+
*/
|
|
52
|
+
type: "claim_lost";
|
|
53
|
+
holder: number | undefined;
|
|
54
|
+
target?: string;
|
|
55
|
+
}
|
|
56
|
+
| {
|
|
57
|
+
/**
|
|
58
|
+
* BlueZ refused the pairing this link requires, which no retry can fix: the
|
|
59
|
+
* panel threw away the long-term key this host is still presenting, so every
|
|
60
|
+
* `Connect` fails authentication the moment pairing is attempted. The panel
|
|
61
|
+
* is DisplayOnly -- it answers each attempt by printing a passkey nobody is
|
|
62
|
+
* waiting at -- so from the desk this looks like a pippi that disconnects
|
|
63
|
+
* for ever. The transport stops dialing and says what to type; a human is
|
|
64
|
+
* the only thing in the system that can delete a bond.
|
|
65
|
+
*/
|
|
66
|
+
type: "bond_stale";
|
|
67
|
+
address: string;
|
|
68
|
+
}
|
|
69
|
+
| { type: "log"; level: "info" | "warn" | "error"; message: string };
|
|
70
|
+
|
|
71
|
+
export interface BridgeTransport {
|
|
72
|
+
readonly kind: string;
|
|
73
|
+
state: TransportState;
|
|
74
|
+
start(): Promise<void>;
|
|
75
|
+
connect(target?: string): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* Take the link over from whoever else holds it, then connect.
|
|
78
|
+
*
|
|
79
|
+
* A BlueZ connection belongs to the adapter, not to the process that opened it,
|
|
80
|
+
* so a pippi attached to another pi window is not merely busy: it is
|
|
81
|
+
* unadvertising and therefore undiscoverable, and no amount of retrying from
|
|
82
|
+
* here will reach it. The holder has to be told to let go, and it will not do so
|
|
83
|
+
* on its own, because the bridge only ever connects on human input.
|
|
84
|
+
*
|
|
85
|
+
* Winning is then published, and that is the half this interface cannot do on
|
|
86
|
+
* its own: releasing the link makes the old holder's *link* drop, which it
|
|
87
|
+
* reports, but a holder whose link never dropped -- because BlueZ let the second
|
|
88
|
+
* client in without ever disturbing the first -- hears nothing at all, and stays
|
|
89
|
+
* attached to a pet it does not have. See claims.ts and `claim_lost`.
|
|
90
|
+
*/
|
|
91
|
+
claim(target?: string): Promise<void>;
|
|
92
|
+
scan(timeoutMs?: number): Promise<ScanResult[]>;
|
|
93
|
+
/** Send one already-serialised protocol line (no trailing newline). */
|
|
94
|
+
write(line: string): void;
|
|
95
|
+
close(): Promise<void>;
|
|
96
|
+
subscribe(listener: TransportListener): () => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Every line to and from the device, appended to a file: the only way to see what
|
|
101
|
+
* the pet was actually told after a session is over, and how a bug report about a
|
|
102
|
+
* missing reaction becomes a question about a specific frame.
|
|
103
|
+
*/
|
|
104
|
+
export class WireTap {
|
|
105
|
+
// No parameter properties anywhere in this repo: the tests run through node's
|
|
106
|
+
// type stripping, which rejects them outright.
|
|
107
|
+
private readonly path?: string;
|
|
108
|
+
|
|
109
|
+
constructor(path?: string) {
|
|
110
|
+
this.path = path;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
static fromEnv(env: NodeJS.ProcessEnv = process.env): WireTap {
|
|
114
|
+
return new WireTap(env.PI_PIPPI_WIRE_LOG);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
record(direction: "tx" | "rx", line: string): void {
|
|
118
|
+
if (!this.path) return;
|
|
119
|
+
const record = `${new Date().toISOString()} ${direction} ${line}\n`;
|
|
120
|
+
// Fire-and-forget, but the callback is required: a promise-less fs call that
|
|
121
|
+
// throws would otherwise surface as an unhandled rejection.
|
|
122
|
+
appendFile(this.path, record, () => {});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Minimal LF-only line splitter (Node's readline also splits on U+2028/U+2029). */
|
|
127
|
+
export class NdjsonReader {
|
|
128
|
+
private buffer = "";
|
|
129
|
+
|
|
130
|
+
feed(chunk: string): string[] {
|
|
131
|
+
this.buffer += chunk;
|
|
132
|
+
const lines: string[] = [];
|
|
133
|
+
let index = this.buffer.indexOf("\n");
|
|
134
|
+
while (index >= 0) {
|
|
135
|
+
const line = this.buffer.slice(0, index).replace(/\r$/, "");
|
|
136
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
137
|
+
if (line.length > 0) lines.push(line);
|
|
138
|
+
index = this.buffer.indexOf("\n");
|
|
139
|
+
}
|
|
140
|
+
return lines;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Fan-out to listeners. A listener that throws must not take the transport down. */
|
|
145
|
+
export class ListenerBase {
|
|
146
|
+
private listeners = new Set<TransportListener>();
|
|
147
|
+
|
|
148
|
+
subscribe(listener: TransportListener): () => void {
|
|
149
|
+
this.listeners.add(listener);
|
|
150
|
+
return () => this.listeners.delete(listener);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
protected emit(event: TransportEvent): void {
|
|
154
|
+
for (const listener of [...this.listeners]) {
|
|
155
|
+
try {
|
|
156
|
+
listener(event);
|
|
157
|
+
} catch {
|
|
158
|
+
// One bad listener is not a reason to stop telling the others.
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Discards everything. Used when the user disables the bridge but pi still has
|
|
166
|
+
* the extension loaded: the pet is off, so there is nowhere to send a snapshot,
|
|
167
|
+
* and every caller still needs something to call.
|
|
168
|
+
*/
|
|
169
|
+
export class NullTransport extends ListenerBase implements BridgeTransport {
|
|
170
|
+
readonly kind = "null";
|
|
171
|
+
state: TransportState = { connected: false };
|
|
172
|
+
|
|
173
|
+
async start(): Promise<void> {}
|
|
174
|
+
async connect(): Promise<void> {}
|
|
175
|
+
async claim(): Promise<void> {}
|
|
176
|
+
|
|
177
|
+
async scan(): Promise<ScanResult[]> {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
write(_line: string): void {}
|
|
182
|
+
async close(): Promise<void> {}
|
|
183
|
+
}
|