Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

/precision reports the relay→Pi and Pi read-back hops on a clock the relay aligns with the arm server #493

Merged opened this

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

smith/arm:smith/481-precision-reports-the-relay-pi-and-pi-re → main 2 commits fork

  • Merged. smith/481-precision-reports-the-relay-pi-and-pi-re was merged into main as dbb53fc.

Review

Sign in to review this change.
13 files changed +245 −14
Software/so101/bench/precision.ts +10 −1
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import WebSocket from "ws";
1313 import { FeetechBus } from "../src/bus.ts";
14 import { wallMs } from "../src/clock.ts";
1415 import { FakeBus } from "../src/fake-bus.ts";
1516 import type { Card } from "../src/precision.ts";
1617 import type { Scorecard } from "../src/precision-history.ts";
@@ -58,13 +59,21 @@ export async function bench(script: readonly Step[] = gesture()): Promise<Card>
5859 try {
5960 const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`);
6061 await new Promise((r, j) => (ws.once("open", r), ws.once("error", j)));
62 // Loopback is its own clock: the stamp is the send time, and a watcher reports each status's age as the relay would.
63 const watch = new WebSocket(`ws://127.0.0.1:${server.port}/watch`);
64 await new Promise((r, j) => (watch.once("open", r), watch.once("error", j)));
65 watch.on("message", (data) => {
66 const { readAt } = JSON.parse(String(data)) as { readAt?: number };
67 if (typeof readAt === "number") watch.send(JSON.stringify({ readBack: [wallMs() - readAt] }));
68 });
6169 const start = performance.now();
6270 for (const step of script) {
6371 const wait = step.at - (performance.now() - start);
6472 if (wait > 0) await new Promise((r) => setTimeout(r, wait));
65 ws.send(JSON.stringify(step.joints));
73 ws.send(JSON.stringify({ ...step.joints, sentAt: wallMs() }));
6674 }
6775 await new Promise((r) => setTimeout(r, 300));
76 watch.close();
6877 ws.close(1000);
6978 await new Promise((r) => ws.once("close", r));
7079 await new Promise((r) => setTimeout(r, 100));
Software/so101/src/clock.ts added +2
@@ -0,0 +1,2 @@
1 /** Wall-clock milliseconds with sub-millisecond resolution: what the relay and the arm server stamp hops with. */
2 export const wallMs = (): number => performance.timeOrigin + performance.now();
Software/so101/src/command-gate.ts +10
@@ -53,6 +53,16 @@ export function parseCommand(text: string): Command | null {
5353 return { seq: stamped ? (seq as number) : null, t: stamped ? (t as number) : null, epoch: Number.isSafeInteger(epoch) && (epoch as number) >= 0 ? (epoch as number) : null, joints };
5454 }
5555
56 /** When the relay sent the frame, ms on the receiver's clock, or null when it did not say (the CLI leader's frames) or the frame is not one. */
57 export function sentAtOf(text: string): number | null {
58 try {
59 const { sentAt } = JSON.parse(text) as { sentAt?: unknown };
60 return typeof sentAt === "number" && Number.isFinite(sentAt) ? sentAt : null;
61 } catch {
62 return null;
63 }
64 }
65
5666 /** Whether the frame says it is the last of a gesture: the target the arm is to land on before the stream closes. */
5767 export function isRelease(text: string): boolean {
5868 try {
Software/so101/src/frame-limit.test.ts +1 −1
@@ -11,7 +11,7 @@ import { BURST, FLOOD_CLOSE, FLOOD_MS, FrameRate, frameBytes, MAX_FRAME_BYTES, T
1111 import { LOST_CLOSE, parseRemote, startRelay, type RunningRelay } from "./relay.ts";
1212 import { startServer, type RunningServer } from "./server.ts";
1313 /** A frame as the arm sees it, without the STOP epoch the relay stamps on it. */
14 const unstamped = (frame: string) => JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(frame) as object).filter(([key]) => key !== "epoch")));
14 const unstamped = (frame: string) => JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(frame) as object).filter(([key]) => key !== "epoch" && key !== "sentAt")));
1515
1616 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
1717 const shut = (s: { close(): Promise<void> } | undefined) => (s ? Promise.race([s.close(), sleep(500)]) : undefined);
Software/so101/src/precision-history.test.ts +38
@@ -5,6 +5,8 @@ import { join } from "node:path";
55 import WebSocket from "ws";
66 import { FeetechBus } from "./bus.ts";
77 import { FakeBus } from "./fake-bus.ts";
8 import { wallMs } from "./clock.ts";
9 import { READ_BACK_HOP, RELAY_HOP } from "./precision.ts";
810 import { deployedCommit, PrecisionHistory, type Scorecard } from "./precision-history.ts";
911 import { startServer, type RunningServer } from "./server.ts";
1012
@@ -123,6 +125,42 @@ describe("GET /precision on the arm server", () => {
123125 expect(after.window.trackingP95Deg).not.toBeNull();
124126 });
125127
128 test("stamped frames time relay→Pi, unstamped ones are accepted and not counted, and the watch answers the clock ping and takes the read-back hop", async () => {
129 const hops = async () => (await card()).window.hops;
130 const before = (await hops())[RELAY_HOP]!.n;
131 const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`);
132 await new Promise((r) => ws.once("open", r));
133 ws.send(JSON.stringify({ "1": 2000 })); // the CLI leader's: no stamp
134 await sleep(60);
135 expect((await hops())[RELAY_HOP]!.n).toBe(before);
136 ws.send(JSON.stringify({ "1": 2010, sentAt: wallMs() - 7 }));
137 ws.send(JSON.stringify({ "1": 2020, sentAt: wallMs() + 5000 })); // a clock that disagrees: not counted
138 await sleep(60);
139 const relayHop = (await hops())[RELAY_HOP]!;
140 expect(relayHop.n).toBe(before + 1);
141 expect(relayHop.p50).toBeGreaterThanOrEqual(7);
142 expect(relayHop.p50).toBeLessThan(200);
143 ws.close();
144
145 const watch = new WebSocket(`ws://127.0.0.1:${server.port}/watch`);
146 const heard: Array<Record<string, any>> = [];
147 watch.on("message", (d) => heard.push(JSON.parse(String(d))));
148 await new Promise((r) => watch.once("open", r));
149 const t0 = wallMs();
150 watch.send(JSON.stringify({ ping: t0 }));
151 watch.send(JSON.stringify({ readBack: [2, 4, -1, "x", 6] }));
152 watch.send("not json");
153 await sleep(100);
154 const pong = heard.find((m) => m.pong)!.pong;
155 expect(pong.t0).toBe(t0);
156 expect(pong.t2).toBeGreaterThanOrEqual(pong.t1);
157 expect(pong.t1).toBeGreaterThanOrEqual(t0);
158 expect(heard.find((m) => m.joints)!.readAt).toBeGreaterThanOrEqual(t0 - 1000);
159 const back = (await hops())[READ_BACK_HOP]!;
160 expect(back).toMatchObject({ n: 3, p50: 4, p95: 6 });
161 watch.close();
162 });
163
126164 test("a turn that ends mid-move (the relay's /stop with hold: false) is a turn-end snap-back, not a STOP, and leaves the arm free", async () => {
127165 const before = (await card()).window.snapBacks.byCause;
128166 const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`);
Software/so101/src/precision-history.ts +8
@@ -86,6 +86,14 @@ export class PrecisionHistory {
8686 return this.#current;
8787 }
8888
89 /** A link hop: in the session being driven when there is one, else in the rolling window alone. */
90 hop(name: string, ms: number): boolean {
91 const at = this.#now();
92 if (this.#current) return this.#current.hop(name, ms, at);
93 const probe = new Tracker(at, [this.#window]);
94 return probe.hop(name, ms, at);
95 }
96
8997 /** A snap-back the page saw: in the session being driven when there is one, else in the rolling window alone (a reconnect comes after the stream). */
9098 pageSnapBack(cause: Cause, sizeDeg: number): void {
9199 const at = this.#now();
Software/so101/src/precision.test.ts +20 −1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2 import { ARRIVE_TICKS, CAUSES, emptyRecords, percentile, SETTLE_MS, summarize, trim, Tracker } from "./precision.ts";
2 import { ARRIVE_TICKS, CAUSES, emptyRecords, MAX_HOP_MS, READ_BACK_HOP, RELAY_HOP, percentile, SETTLE_MS, summarize, trim, Tracker } from "./precision.ts";
33
44 describe("percentile", () => {
55 test("nearest rank, unsorted input, none for an empty list", () => {
@@ -97,6 +97,25 @@ describe("bus to motion", () => {
9797 });
9898 });
9999
100 describe("link hops", () => {
101 test("relay→Pi and read-back→relay get p50/p95 beside bus→move, and latencyP95Ms adds all three; a negative or absurd one is not counted", () => {
102 const t = new Tracker(0);
103 for (const ms of [4, 6, 8, 10]) expect(t.hop(RELAY_HOP, ms, 100)).toBe(true);
104 expect(t.hop(READ_BACK_HOP, 3, 100)).toBe(true);
105 expect(t.hop(RELAY_HOP, -1, 100)).toBe(false);
106 expect(t.hop(RELAY_HOP, Number.NaN, 100)).toBe(false);
107 expect(t.hop(RELAY_HOP, MAX_HOP_MS + 1, 100)).toBe(false);
108 t.sample(1, 2000, 0);
109 t.wrote(1, 10);
110 t.sample(1, 2010, 35);
111 const card = summarize(t.records);
112 expect(card.hops[RELAY_HOP]).toMatchObject({ n: 4, p50: 6, p95: 10 });
113 expect(card.hops[READ_BACK_HOP]).toMatchObject({ n: 1, p95: 3 });
114 expect(card.latencyP95Ms).toBe(10 + 3 + 25);
115 expect(summarize(t.records, 101).hops[RELAY_HOP]!.n).toBe(0);
116 });
117 });
118
100119 describe("snap-backs", () => {
101120 test("every listed cause is counted with that cause, per 100 releases", () => {
102121 const t = new Tracker(0);
Software/so101/src/precision.ts +26 −4
@@ -7,7 +7,9 @@
77 * ARRIVE_TICKS; then, for SETTLE_MS: the overshoot past the target, the settling time (until the
88 * last entry into the band) and the oscillations (each exit and re-entry is one)
99 * snap-backs each time the arm is kept from the driver's target without the driver doing it, with its cause
10 * latency, by hop for now the arm server's own: a Goal_Position write to the first read-back past MOVE_TICKS
10 * latency, by hop the arm server's own (a Goal_Position write to the first read-back past MOVE_TICKS), and the two
11 * the relay times on a clock it aligns with the arm server's (src/hops.ts): relay→Pi, from the stamp on
12 * a forwarded command, and read-back→relay, from the read time on a status
1113 *
1214 * One `Tracker` per drive session; `summarize` folds any span of its records into the same numbers, which is how the
1315 * rolling window and the stored session rows are made.
@@ -44,6 +46,11 @@ export function parseSnapBack(body: unknown): { cause: Cause; sizeDeg: number }
4446 return { cause, sizeDeg: Number(sizeDeg.toFixed(2)) };
4547 }
4648
49 /** The hops timed across the link, by name: a duration is only counted when it is from 0 to MAX_HOP_MS. */
50 export const RELAY_HOP = "relay→Pi";
51 export const READ_BACK_HOP = "read-back→relay";
52 export const MAX_HOP_MS = 60_000;
53
4754 export type Kind = "error" | "arrive" | "overshoot" | "settle" | "busToMove";
4855 /** Timestamped samples, by joint and kind: [at, value]. */
4956 export interface Records {
@@ -51,9 +58,11 @@ export interface Records {
5158 snaps: Array<{ at: number; cause: Cause; id: number | null; sizeDeg: number | null }>;
5259 releases: number[];
5360 oscillations: Array<readonly [number, number]>;
61 /** Link hops (RELAY_HOP, READ_BACK_HOP): [at, ms]. */
62 hops: Map<string, Array<readonly [number, number]>>;
5463 }
5564
56 export const emptyRecords = (): Records => ({ joints: new Map(), snaps: [], releases: [], oscillations: [] });
65 export const emptyRecords = (): Records => ({ joints: new Map(), snaps: [], releases: [], oscillations: [], hops: new Map() });
5766
5867 /** Nearest-rank percentile of unsorted values; null for none. */
5968 export function percentile(values: readonly number[], p: number): number | null {
@@ -94,7 +103,7 @@ export interface Card {
94103 trackingP95Deg: number | null;
95104 arriveP95Ms: number | null;
96105 snapBacksPer100Releases: number | null;
97 /** End to end: the sum of every measured hop's p95. Only the arm server's own hop is measured so far. */
106 /** End to end: the sum of every measured hop's p95. */
98107 latencyP95Ms: number | null;
99108 /** The joint with the highest p95 tracking error. */
100109 worstJoint: string | null;
@@ -135,7 +144,7 @@ export function summarize(records: Records, since = -Infinity): Card {
135144 for (const s of snaps) byCause[s.cause]++;
136145 const releases = records.releases.filter((at) => at >= since).length;
137146 const worst = joints.filter((j) => j.errorDeg.p95 !== null).sort((a, b) => b.errorDeg.p95! - a.errorDeg.p95!)[0];
138 const hops = { "bus→move": spread(allBus, 0) };
147 const hops: Record<string, Spread> = { [RELAY_HOP]: spread(after(records.hops.get(RELAY_HOP) ?? []), 2), [READ_BACK_HOP]: spread(after(records.hops.get(READ_BACK_HOP) ?? []), 2), "bus→move": spread(allBus, 0) };
139148 const measured = Object.values(hops).filter((h) => h.p95 !== null);
140149 return {
141150 trackingP95Deg: round(percentile(allErrors.map((t) => t / TICKS_PER_DEGREE), 95)),
@@ -161,6 +170,7 @@ export function trim(records: Records, since: number): void {
161170 keep(records.snaps, (s) => s.at);
162171 keep(records.releases, (at) => at);
163172 keep(records.oscillations, ([at]) => at);
173 for (const list of records.hops.values()) keep(list, ([at]) => at);
164174 }
165175
166176 interface Joint {
@@ -288,6 +298,18 @@ export class Tracker {
288298 for (const records of [this.records, ...this.#sinks]) records.snaps.push({ at, cause, id: null, sizeDeg });
289299 }
290300
301 /** One crossing of a link hop, ms on the aligned clock; a negative or absurd one (the clocks disagree) is not counted. */
302 hop(name: string, ms: number, at: number): boolean {
303 if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0 || ms > MAX_HOP_MS) return false;
304 for (const records of [this.records, ...this.#sinks]) {
305 let list = records.hops.get(name);
306 if (!list) records.hops.set(name, (list = []));
307 list.push([at, ms]);
308 if (list.length > KEEP) list.shift();
309 }
310 return true;
311 }
312
291313 /** The driver let go: a dead-man hold, or the end of the stream. */
292314 release(at: number): void {
293315 for (const records of [this.records, ...this.#sinks]) records.releases.push(at);
Software/so101/src/relay.test.ts +40 −1
@@ -8,13 +8,14 @@ import { gunzipSync } from "node:zlib";
88 import WebSocket, { WebSocketServer } from "ws";
99 import { FeetechBus } from "./bus.ts";
1010 import { CameraHub } from "./cameras.ts";
11 import { wallMs } from "./clock.ts";
1112 import { stamper } from "./command-gate.ts";
1213 import { FakeBus } from "./fake-bus.ts";
1314 import { OFFLINE_FRAME } from "./offline-frame.ts";
1415 import { parseRemote, sameOrigin, startRelay, type Remote, type RunningRelay } from "./relay.ts";
1516 import { startServer, type RunningServer } from "./server.ts";
1617 /** A frame as the arm sees it, without the STOP epoch the relay stamps on it. */
17 const unstamped = (frame: string) => JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(frame) as object).filter(([key]) => key !== "epoch")));
18 const unstamped = (frame: string) => JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(frame) as object).filter(([key]) => key !== "epoch" && key !== "sentAt")));
1819
1920 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
2021 // Bun's node:http can keep a server-closed connection from ending (see server.test.ts): cap every close.
@@ -408,6 +409,44 @@ describe("relay", () => {
408409 expect((await fetch(`${base}/move`, { method: "POST", body: '{"targets":{"1":2000}}' })).status).toBe(200);
409410 });
410411
412 test("the relay aligns its clock with an arm server 5 s ahead: stamps its frames on that clock and reports the read-back hop", async () => {
413 const SKEW = 5000;
414 const armClock = () => wallMs() + SKEW;
415 const frames: Array<{ sentAt?: number; arrived: number }> = [];
416 const reports: number[] = [];
417 const wss = new WebSocketServer({ noServer: true });
418 camera = createServer((_req, res) => res.writeHead(404).end());
419 camera.on("upgrade", (req, socket, head) =>
420 wss.handleUpgrade(req, socket, head, (ws) => {
421 ws.on("message", (d) => {
422 const body = JSON.parse(String(d)) as { ping?: number; readBack?: number[]; sentAt?: number };
423 if (req.url === "/follow") return void frames.push({ sentAt: body.sentAt, arrived: armClock() });
424 if (typeof body.ping === "number") ws.send(JSON.stringify({ pong: { t0: body.ping, t1: armClock(), t2: armClock() } }));
425 if (body.readBack) reports.push(...body.readBack);
426 });
427 }),
428 );
429 const pump = setInterval(() => wss.clients.forEach((c) => c.send(JSON.stringify({ readAt: armClock() - 2, joints: [] }))), 10);
430 try {
431 relay = await startRelay({ port: 0, simulation: simBase, remote: remoteAt(await listening(camera)), link: { ...FAST, staleMs: 500, syncEveryMs: 20 } });
432 const ws = new WebSocket(`ws://127.0.0.1:${relay.port}/follow`);
433 await new Promise((r, j) => (ws.once("open", r), ws.once("error", j)));
434 await sleep(150);
435 ws.send(stamper()({ 1: 2050 }));
436 await sleep(50);
437 expect(frames).toHaveLength(1);
438 const hop = frames[0]!.arrived - frames[0]!.sentAt!;
439 expect(hop).toBeGreaterThanOrEqual(-1); // the skew is gone: a hop of a few ms, not 5000
440 expect(hop).toBeLessThan(50);
441 expect(reports.length).toBeGreaterThan(0);
442 for (const ms of reports) expect(Math.abs(ms - 2)).toBeLessThan(50); // read-back→relay: the 2 ms the fake aged its read, plus a hop
443 ws.close();
444 } finally {
445 clearInterval(pump);
446 for (const c of wss.clients) c.terminate();
447 }
448 });
449
411450 test("a stream on the real arm goes quiet while the link reconnects, and flows again once it is back", async () => {
412451 // An arm server whose /watch can be silenced while its /follow stays up: what the relay passes on is counted.
413452 let watching = true;
Software/so101/src/relay.ts +6 −1
@@ -61,6 +61,7 @@ import { Readable } from "node:stream";
6161 import { pipeline } from "node:stream/promises";
6262 import WebSocket, { WebSocketServer } from "ws";
6363 import { LiveMetrics } from "./live-metrics.ts";
64 import { wallMs } from "./clock.ts";
6465 import { ArmLink, type LinkTimings } from "./arm-link.ts";
6566 import { MachineFeed } from "./machine-feed.ts";
6667 import { refusalBatch } from "./refusals.ts";
@@ -891,7 +892,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
891892 const values = (text: string) => perServo(parseFrame(text) ?? []);
892893 const rate = new FrameRate();
893894 /** A frame as it goes to the arm server: carrying the STOP epoch it was sent under. */
894 const stamped = (frame: string, release: boolean) => JSON.stringify({ ...(JSON.parse(frame) as object), ...(release ? { type: "release" } : {}), epoch });
895 const stamped = (frame: string, release: boolean) => {
896 // `sentAt` is the send time on the arm server's clock (ours plus the offset the link keeps), so it can time the hop; none until the offset is known.
897 const sentAt = real ? armLink?.armNow() ?? null : wallMs();
898 return JSON.stringify({ ...(JSON.parse(frame) as object), ...(release ? { type: "release" } : {}), epoch, ...(sentAt === null ? {} : { sentAt: Number(sentAt.toFixed(3)) }) });
899 };
895900 /** Set when this relay ends the stream for breaking the limits: the arm then holds, as for a stream closed on purpose. */
896901 let overLimit = false;
897902 browser.on("message", (raw) => {
Software/so101/src/server.ts +26 −3
@@ -73,7 +73,7 @@ import { fileURLToPath } from "node:url";
7373 import { ParamsError, factoryValues, readServoParams, recordFactory, validateWrite, writeServoParams } from "./servo-params.ts";
7474 import { WebSocketServer, type WebSocket } from "ws";
7575 import { browserModule } from "./browser-modules.ts";
76 import { Clock, CommandGate, HELD_CLOSE, isRelease } from "./command-gate.ts";
76 import { Clock, CommandGate, HELD_CLOSE, isRelease, sentAtOf } from "./command-gate.ts";
7777 import { FLOOD_CLOSE, FrameRate, frameBytes, MAX_FRAME_BYTES, TOO_BIG_CLOSE } from "./frame-limit.ts";
7878 import type { FeetechBus } from "./bus.ts";
7979 import { ArmModel, gripperTicksToRadians, ticksToRadians, type Vec3, type Violation } from "./kinematics.ts";
@@ -81,7 +81,8 @@ import { fitTablePlane, MAX_TILT_DEG } from "./table-plane.ts";
8181 import { clamp, type Frame } from "./mapping.ts";
8282 import { MachineLog, perServo } from "./machine-log.ts";
8383 import { Metrics } from "./metrics.ts";
84 import { ARRIVE_TICKS, parseSnapBack, type Cause, type Tracker } from "./precision.ts";
84 import { wallMs } from "./clock.ts";
85 import { ARRIVE_TICKS, parseSnapBack, READ_BACK_HOP, RELAY_HOP, type Cause, type Tracker } from "./precision.ts";
8586 import { deployedCommit, PrecisionHistory } from "./precision-history.ts";
8687 import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts";
8788 import { assertPoseName, parsePoseFile, serializePoseFile, type PoseFile } from "./poses.ts";
@@ -1429,6 +1430,9 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
14291430 return end(ws, FLOOD_CLOSE, "too many frames: the stream was closed");
14301431 }
14311432 if (pace === "drop") return void stats.gated++;
1433 // A frame the relay stamped says when it was sent, on this server's clock (the relay aligns it): relay→Pi. The CLI leader's has no stamp and is not counted.
1434 const sentAt = sentAtOf(String(data));
1435 if (sentAt !== null) tracker.hop(RELAY_HOP, wallMs() - sentAt, Date.now());
14321436 const verdict = admission.admit(String(data));
14331437 if (!verdict.ok) {
14341438 if (verdict.drop !== "malformed") {
@@ -1527,18 +1531,33 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
15271531 const watchQuietMs = options.watchQuietMs ?? 200;
15281532 let watched = "";
15291533 let watchedAt = 0;
1534 /** What a watcher may say: {"ping": t0} is answered with {"pong": {t0, t1, t2}} (the four-timestamp ping, src/hops.ts); {"readBack": [ms…]} is the relay's read-back hop. Anything else is ignored. */
1535 const watcherMessage = (text: string, t1: number): string | null => {
1536 let body: { ping?: unknown; readBack?: unknown } | null;
1537 try {
1538 body = JSON.parse(text);
1539 } catch {
1540 return null;
1541 }
1542 if (!body || typeof body !== "object") return null;
1543 if (typeof body.ping === "number" && Number.isFinite(body.ping)) return JSON.stringify({ pong: { t0: body.ping, t1, t2: wallMs() } });
1544 if (Array.isArray(body.readBack)) for (const ms of body.readBack.slice(0, 64)) if (typeof ms === "number") precision.hop(READ_BACK_HOP, ms);
1545 return null;
1546 };
15301547 const machineFrame = (entries: readonly unknown[]) => JSON.stringify({ machine: entries, run });
15311548 const broadcast = async () => {
15321549 if (reading) return; // a slow bus read is not stacked behind another: the next tick asks again
15331550 reading = true;
15341551 try {
15351552 const text = JSON.stringify(await status());
1553 // The read time rides on every message, outside the comparison: a status that did not change is still not sent again.
1554 const sent = `{"readAt":${wallMs().toFixed(3)},${text.slice(1)}`;
15361555 const now = performance.now();
15371556 const same = text === watched && now - watchedAt < watchQuietMs;
15381557 if (!same) [watched, watchedAt] = [text, now];
15391558 for (const w of watchers.clients) {
15401559 if (w.readyState !== w.OPEN || (same && !fresh.has(w))) continue;
1541 w.send(text);
1560 w.send(sent);
15421561 // A new watcher's first message is a status; the machine log so far comes right after it.
15431562 if (fresh.delete(w)) w.send(machineFrame(machine.recent(200)));
15441563 }
@@ -1559,6 +1578,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
15591578 });
15601579 fresh.add(ws);
15611580 void broadcast();
1581 ws.on("message", (data) => {
1582 const reply = watcherMessage(String(data), wallMs());
1583 if (reply) ws.send(reply);
1584 });
15621585 ws.on("error", () => ws.terminate());
15631586 ws.on("close", () => {
15641587 if (watchers.clients.size > 0 || !watching) return;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs