Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Precision scorecard: tracking error, time to arrive, snap-backs with causes, per-hop latency - measured, shown, kept #456
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
quill/arm:quill/436-precision-scorecard-tracking-error-time → main 11 commits fork
17 files
changed +1322
−17
Software/README.md +65
| @@ -552,6 +552,10 @@ watches. A line you type is said in the chat; commands start with `/`: | ||
| 552 | 552 | (serial, name, round trip p50/p95, sent/s, dropped/s, camera fps, frame age, |
| 553 | 553 | stalls, reconnects), from the same `GET /admin/health`. A guest or a plain |
| 554 | 554 | user is told it is for the owner and moderators and sees no rows. |
| 555 | - `/precision`, owner or moderator: Admin → Precision as lines, each headline | |
| 556 | number with its sparkline over the stored sessions, then the worst joint and | |
| 557 | the commit, from the same `GET /precision` (see Precision). Anyone else is | |
| 558 | told it is for the owner and moderators. | |
| 555 | 559 | - `/who` (who drives, who waits), `/help`, `/quit`. |
| 556 | 560 | |
| 557 | 561 | The terminal is a client of the running server, like the page: it opens |
| @@ -930,6 +934,67 @@ curl https://arm--forge-trevato-apps.open-platform.sh/metrics.prom | ||
| 930 | 934 | The endpoint is unauthenticated, like `/link` and `/status`: it exposes only timing aggregates, no names, tokens or |
| 931 | 935 | commands, and cannot move the arm. `GET /metrics` is unchanged and is still the arm server's own, proxied. |
| 932 | 936 | |
| 937 | ## Precision | |
| 938 | ||
| 939 | Every change to how closely the arm follows is judged by one scorecard, measured on the arm server | |
| 940 | (`src/precision.ts`) while a stream drives it: | |
| 941 | ||
| 942 | - **Tracking error**, per joint: the commanded target minus Present_Position at every read-back (each jam-watch | |
| 943 | sample, 100 ms by default), in ticks and degrees; p50, p95 and max. | |
| 944 | - **Time to arrive**: from a target being set, the joint more than 12 ticks from it, to the first read-back within | |
| 945 | 12 ticks. A target that moves during the chase extends the same chase. For 1 s after arriving the joint is watched: | |
| 946 | **overshoot** (ticks past the target on the far side), **settling time** (to the last entry into the band) and | |
| 947 | **oscillations** (each exit and re-entry). | |
| 948 | - **Snap-backs**: each time the arm is kept from the driver's target, once per episode, with its size and a cause from | |
| 949 | a fixed list: `release-park` (the connection was lost and the arm parks), `hold-expired` (the dead-man held it short), | |
| 950 | `zone`, `cap` (a joint limit), `stale-drop`, `maxStep-drop`, `jam`, `STOP`, `turn-end`, `reconnect`. A release is a | |
| 951 | dead-man hold or the end of a stream; the headline is snap-backs per 100 releases. | |
| 952 | - **Latency by hop**: for now the arm server's own, a Goal_Position write to the first read-back more than 3 ticks | |
| 953 | from where the joint was (`bus→move`). The headline is the sum of the measured hops' p95. The hops through the | |
| 954 | browser and the relay, on aligned clocks, are #458; snap-backs the page sees and refusals shown on the page are #457. | |
| 955 | ||
| 956 | `GET /precision` answers the session being driven, the last 10 minutes, the last 48 stored sessions and the hourly | |
| 957 | roll-up (`?hours=1-720` for more), every row tagged with the deployed commit (`FORGE_APP_COMMIT` or the checkout's | |
| 958 | HEAD). The rows live in `precision.sqlite` beside the poses: `$FORGE_APP_DATA/so101/precision.sqlite` on the forge, | |
| 959 | the arm server's data directory on the Pi. An hour keeps the worst of its sessions' p95s. | |
| 960 | ||
| 961 | Where to read it: | |
| 962 | ||
| 963 | - **Admin → Precision** (`/admin`, owner and moderators): the four headline numbers, a sparkline each over the | |
| 964 | stored sessions, the worst joint and the commit. | |
| 965 | - **`/precision` in the terminal** (`$FORGE_APP_SSH`), owner and moderators: the same, as text. | |
| 966 | - **`GET /precision` on the app** (the relay), owner and moderators, signed in as for `/admin`: the arm's scorecard | |
| 967 | as JSON, from whichever arm is live (the simulation on a preview). Anyone else gets the ordinary 404 | |
| 968 | `{"error":"no such route"}` and the arm is not asked. | |
| 969 | - **`GET /precision` on the arm server itself** (`so101 serve`, port 8101 on the Pi's private network, like | |
| 970 | `/metrics`): unauthenticated, for the crew's scripts on that network. It holds timing and position aggregates | |
| 971 | only: no names, tokens or commands. | |
| 972 | ||
| 973 | `bench/precision.ts` replays a fixed gesture script on the fake bus, through the real Governor, with servos that | |
| 974 | follow their goals at 1500 ticks/s, and prints the same scorecard (`--json` for the whole card). Every precision pull | |
| 975 | quotes its numbers before and after. As of #436 (the time to arrive moves by a few hundred ms from run to run with | |
| 976 | the machine's timers; the rest within a few percent): | |
| 977 | ||
| 978 | ||
| 979 | p95 tracking error 8.96 ° (worst joint: shoulder_lift) | |
| 980 | p95 time to arrive 533 ms | |
| 981 | snap-backs 2 in 2 releases: 100 per 100 | |
| 982 | p95 latency 40 ms (bus→move p50 18 ms, p95 40 ms) | |
| 983 | ||
| 984 | joint err p50/p95/max ° arrive p50/p95 ms overshoot max settle p95 ms osc | |
| 985 | shoulder_pan 0 / 8.26 / 23.64 213 / 831 0 831 0 | |
| 986 | shoulder_lift 0.26 / 42.54 / 55.11 22 / 68 10 68 0 | |
| 987 | elbow_flex 0 / 0 / 26.37 213 / 213 0 213 0 | |
| 988 | wrist_flex 0 / 0 / 26.37 212 / 212 0 212 0 | |
| 989 | wrist_roll 0 / 0 / 26.37 213 / 213 0 213 0 | |
| 990 | gripper 3.69 / 12.92 / 16 480 / 533 7 496 0 | |
| 991 | ||
| 992 | by cause: cap 1, maxStep-drop 1 | |
| 993 | ||
| 994 | ||
| 995 | The shoulder lift's p95 is the script walking it at 1500 ticks/s against the 90 °/s speed limit: the Governor's lag, | |
| 996 | which is what the instrument is for. | |
| 997 | ||
| 933 | 998 | ## Video trial |
| 934 | 999 | |
| 935 | 1000 | `so101/bench/video-trial.ts` watches one camera of a deployed page the way a |
Software/so101/bench/precision.test.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { bench, gesture, render } from "./precision.ts"; | |
| 3 | ||
| 4 | test("the gesture script is fixed: the same frames every run", () => { | |
| 5 | expect(gesture()).toEqual(gesture()); | |
| 6 | expect(gesture().length).toBeGreaterThan(100); | |
| 7 | }); | |
| 8 | ||
| 9 | test("a short script on the fake bus gives a scorecard with every headline number", async () => { | |
| 10 | const card = await bench([ | |
| 11 | { at: 0, joints: { 1: 2048 } }, | |
| 12 | { at: 400, joints: { 1: 2348 } }, | |
| 13 | { at: 900, joints: { 1: 2000 } }, // 348 ticks back: within maxStep | |
| 14 | { at: 1000, joints: { 1: 2900 } }, // 900 ticks in one frame: dropped | |
| 15 | ]); | |
| 16 | expect(card.trackingP95Deg).not.toBeNull(); | |
| 17 | expect(card.arriveP95Ms).toBeGreaterThan(0); | |
| 18 | expect(card.latencyP95Ms).toBeGreaterThan(0); | |
| 19 | expect(card.snapBacks.byCause["maxStep-drop"]).toBe(1); | |
| 20 | expect(card.snapBacksPer100Releases).toBe(100); | |
| 21 | expect(render(card)).toContain("p95 tracking error"); | |
| 22 | }, 10_000); |
Software/so101/bench/precision.ts added +102
| @@ -0,0 +1,102 @@ | ||
| 1 | /** | |
| 2 | * The precision scorecard on a bench: a fixed gesture script streamed to the arm server on the fake bus, through the | |
| 3 | * real Governor, with servos that follow their goals at a set speed; then the same scorecard GET /precision gives. | |
| 4 | * bun bench/precision.ts the scorecard, as text | |
| 5 | * bun bench/precision.ts --json the whole card | |
| 6 | * Every precision pull quotes this before and after its change. The script is the same on every run; the numbers move | |
| 7 | * only with the code (and a little with the machine's timers). | |
| 8 | */ | |
| 9 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import WebSocket from "ws"; | |
| 13 | import { FeetechBus } from "../src/bus.ts"; | |
| 14 | import { FakeBus } from "../src/fake-bus.ts"; | |
| 15 | import type { Card } from "../src/precision.ts"; | |
| 16 | import type { Scorecard } from "../src/precision-history.ts"; | |
| 17 | import { startServer } from "../src/server.ts"; | |
| 18 | ||
| 19 | /** One frame of the script: when (ms from the start) and the joints it names. */ | |
| 20 | export interface Step { | |
| 21 | at: number; | |
| 22 | joints: Record<string, number>; | |
| 23 | } | |
| 24 | ||
| 25 | const RANGES: Record<number, [number, number]> = { 1: [818, 3487], 2: [813, 3202], 3: [900, 3100], 4: [700, 3300], 5: [600, 3400], 6: [1995, 3525] }; | |
| 26 | /** STS3215 no-load speed at 7.4 V is about 0.2 s/60°: ~3400 ticks/s. Under load it is far less; this bench says 1500. */ | |
| 27 | export const SERVO_TICKS_S = 1500; | |
| 28 | ||
| 29 | /** The gesture: sweeps at hand speed, a pause long enough for the dead-man, step moves, a jump, a push past a limit. */ | |
| 30 | export function gesture(): Step[] { | |
| 31 | const steps: Step[] = []; | |
| 32 | const hz = 30; | |
| 33 | let at = 0; | |
| 34 | const frame = (joints: Record<string, number>, wait = 1000 / hz) => { | |
| 35 | steps.push({ at: Math.round(at), joints }); | |
| 36 | at += wait; | |
| 37 | }; | |
| 38 | frame({ 1: 2048, 2: 2048, 3: 2048, 4: 2048, 5: 2048, 6: 2200 }, 600); // eased over first | |
| 39 | for (let i = 0; i < 3 * hz; i++) { | |
| 40 | const s = i / hz; | |
| 41 | frame({ 1: Math.round(2048 + 300 * Math.sin(2 * Math.PI * 0.5 * s)), 2: Math.round(2048 + 200 * Math.sin(2 * Math.PI * 0.25 * s)), 6: Math.round(2200 + 150 * (1 - Math.cos(2 * Math.PI * s))) }); | |
| 42 | } | |
| 43 | at += 1500; // let go: the dead-man holds | |
| 44 | for (const [id, to] of [[3, 2348], [4, 1748], [5, 2348], [1, 2348]] as const) frame({ [id]: to }, 900); // steps of 300 ticks | |
| 45 | frame({ 2: 2048 }, 300); | |
| 46 | frame({ 2: 2600 }, 300); // 552 ticks in one frame: dropped | |
| 47 | for (let t = 2048; t <= 3300; t += 300) frame({ 2: t }, 200); // walking up to, then past, the shoulder's limit | |
| 48 | frame({ 2: 3400 }, 600); | |
| 49 | return steps; | |
| 50 | } | |
| 51 | ||
| 52 | /** Runs the script against a fresh arm server and answers its scorecard: the session just driven. */ | |
| 53 | export async function bench(script: readonly Step[] = gesture()): Promise<Card> { | |
| 54 | const fake = new FakeBus([1, 2, 3, 4, 5, 6], { speedTicksS: SERVO_TICKS_S }); | |
| 55 | for (const [id, [min, max]] of Object.entries(RANGES)) fake.servos.get(Number(id))!.set([min & 0xff, min >> 8, max & 0xff, max >> 8], 9); | |
| 56 | const dir = mkdtempSync(join(tmpdir(), "so101-precision-bench-")); | |
| 57 | const server = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, posesFile: join(dir, "poses.json"), modelDir: "/nowhere", commit: "bench", jamSampleMs: 20 }); | |
| 58 | try { | |
| 59 | const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`); | |
| 60 | await new Promise((r, j) => (ws.once("open", r), ws.once("error", j))); | |
| 61 | const start = performance.now(); | |
| 62 | for (const step of script) { | |
| 63 | const wait = step.at - (performance.now() - start); | |
| 64 | if (wait > 0) await new Promise((r) => setTimeout(r, wait)); | |
| 65 | ws.send(JSON.stringify(step.joints)); | |
| 66 | } | |
| 67 | await new Promise((r) => setTimeout(r, 300)); | |
| 68 | ws.close(1000); | |
| 69 | await new Promise((r) => ws.once("close", r)); | |
| 70 | await new Promise((r) => setTimeout(r, 100)); | |
| 71 | const card = (await (await fetch(`http://127.0.0.1:${server.port}/precision`)).json()) as Scorecard; | |
| 72 | return card.window; | |
| 73 | } finally { | |
| 74 | await Promise.race([server.close(), new Promise((r) => setTimeout(r, 500))]); | |
| 75 | rmSync(dir, { recursive: true, force: true }); | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | const show = (v: number | null, unit: string) => (v === null ? "—" : `${v} ${unit}`); | |
| 80 | ||
| 81 | /** The scorecard as text: the headline, then a line per joint, then the snap-backs by cause. */ | |
| 82 | export function render(card: Card): string { | |
| 83 | const lines = [ | |
| 84 | `p95 tracking error ${show(card.trackingP95Deg, "°")} (worst joint: ${card.worstJoint ?? "—"})`, | |
| 85 | `p95 time to arrive ${show(card.arriveP95Ms, "ms")}`, | |
| 86 | `snap-backs ${card.snapBacks.total} in ${card.releases} releases: ${show(card.snapBacksPer100Releases, "per 100")}`, | |
| 87 | `p95 latency ${show(card.latencyP95Ms, "ms")} (${Object.entries(card.hops).map(([hop, s]) => `${hop} p50 ${show(s.p50, "ms")}, p95 ${show(s.p95, "ms")}`).join("; ")})`, | |
| 88 | "", | |
| 89 | "joint err p50/p95/max ° arrive p50/p95 ms overshoot max settle p95 ms osc", | |
| 90 | ...card.joints.map((j) => | |
| 91 | [(j.joint ?? String(j.id)).padEnd(16), `${j.errorDeg.p50 ?? "—"} / ${j.errorDeg.p95 ?? "—"} / ${j.errorDeg.max ?? "—"}`.padEnd(21), `${j.arriveMs.p50 ?? "—"} / ${j.arriveMs.p95 ?? "—"}`.padEnd(19), String(j.overshootTicks.max ?? "—").padEnd(15), String(j.settleMs.p95 ?? "—").padEnd(15), j.oscillations].join(" "), | |
| 92 | ), | |
| 93 | "", | |
| 94 | `by cause: ${Object.entries(card.snapBacks.byCause).filter(([, n]) => n).map(([c, n]) => `${c} ${n}`).join(", ") || "none"}`, | |
| 95 | ]; | |
| 96 | return lines.join("\n"); | |
| 97 | } | |
| 98 | ||
| 99 | if (import.meta.main) { | |
| 100 | const card = await bench(); | |
| 101 | console.log(process.argv.includes("--json") ? JSON.stringify(card, null, 1) : render(card)); | |
| 102 | } |
Software/so101/src/admin-page.ts +5
| @@ -11,6 +11,7 @@ import type { Report } from "./reports.ts"; | ||
| 11 | 11 | import type { Person, Who } from "./identity.ts"; |
| 12 | 12 | import type { Snapshot } from "./turns.ts"; |
| 13 | 13 | import type { ViewerRow } from "./viewer-reports.ts"; |
| 14 | import { precisionSection, type PrecisionPanel } from "./precision-panel.ts"; | |
| 14 | 15 | |
| 15 | 16 | export const esc = (text: string): string => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); |
| 16 | 17 | |
| @@ -56,6 +57,7 @@ th { color: var(--dim); font-weight: 600; } | ||
| 56 | 57 | .bars li { grid-template-columns: 3.5rem 1fr; gap: .5rem; overflow-wrap: normal; font-family: ui-monospace, monospace; border: 0; padding: 0; } |
| 57 | 58 | .bars li span:nth-child(2) { color: var(--blue); } |
| 58 | 59 | .bars li b { color: var(--fg); font-weight: 600; } |
| 60 | .bars.precision li { grid-template-columns: minmax(8rem, 15rem) 1fr; } | |
| 59 | 61 | .inline { display: inline; margin: 0; } |
| 60 | 62 | .empty { color: var(--dim); } |
| 61 | 63 | @media (prefers-reduced-motion: reduce) { * { transition: none !important; } } |
| @@ -151,6 +153,8 @@ export interface AdminPage { | ||
| 151 | 153 | banned?: readonly Target[]; |
| 152 | 154 | /** Owner only: today's peak and joins per hour for the last 24 hours, oldest first. */ |
| 153 | 155 | visitors?: { peak: number; hours: readonly number[] }; |
| 156 | /** The arm's precision scorecard (src/precision-panel.ts); null when the arm did not answer, absent when not asked. */ | |
| 157 | precision?: PrecisionPanel | null; | |
| 154 | 158 | done?: Done | null; |
| 155 | 159 | error?: string | null; |
| 156 | 160 | } |
| @@ -274,6 +278,7 @@ ${p.canEdit ? `<section aria-labelledby="table"><h2 id="table">Table height</h2> | ||
| 274 | 278 | <div class="save"><button type="button" class="go" id="table-save">Save</button> <button type="button" id="table-here">The arm rests on the table now</button> <span id="table-note" role="status"></span></div> |
| 275 | 279 | </section>` : ""} |
| 276 | 280 | ${p.canEdit && p.visitors ? visitorsSection(p.visitors) : ""} |
| 281 | ${p.precision !== undefined ? precisionSection(p.precision, esc) : ""} | |
| 277 | 282 | <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section> |
| 278 | 283 | <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section> |
| 279 | 284 | <section aria-labelledby="moderation"><h2 id="moderation">Moderation</h2>${inForce("mute", p.muted ?? [], canLift)}${inForce("ban", p.banned ?? [], canLift)}${actions}</section> |
Software/so101/src/admin-routes.ts +9 −4
| @@ -5,6 +5,10 @@ import type { Lobby } from "./lobby.ts"; | ||
| 5 | 5 | import { AdminError, changeFromForm } from "./admin.ts"; |
| 6 | 6 | import { sameOrigin } from "./relay.ts"; |
| 7 | 7 | import { adminCsp, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 8 | import type { PrecisionPanel } from "./precision-panel.ts"; | |
| 9 | ||
| 10 | /** Asks the arm for its precision scorecard; only called for someone allowed on the page. */ | |
| 11 | export type AskPrecision = () => Promise<PrecisionPanel | null>; | |
| 8 | 12 | |
| 9 | 13 | /** What a POST needs once the caller is known to be allowed on the page. */ |
| 10 | 14 | export interface AdminSession { |
| @@ -20,7 +24,7 @@ export interface AdminSession { | ||
| 20 | 24 | * Answer 404 to anyone not allowed, and the page itself to GET and HEAD. Returns the session for any other |
| 21 | 25 | * method by an allowed caller, and null when the response has been sent. |
| 22 | 26 | */ |
| 23 | export function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL): AdminSession | null { | |
| 27 | export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, askPrecision?: AskPrecision): Promise<AdminSession | null> { | |
| 24 | 28 | const who = lobby.who(req); |
| 25 | 29 | const html = (status: number, text: string, edit = false) => { |
| 26 | 30 | res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": adminCsp(edit) }); |
| @@ -43,8 +47,9 @@ export function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerRe | ||
| 43 | 47 | } |
| 44 | 48 | return null; |
| 45 | 49 | } |
| 50 | const precision = (req.method === "GET" || req.method === "HEAD") && askPrecision ? await askPrecision() : undefined; | |
| 46 | 51 | const show = (status: number, done: Done | null, error: string | null) => |
| 47 | html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit); | |
| 52 | html(status, renderAdmin({ precision, who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit); | |
| 48 | 53 | if (req.method === "GET" || req.method === "HEAD") { |
| 49 | 54 | const done = url.searchParams.get("done"); |
| 50 | 55 | show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); |
| @@ -63,8 +68,8 @@ const REPORT_ACTIONS = new Set(["report-remove", "report-mute", "report-dismiss" | ||
| 63 | 68 | type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>; |
| 64 | 69 | |
| 65 | 70 | /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */ |
| 66 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody): Promise<void> { | |
| 67 | const session = serveAdminPage(lobby, req, res, url); | |
| 71 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision): Promise<void> { | |
| 72 | const session = await serveAdminPage(lobby, req, res, url, askPrecision); | |
| 68 | 73 | if (!session) return; |
| 69 | 74 | const { who, canEdit, show } = session; |
| 70 | 75 | if (req.method !== "POST") { |
Software/so101/src/fake-bus.ts +23
| @@ -17,6 +17,8 @@ export interface FakeOptions { | ||
| 17 | 17 | jitter?: boolean; |
| 18 | 18 | /** Ids that go silent after answering this many more times (deterministic mid-move dropout). */ |
| 19 | 19 | dropAfter?: Map<number, number>; |
| 20 | /** Goals are followed at this many ticks a second, read by read, instead of reached at once (bench/precision.ts). */ | |
| 21 | speedTicksS?: number; | |
| 20 | 22 | } |
| 21 | 23 | |
| 22 | 24 | /** Enough of an STS3215 to answer the bus: a memory map per id, replies by instruction. */ |
| @@ -28,6 +30,9 @@ export class FakeBus implements Transport { | ||
| 28 | 30 | : ((chunk: Uint8Array) => void) | undefined; |
| 29 | 31 | readonly = new FrameParser(); |
| 30 | 32 | readonly : FakeOptions; |
| 33 | /** With a speed: each servo's goal and when its position was last brought up to date. */ | |
| 34 | readonly = new Map<number, { goal: number; p: number }>(); | |
| 35 | = performance.now(); | |
| 31 | 36 | |
| 32 | 37 | constructor(ids: number[], options: FakeOptions = {}) { |
| 33 | 38 | this. = options; |
| @@ -55,6 +60,7 @@ export class FakeBus implements Transport { | ||
| 55 | 60 | |
| 56 | 61 | write(data: Uint8Array, callback: (error: Error | null | undefined) => void): void { |
| 57 | 62 | callback(null); |
| 63 | this.(); | |
| 58 | 64 | const replies: Array<[number, Uint8Array]> = this..echo ? [[0, data]] : []; |
| 59 | 65 | const replyFrom = (id: number, frame: Uint8Array) => { |
| 60 | 66 | const left = this..dropAfter?.get(id); |
| @@ -134,10 +140,27 @@ export class FakeBus implements Transport { | ||
| 134 | 140 | memory[61] = 900 >> 8; |
| 135 | 141 | return; |
| 136 | 142 | } |
| 143 | if (this..speedTicksS) return void this..set(id, { goal: memory[42]! | (memory[43]! << 8), p: this..get(id)?.p ?? memory[56]! | (memory[57]! << 8) }); | |
| 137 | 144 | memory[56] = memory[42]!; |
| 138 | 145 | memory[57] = memory[43]!; |
| 139 | 146 | } |
| 140 | 147 | |
| 148 | /** With a speed, every moving servo goes the distance the time since the last packet allows toward its goal. */ | |
| 149 | (): void { | |
| 150 | const now = performance.now(); | |
| 151 | const reach = ((now - this.) / 1000) * (this..speedTicksS ?? 0); | |
| 152 | this. = now; | |
| 153 | if (!reach) return; | |
| 154 | for (const [id, g] of this.) { | |
| 155 | const memory = this.servos.get(id)!; | |
| 156 | g.p += Math.max(-reach, Math.min(reach, g.goal - g.p)); | |
| 157 | const next = Math.round(g.p); | |
| 158 | memory[56] = next & 0xff; | |
| 159 | memory[57] = next >> 8; | |
| 160 | if (g.p === g.goal) this..delete(id); | |
| 161 | } | |
| 162 | } | |
| 163 | ||
| 141 | 164 | (from: number, to: number): void { |
| 142 | 165 | const memory = this.servos.get(from)!; |
| 143 | 166 | this.servos.delete(from); |
Software/so101/src/precision-history.test.ts added +143
| @@ -0,0 +1,143 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import WebSocket from "ws"; | |
| 6 | import { FeetechBus } from "./bus.ts"; | |
| 7 | import { FakeBus } from "./fake-bus.ts"; | |
| 8 | import { deployedCommit, PrecisionHistory, type Scorecard } from "./precision-history.ts"; | |
| 9 | import { startServer, type RunningServer } from "./server.ts"; | |
| 10 | ||
| 11 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 12 | const HOUR = 3_600_000; | |
| 13 | ||
| 14 | describe("the history", () => { | |
| 15 | test("one row per session and an hourly roll-up, tagged with the commit, kept across a restart", () => { | |
| 16 | const file = join(mkdtempSync(join(tmpdir(), "so101-precision-")), "precision.sqlite"); | |
| 17 | let now = Date.UTC(2026, 9, 21, 10, 5); | |
| 18 | const history = new PrecisionHistory({ file, commit: "abc1234", now: () => now }); | |
| 19 | for (const short of [10, 100]) { | |
| 20 | const t = history.begin(); | |
| 21 | t.target(1, 2048, now); | |
| 22 | t.sample(1, 2048 - short, now + 10); | |
| 23 | t.release(now + 20); | |
| 24 | t.snapBack("jam", now + 20, 1, short); | |
| 25 | now += 60_000; | |
| 26 | history.end(t); | |
| 27 | } | |
| 28 | history.close(); | |
| 29 | const again = new PrecisionHistory({ file, commit: "def5678", now: () => now }); | |
| 30 | const card = again.scorecard(); | |
| 31 | expect(card.commit).toBe("def5678"); | |
| 32 | expect(card.sessions).toHaveLength(2); | |
| 33 | expect(card.sessions.map((r) => r.commit)).toEqual(["abc1234", "abc1234"]); | |
| 34 | expect(card.sessions[1]!.trackingP95Deg).toBeCloseTo(8.79, 1); | |
| 35 | expect(card.hours).toHaveLength(1); | |
| 36 | expect(card.hours[0]).toMatchObject({ at: "2026-10-21T10:00:00.000Z", commit: "abc1234", sessions: 2, snapBacks: 2, releases: 2, worstJoint: "shoulder_pan" }); | |
| 37 | // the hour keeps the worse session's p95 | |
| 38 | expect(card.hours[0]!.trackingP95Deg).toBeCloseTo(8.79, 1); | |
| 39 | again.close(); | |
| 40 | }); | |
| 41 | ||
| 42 | test("the window is the last ten minutes, and a session that measured nothing is not stored", () => { | |
| 43 | let now = 0; | |
| 44 | const history = new PrecisionHistory({ commit: "abc1234", now: () => now }); | |
| 45 | const t = history.begin(); | |
| 46 | t.target(1, 2048, 0); | |
| 47 | t.sample(1, 2000, 0); | |
| 48 | expect(history.scorecard().session?.joints[0]?.errorTicks.n).toBe(1); | |
| 49 | history.end(t); | |
| 50 | now = HOUR; | |
| 51 | expect(history.scorecard().window.trackingP95Deg).toBeNull(); | |
| 52 | expect(history.end(history.begin()).trackingP95Deg).toBeNull(); | |
| 53 | expect(history.scorecard().sessions).toHaveLength(1); | |
| 54 | }); | |
| 55 | ||
| 56 | test("the commit comes from the environment, else the checkout's HEAD, else unknown", () => { | |
| 57 | expect(deployedCommit({ FORGE_APP_COMMIT: "ABCDEF0123456789" }, "/nowhere")).toBe("abcdef012345"); | |
| 58 | expect(deployedCommit({ FORGE_APP_COMMIT: "not a commit" }, "/nowhere")).toBe("unknown"); | |
| 59 | const root = mkdtempSync(join(tmpdir(), "so101-git-")); | |
| 60 | mkdirSync(join(root, ".git/refs/heads"), { recursive: true }); | |
| 61 | writeFileSync(join(root, ".git/HEAD"), "ref: refs/heads/main\n"); | |
| 62 | writeFileSync(join(root, ".git/packed-refs"), `${"1".repeat(40)} refs/heads/main\n`); | |
| 63 | expect(deployedCommit({}, root)).toBe("111111111111"); | |
| 64 | writeFileSync(join(root, ".git/refs/heads/main"), `${"2".repeat(40)}\n`); | |
| 65 | expect(deployedCommit({}, root)).toBe("222222222222"); | |
| 66 | }); | |
| 67 | }); | |
| 68 | ||
| 69 | describe("GET /precision on the arm server", () => { | |
| 70 | let fake: FakeBus; | |
| 71 | let server: RunningServer; | |
| 72 | let base: string; | |
| 73 | beforeAll(async () => { | |
| 74 | const dir = mkdtempSync(join(tmpdir(), "so101-precision-serve-")); | |
| 75 | fake = new FakeBus([1, 2], { stuck: new Set([2]) }); | |
| 76 | fake.servos.get(1)!.set([0x32, 0x03, 0x9f, 0x0d], 9); // 818-3487 | |
| 77 | fake.servos.get(2)!.set([0x2d, 0x03, 0x82, 0x0c], 9); // 813-3202 | |
| 78 | server = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, ids: [1, 2], posesFile: join(dir, "poses.json"), watchdogMs: 5000, jamSampleMs: 10, commit: "feed123", modelDir: "/nowhere" }); | |
| 79 | base = `http://127.0.0.1:${server.port}`; | |
| 80 | }); | |
| 81 | afterAll(() => Promise.race([server.close(), sleep(500)])); | |
| 82 | const card = async () => (await (await fetch(`${base}/precision`)).json()) as Scorecard; | |
| 83 | ||
| 84 | test("a stream's tracking error is measured, and a limit, a jump, a jam and a STOP are snap-backs with their cause", async () => { | |
| 85 | const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`); | |
| 86 | await new Promise((r) => ws.once("open", r)); | |
| 87 | ws.send(JSON.stringify({ "1": 2100 })); | |
| 88 | await sleep(150); | |
| 89 | for (const t of [2450, 2800, 3150]) { | |
| 90 | ws.send(JSON.stringify({ "1": t })); | |
| 91 | await sleep(60); | |
| 92 | } | |
| 93 | ws.send(JSON.stringify({ "1": 3600 })); // past the limit (3457): capped | |
| 94 | await sleep(60); | |
| 95 | ws.send(JSON.stringify({ "1": 3700 })); // still capped: the same episode | |
| 96 | await sleep(60); | |
| 97 | ws.send(JSON.stringify({ "1": 2000 })); // 1457 ticks in one frame: dropped | |
| 98 | await sleep(60); | |
| 99 | ws.send(JSON.stringify({ "2": 2600 })); // joint 2 is stuck: it jams | |
| 100 | await sleep(400); | |
| 101 | const live = await card(); | |
| 102 | expect(live.commit).toBe("feed123"); | |
| 103 | expect(live.session?.joints.find((j) => j.id === 1)?.errorTicks.n).toBeGreaterThan(0); | |
| 104 | ws.send(JSON.stringify({ "1": 3100 })); // 357 ticks away at 90°/s: still on its way when the stop comes | |
| 105 | await sleep(80); | |
| 106 | await fetch(`${base}/stop`, { method: "POST", body: JSON.stringify({ by: "test" }) }); | |
| 107 | await new Promise((r) => ws.once("close", r)); | |
| 108 | await sleep(100); | |
| 109 | await fetch(`${base}/resume`, { method: "POST", body: JSON.stringify({ by: "test" }) }); | |
| 110 | const after = await card(); | |
| 111 | expect((await fetch(`${base}/precision?hours=0`)).status).toBe(400); | |
| 112 | expect((await fetch(`${base}/precision?hours=721`)).status).toBe(400); | |
| 113 | expect(((await (await fetch(`${base}/precision?hours=336`)).json()) as Scorecard).hours).toHaveLength(1); | |
| 114 | expect(after.session).toBeNull(); | |
| 115 | const [row] = after.sessions; | |
| 116 | expect(row).toMatchObject({ commit: "feed123", sessions: 1 }); | |
| 117 | const causes = after.window.snapBacks.byCause; | |
| 118 | expect(causes.cap).toBe(1); | |
| 119 | expect(causes["maxStep-drop"]).toBe(1); | |
| 120 | expect(causes.jam).toBe(1); | |
| 121 | expect(causes.STOP).toBe(1); | |
| 122 | expect(after.window.releases).toBe(1); | |
| 123 | expect(after.window.trackingP95Deg).not.toBeNull(); | |
| 124 | }); | |
| 125 | ||
| 126 | 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 () => { | |
| 127 | const before = (await card()).window.snapBacks.byCause; | |
| 128 | const ws = new WebSocket(`ws://127.0.0.1:${server.port}/follow`); | |
| 129 | await new Promise((r) => ws.once("open", r)); | |
| 130 | ws.send(JSON.stringify({ "1": 1500 })); | |
| 131 | await sleep(600); | |
| 132 | ws.send(JSON.stringify({ "1": 1850 })); // on its way at the governor's pace when the turn ends | |
| 133 | await sleep(80); | |
| 134 | const stop = await fetch(`${base}/stop`, { method: "POST", body: JSON.stringify({ by: "the relay", hold: false }) }); | |
| 135 | expect(stop.status).toBe(200); | |
| 136 | await new Promise((r) => ws.once("close", r)); | |
| 137 | await sleep(100); | |
| 138 | const after = await card(); | |
| 139 | expect(after.window.snapBacks.byCause["turn-end"]).toBe(before["turn-end"] + 1); | |
| 140 | expect(after.window.snapBacks.byCause.STOP).toBe(before.STOP); | |
| 141 | expect(after.sessions.at(-1)).toMatchObject({ commit: "feed123", releases: 1 }); | |
| 142 | }); | |
| 143 | }); |
Software/so101/src/precision-history.ts added +138
| @@ -0,0 +1,138 @@ | ||
| 1 | /** | |
| 2 | * The precision scorecard kept: the session being driven, the rolling 10-minute window, one row per drive session | |
| 3 | * and an hourly roll-up, every row tagged with the commit that measured it, in a sqlite file beside the poses. | |
| 4 | * The numbers are src/precision.ts's; this module only keeps them and answers GET /precision. | |
| 5 | */ | |
| 6 | ||
| 7 | import { Database } from "bun:sqlite"; | |
| 8 | import { existsSync, readFileSync } from "node:fs"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { emptyRecords, summarize, trim, Tracker, WINDOW_MS, type Card } from "./precision.ts"; | |
| 11 | ||
| 12 | /** The deployed commit: the forge's or CI's variable when set, else the checkout's HEAD, else "unknown". Never a shell. */ | |
| 13 | export function deployedCommit(env: Record<string, string | undefined> = process.env, root = join(import.meta.dir, "../../..")): string { | |
| 14 | const named = env.FORGE_APP_COMMIT ?? env.FORGE_COMMIT ?? env.GIT_COMMIT ?? env.SOURCE_COMMIT; | |
| 15 | if (named && /^[0-9a-f]{7,40}$/i.test(named)) return named.slice(0, 12).toLowerCase(); | |
| 16 | try { | |
| 17 | const git = join(root, ".git"); | |
| 18 | const head = readFileSync(join(git, "HEAD"), "utf8").trim(); | |
| 19 | const ref = /^ref: (refs\/[\w./-]+)$/.exec(head)?.[1]; | |
| 20 | let id = ref ? (existsSync(join(git, ref)) ? readFileSync(join(git, ref), "utf8").trim() : "") : head; | |
| 21 | if (ref && !id) id = readFileSync(join(git, "packed-refs"), "utf8").split("\n").find((l) => l.endsWith(` ${ref}`))?.split(" ")[0] ?? ""; | |
| 22 | if (/^[0-9a-f]{40}$/.test(id)) return id.slice(0, 12); | |
| 23 | } catch { | |
| 24 | /* no checkout here */ | |
| 25 | } | |
| 26 | return "unknown"; | |
| 27 | } | |
| 28 | ||
| 29 | /** One stored drive session, or one hour of them: the headline numbers. */ | |
| 30 | export interface Row { | |
| 31 | at: string; | |
| 32 | commit: string; | |
| 33 | sessions: number; | |
| 34 | seconds: number; | |
| 35 | trackingP95Deg: number | null; | |
| 36 | trackingMaxDeg: number | null; | |
| 37 | arriveP95Ms: number | null; | |
| 38 | snapBacks: number; | |
| 39 | releases: number; | |
| 40 | latencyP95Ms: number | null; | |
| 41 | worstJoint: string | null; | |
| 42 | } | |
| 43 | ||
| 44 | export interface Scorecard { | |
| 45 | commit: string; | |
| 46 | /** The session being driven now, or null. */ | |
| 47 | session: Card | null; | |
| 48 | /** The last ten minutes, sessions pooled. */ | |
| 49 | window: Card; | |
| 50 | /** The last stored sessions and hours, oldest first: the trend across releases. */ | |
| 51 | sessions: Row[]; | |
| 52 | hours: Row[]; | |
| 53 | } | |
| 54 | ||
| 55 | type Stored = { at: string; commit: string; sessions: number; seconds: number; tracking_p95_deg: number | null; tracking_max_deg: number | null; arrive_p95_ms: number | null; snap_backs: number; releases: number; latency_p95_ms: number | null; worst_joint: string | null }; | |
| 56 | const fromStored = (r: Stored): Row => ({ at: r.at, commit: r.commit, sessions: r.sessions, seconds: r.seconds, trackingP95Deg: r.tracking_p95_deg, trackingMaxDeg: r.tracking_max_deg, arriveP95Ms: r.arrive_p95_ms, snapBacks: r.snap_backs, releases: r.releases, latencyP95Ms: r.latency_p95_ms, worstJoint: r.worst_joint }); | |
| 57 | ||
| 58 | export class PrecisionHistory { | |
| 59 | readonly commit: string; | |
| 60 | readonly : Database; | |
| 61 | readonly : () => number; | |
| 62 | readonly = emptyRecords(); | |
| 63 | : Tracker | null = null; | |
| 64 | ||
| 65 | constructor(options: { file?: string; commit?: string; now?: () => number } = {}) { | |
| 66 | this.commit = options.commit ?? deployedCommit(); | |
| 67 | this. = options.now ?? Date.now; | |
| 68 | this. = new Database(options.file ?? ":memory:", { create: true, strict: true }); | |
| 69 | this..run("PRAGMA journal_mode = WAL"); | |
| 70 | const columns = `commit_id TEXT NOT NULL, sessions INTEGER NOT NULL, seconds REAL NOT NULL, tracking_p95_deg REAL, tracking_max_deg REAL, arrive_p95_ms REAL, | |
| 71 | snap_backs INTEGER NOT NULL, releases INTEGER NOT NULL, latency_p95_ms REAL, worst_joint TEXT`; | |
| 72 | this..run(`CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY, at TEXT NOT NULL, ${columns}, card TEXT NOT NULL)`); | |
| 73 | // An hour's roll-up keeps the worst of its sessions' p95s: one bad session in the hour is what the trend must show. | |
| 74 | this..run(`CREATE TABLE IF NOT EXISTS hours (at TEXT NOT NULL, ${columns}, PRIMARY KEY (at, commit_id))`); | |
| 75 | } | |
| 76 | ||
| 77 | /** A drive session starts: its tracker, whose records also feed the window. */ | |
| 78 | begin(): Tracker { | |
| 79 | this. = new Tracker(this.(), [this.]); | |
| 80 | return this.; | |
| 81 | } | |
| 82 | ||
| 83 | /** The session ends: its row and its hour are written. A session that measured nothing is not kept. */ | |
| 84 | end(tracker: Tracker): Card { | |
| 85 | const at = this.(); | |
| 86 | tracker.finish(at); | |
| 87 | if (this. === tracker) this. = null; | |
| 88 | const card = summarize(tracker.records); | |
| 89 | const measured = card.joints.some((j) => j.errorTicks.n > 0) || card.snapBacks.total > 0; | |
| 90 | if (!measured) return card; | |
| 91 | const seconds = Number(((at - tracker.startedAt) / 1000).toFixed(1)); | |
| 92 | const maxDeg = card.joints.reduce<number | null>((m, j) => (j.errorDeg.max === null ? m : Math.max(m ?? 0, j.errorDeg.max)), null); | |
| 93 | const row = [this.commit, 1, seconds, card.trackingP95Deg, maxDeg, card.arriveP95Ms, card.snapBacks.total, card.releases, card.latencyP95Ms, card.worstJoint] as const; | |
| 94 | const iso = new Date(at).toISOString(); | |
| 95 | this..query(`INSERT INTO sessions (at, commit_id, sessions, seconds, tracking_p95_deg, tracking_max_deg, arrive_p95_ms, snap_backs, releases, latency_p95_ms, worst_joint, card) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(iso, ...row, JSON.stringify(card)); | |
| 96 | const hour = `${iso.slice(0, 13)}:00:00.000Z`; | |
| 97 | this. | |
| 98 | .query( | |
| 99 | `INSERT INTO hours (at, commit_id, sessions, seconds, tracking_p95_deg, tracking_max_deg, arrive_p95_ms, snap_backs, releases, latency_p95_ms, worst_joint) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| 100 | ON CONFLICT (at, commit_id) DO UPDATE SET sessions = sessions + 1, seconds = seconds + excluded.seconds, | |
| 101 | tracking_p95_deg = max(coalesce(tracking_p95_deg, excluded.tracking_p95_deg), coalesce(excluded.tracking_p95_deg, tracking_p95_deg)), | |
| 102 | tracking_max_deg = max(coalesce(tracking_max_deg, excluded.tracking_max_deg), coalesce(excluded.tracking_max_deg, tracking_max_deg)), | |
| 103 | arrive_p95_ms = max(coalesce(arrive_p95_ms, excluded.arrive_p95_ms), coalesce(excluded.arrive_p95_ms, arrive_p95_ms)), | |
| 104 | latency_p95_ms = max(coalesce(latency_p95_ms, excluded.latency_p95_ms), coalesce(excluded.latency_p95_ms, latency_p95_ms)), | |
| 105 | snap_backs = snap_backs + excluded.snap_backs, releases = releases + excluded.releases, | |
| 106 | worst_joint = CASE WHEN excluded.tracking_p95_deg >= coalesce(tracking_p95_deg, -1) THEN excluded.worst_joint ELSE worst_joint END`, | |
| 107 | ) | |
| 108 | .run(hour, ...row); | |
| 109 | return card; | |
| 110 | } | |
| 111 | ||
| 112 | /** The stored rows, oldest first. */ | |
| 113 | rows(table: "sessions" | "hours", limit = 48): Row[] { | |
| 114 | const sql = | |
| 115 | table === "sessions" | |
| 116 | ? `SELECT at, commit_id AS "commit", sessions, seconds, tracking_p95_deg, tracking_max_deg, arrive_p95_ms, snap_backs, releases, latency_p95_ms, worst_joint FROM sessions ORDER BY id DESC LIMIT ?` | |
| 117 | : `SELECT at, commit_id AS "commit", sessions, seconds, tracking_p95_deg, tracking_max_deg, arrive_p95_ms, snap_backs, releases, latency_p95_ms, worst_joint FROM hours ORDER BY at DESC LIMIT ?`; | |
| 118 | const rows = this..query(sql).all(limit) as Stored[]; | |
| 119 | return rows.reverse().map(fromStored); | |
| 120 | } | |
| 121 | ||
| 122 | /** `hours`: how many hourly rows, newest kept (two weeks of them compare one week with the last). */ | |
| 123 | scorecard(hours = 48): Scorecard { | |
| 124 | const now = this.(); | |
| 125 | trim(this., now - WINDOW_MS); | |
| 126 | return { | |
| 127 | commit: this.commit, | |
| 128 | session: this. ? summarize(this..records) : null, | |
| 129 | window: summarize(this., now - WINDOW_MS), | |
| 130 | sessions: this.rows("sessions"), | |
| 131 | hours: this.rows("hours", hours), | |
| 132 | }; | |
| 133 | } | |
| 134 | ||
| 135 | close(): void { | |
| 136 | this..close(); | |
| 137 | } | |
| 138 | } |
Software/so101/src/precision-panel.test.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | import { afterEach, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { esc } from "./admin-page.ts"; | |
| 6 | import { sign } from "./identity.ts"; | |
| 7 | import { Lobby } from "./lobby.ts"; | |
| 8 | import { precisionSection, readPrecision, sparkline } from "./precision-panel.ts"; | |
| 9 | import { startRelay, type RunningRelay } from "./relay.ts"; | |
| 10 | ||
| 11 | const row = (trackingP95Deg: number | null, snapBacks: number, releases: number) => ({ at: "2026-10-21T10:00:00.000Z", commit: "abc1234", sessions: 1, seconds: 30, trackingP95Deg, trackingMaxDeg: 9, arriveP95Ms: 200, snapBacks, releases, latencyP95Ms: 40, worstJoint: "elbow_flex" }); | |
| 12 | const scorecard = (window: Record<string, unknown> = {}) => ({ commit: "abc1234", session: null, window: { trackingP95Deg: null, arriveP95Ms: null, snapBacksPer100Releases: null, latencyP95Ms: null, worstJoint: null, ...window }, sessions: [row(1, 1, 4), row(3, 0, 2), row(2, 2, 2)], hours: [] }); | |
| 13 | ||
| 14 | describe("reading /precision", () => { | |
| 15 | test("the window's numbers when it has them, else the last session's, and a trend per number", () => { | |
| 16 | const p = readPrecision(scorecard({ trackingP95Deg: 0.5, worstJoint: "wrist_flex" }))!; | |
| 17 | expect(p.headline.map((h) => h.value)).toEqual([0.5, 200, 100, 40]); | |
| 18 | expect(p.headline[0]!.trend).toEqual([1, 3, 2]); | |
| 19 | expect(p.headline[2]!.trend).toEqual([25, 0, 100]); | |
| 20 | expect(p.worstJoint).toBe("wrist_flex"); | |
| 21 | expect(readPrecision(scorecard())!.worstJoint).toBe("elbow_flex"); | |
| 22 | }); | |
| 23 | ||
| 24 | test("anything that is not a scorecard is null; a field of the wrong type is a gap, never an error", () => { | |
| 25 | expect(readPrecision("nope")).toBeNull(); | |
| 26 | expect(readPrecision({ commit: 1, sessions: [] })).toBeNull(); | |
| 27 | const p = readPrecision({ commit: "x", sessions: [{ trackingP95Deg: "9" }], window: [] })!; | |
| 28 | expect(p.headline[0]!.value).toBeNull(); | |
| 29 | expect(p.headline[0]!.trend).toEqual([null]); | |
| 30 | }); | |
| 31 | ||
| 32 | test("a sparkline scales lowest to highest and leaves a gap where nothing was measured", () => { | |
| 33 | expect(sparkline([1, 3, 2, null, 5])).toBe("▁▅▃ █"); | |
| 34 | expect(sparkline([2, 2])).toBe("▁▁"); | |
| 35 | expect(sparkline([null])).toBe(""); | |
| 36 | }); | |
| 37 | ||
| 38 | test("what came over the wire is escaped", () => { | |
| 39 | const html = precisionSection(readPrecision({ ...scorecard({ worstJoint: "<img src=x onerror=alert(1)>" }), commit: "<b>" }), esc); | |
| 40 | expect(html).not.toContain("<img"); | |
| 41 | expect(html).not.toContain("<b><"); | |
| 42 | expect(html).toContain("<img"); | |
| 43 | }); | |
| 44 | }); | |
| 45 | ||
| 46 | describe("the Precision panel on /admin", () => { | |
| 47 | const KEY = "k".repeat(64); | |
| 48 | const identity = `id-trevato|trevato|admin|${Date.now() + 600_000}`; | |
| 49 | const owner = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 50 | const guestIdentity = `id-bob|bob|user|${Date.now() + 600_000}`; | |
| 51 | const guest = { "x-forge-identity": guestIdentity, "x-forge-signature": sign(guestIdentity, KEY) }; | |
| 52 | let dir = ""; | |
| 53 | let relay: RunningRelay | undefined; | |
| 54 | let lobby: Lobby | undefined; | |
| 55 | let arm: ReturnType<typeof Bun.serve> | undefined; | |
| 56 | afterEach(async () => { | |
| 57 | await relay?.close(); | |
| 58 | lobby?.close(); | |
| 59 | arm?.stop(true); | |
| 60 | rmSync(dir, { recursive: true, force: true }); | |
| 61 | }); | |
| 62 | const boot = async (answer: (() => Response) | null) => { | |
| 63 | dir = mkdtempSync(join(tmpdir(), "so101-precision-panel-")); | |
| 64 | let asked = 0; | |
| 65 | arm = answer ? Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (req) => (new URL(req.url).pathname === "/precision" ? (asked++, answer()) : new Response("{}")) }) : undefined; | |
| 66 | lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json"), countsFile: join(dir, "visitors.json") }); | |
| 67 | relay = await startRelay({ port: 0, simulation: arm ? `http://127.0.0.1:${arm.port}` : "http://127.0.0.1:1", lobby }); | |
| 68 | return { base: `http://127.0.0.1:${relay.port}`, asked: () => asked }; | |
| 69 | }; | |
| 70 | ||
| 71 | test("the owner sees the four headline numbers, the worst joint and the commit; a stranger gets 404 and the arm is not asked", async () => { | |
| 72 | const { base, asked } = await boot(() => Response.json(scorecard({ trackingP95Deg: 0.5 }))); | |
| 73 | expect((await fetch(`${base}/admin`)).status).toBe(404); | |
| 74 | expect(asked()).toBe(0); | |
| 75 | const html = await (await fetch(`${base}/admin`, { headers: owner })).text(); | |
| 76 | expect(html).toContain(`<h2 id="precision">Precision</h2>`); | |
| 77 | for (const label of ["Tracking error, p95", "Time to arrive, p95", "Snap-backs per 100 releases", "Latency, p95"]) expect(html).toContain(label); | |
| 78 | expect(html).toContain("<b>0.5°</b>"); | |
| 79 | expect(html).toContain("elbow_flex"); | |
| 80 | expect(html).toContain("commit abc1234"); | |
| 81 | }); | |
| 82 | ||
| 83 | test("an arm that does not answer is said so, and the page still renders", async () => { | |
| 84 | const { base } = await boot(null); | |
| 85 | const res = await fetch(`${base}/admin`, { headers: owner }); | |
| 86 | expect(res.status).toBe(200); | |
| 87 | expect(await res.text()).toContain("did not answer <code>/precision</code>"); | |
| 88 | }); | |
| 89 | ||
| 90 | test("GET /precision on the public server: the owner gets the arm's scorecard; a stranger or a signed-in guest gets 404 and the arm is not asked", async () => { | |
| 91 | const { base, asked } = await boot(() => Response.json(scorecard({ trackingP95Deg: 0.5 }))); | |
| 92 | for (const headers of [{}, guest]) { | |
| 93 | const refused = await fetch(`${base}/precision`, { headers }); | |
| 94 | expect(refused.status).toBe(404); | |
| 95 | expect(await refused.json()).toEqual({ error: "no such route" }); | |
| 96 | } | |
| 97 | expect(asked()).toBe(0); | |
| 98 | const res = await fetch(`${base}/precision?hours=336`, { headers: owner }); | |
| 99 | expect(res.status).toBe(200); | |
| 100 | expect(await res.json()).toMatchObject({ commit: "abc1234", window: { trackingP95Deg: 0.5 } }); | |
| 101 | expect(asked()).toBe(1); | |
| 102 | expect((await fetch(`${base}/precision?hours=0`, { headers: owner })).status).toBe(400); | |
| 103 | expect((await fetch(`${base}/precision?hours=1;x`, { headers: owner })).status).toBe(400); | |
| 104 | expect(asked()).toBe(1); | |
| 105 | }); | |
| 106 | ||
| 107 | test("GET /precision says so when the arm does not answer", async () => { | |
| 108 | const { base } = await boot(null); | |
| 109 | expect((await fetch(`${base}/precision`, { headers: owner })).status).toBe(502); | |
| 110 | }); | |
| 111 | }); |
Software/so101/src/precision-panel.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * The Precision panel of /admin: the arm server's GET /precision (src/precision-history.ts) read field by field, for | |
| 3 | * the answer comes over the network from another machine, and drawn as four headline numbers, each with a sparkline of | |
| 4 | * the stored sessions, oldest first, and the worst joint named. Plain text and characters; no script. | |
| 5 | */ | |
| 6 | ||
| 7 | const SPARK = "▁▂▃▄▅▆▇█"; | |
| 8 | const TREND = 24; | |
| 9 | ||
| 10 | export interface Headline { | |
| 11 | label: string; | |
| 12 | unit: string; | |
| 13 | value: number | null; | |
| 14 | /** The same number, session by session, oldest first; null where a session did not measure it. */ | |
| 15 | trend: Array<number | null>; | |
| 16 | } | |
| 17 | ||
| 18 | export interface PrecisionPanel { | |
| 19 | commit: string; | |
| 20 | worstJoint: string | null; | |
| 21 | sessions: number; | |
| 22 | headline: Headline[]; | |
| 23 | } | |
| 24 | ||
| 25 | const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); | |
| 26 | const text = (v: unknown, max = 40): string | null => (typeof v === "string" && v.length ? [...v.replace(/[\p{Cc}\p{Cf}]/gu, "")].slice(0, max).join("") : null); | |
| 27 | const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}); | |
| 28 | ||
| 29 | /** The panel's numbers from whatever /precision answered; null when it was not a scorecard at all. */ | |
| 30 | export function readPrecision(body: unknown): PrecisionPanel | null { | |
| 31 | const card = obj(body); | |
| 32 | if (typeof card.commit !== "string" || !Array.isArray(card.sessions)) return null; | |
| 33 | const window = obj(card.window); | |
| 34 | const rows = card.sessions.slice(-TREND).map(obj); | |
| 35 | const last = rows.at(-1) ?? {}; | |
| 36 | // The window when it measured something, else the last stored session: the panel never goes blank between drives. | |
| 37 | const pick = (fromWindow: unknown, fromRow: unknown) => num(fromWindow) ?? num(fromRow); | |
| 38 | const rate = (r: Record<string, unknown>) => { | |
| 39 | const snaps = num(r.snapBacks), releases = num(r.releases); | |
| 40 | return snaps !== null && releases ? Number(((snaps / releases) * 100).toFixed(1)) : null; | |
| 41 | }; | |
| 42 | return { | |
| 43 | commit: text(card.commit) ?? "unknown", | |
| 44 | worstJoint: text(window.worstJoint) ?? text(last.worstJoint), | |
| 45 | sessions: rows.length, | |
| 46 | headline: [ | |
| 47 | { label: "Tracking error, p95", unit: "°", value: pick(window.trackingP95Deg, last.trackingP95Deg), trend: rows.map((r) => num(r.trackingP95Deg)) }, | |
| 48 | { label: "Time to arrive, p95", unit: "ms", value: pick(window.arriveP95Ms, last.arriveP95Ms), trend: rows.map((r) => num(r.arriveP95Ms)) }, | |
| 49 | { label: "Snap-backs per 100 releases", unit: "", value: pick(window.snapBacksPer100Releases, rate(last)), trend: rows.map(rate) }, | |
| 50 | { label: "Latency, p95, bus→motion", unit: "ms", value: pick(window.latencyP95Ms, last.latencyP95Ms), trend: rows.map((r) => num(r.latencyP95Ms)) }, | |
| 51 | ], | |
| 52 | }; | |
| 53 | } | |
| 54 | ||
| 55 | /** A headline number with its unit, or a dash when nothing measured it. */ | |
| 56 | export const headlineValue = (h: Headline): string => (h.value === null ? "—" : `${h.value}${h.unit && h.unit !== "°" ? " " : ""}${h.unit}`); | |
| 57 | ||
| 58 | /** A row of block characters, lowest to highest; a gap for a session that did not measure it. */ | |
| 59 | export function sparkline(values: ReadonlyArray<number | null>): string { | |
| 60 | const known = values.filter((v): v is number => v !== null); | |
| 61 | if (!known.length) return ""; | |
| 62 | const lo = Math.min(...known), hi = Math.max(...known); | |
| 63 | return values.map((v) => (v === null ? " " : SPARK[hi === lo ? 0 : Math.round(((v - lo) / (hi - lo)) * (SPARK.length - 1))])).join(""); | |
| 64 | } | |
| 65 | ||
| 66 | /** The section; `esc` is the page's own escaping, applied to everything that came over the wire. */ | |
| 67 | export function precisionSection(p: PrecisionPanel | null | undefined, esc: (s: string) => string): string { | |
| 68 | const head = `<section aria-labelledby="precision"><h2 id="precision">Precision</h2>`; | |
| 69 | if (!p) return `${head}<p class="empty">The arm server did not answer <code>/precision</code>.</p></section>`; | |
| 70 | if (!p.sessions && p.headline.every((h) => h.value === null)) return `${head}<p class="empty">Nothing measured yet: drive the arm and the numbers appear. Commit ${esc(p.commit)}.</p></section>`; | |
| 71 | const items = p.headline | |
| 72 | .map((h) => { | |
| 73 | const value = headlineValue(h); | |
| 74 | const spark = sparkline(h.trend); | |
| 75 | return `<li><span>${esc(h.label)}</span><span><b>${esc(value)}</b>${spark ? ` <span aria-hidden="true">${spark}</span>` : ""}</span></li>`; | |
| 76 | }) | |
| 77 | .join(""); | |
| 78 | return `${head}<p>Worst joint: <b>${esc(p.worstJoint ?? "—")}</b> · last 10 minutes, else the last session · trend over ${p.sessions} session${p.sessions === 1 ? "" : "s"} · commit ${esc(p.commit)}</p><ol class="bars precision" aria-label="Precision, headline numbers">${items}</ol></section>`; | |
| 79 | } |
Software/so101/src/precision.test.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { ARRIVE_TICKS, CAUSES, emptyRecords, percentile, SETTLE_MS, summarize, trim, Tracker } from "./precision.ts"; | |
| 3 | ||
| 4 | describe("percentile", () => { | |
| 5 | test("nearest rank, unsorted input, none for an empty list", () => { | |
| 6 | expect(percentile([5, 1, 4, 2, 3], 50)).toBe(3); | |
| 7 | expect(percentile(Array.from({ length: 100 }, (_, i) => i + 1), 95)).toBe(95); | |
| 8 | expect(percentile([7], 95)).toBe(7); | |
| 9 | expect(percentile([], 50)).toBeNull(); | |
| 10 | }); | |
| 11 | }); | |
| 12 | ||
| 13 | describe("tracking error", () => { | |
| 14 | test("is target minus read-back, in ticks and degrees, per joint and pooled", () => { | |
| 15 | const t = new Tracker(0); | |
| 16 | t.target(1, 2048, 0); | |
| 17 | // 20 read-backs 0..19 ticks short of the target on joint 1; joint 2 always 114 ticks (10°) short. | |
| 18 | for (let i = 0; i < 20; i++) t.sample(1, 2048 - i, i * 10); | |
| 19 | t.target(2, 2162, 0); | |
| 20 | for (let i = 0; i < 20; i++) t.sample(2, 2048, i * 10); | |
| 21 | const card = summarize(t.records); | |
| 22 | const [j1, j2] = card.joints; | |
| 23 | expect(j1!.errorTicks).toEqual({ n: 20, p50: 9, p95: 18, max: 19 }); | |
| 24 | expect(j2!.errorDeg.p95).toBeCloseTo(10.02, 1); | |
| 25 | expect(card.worstJoint).toBe("shoulder_lift"); | |
| 26 | expect(card.trackingP95Deg).toBeCloseTo(10.02, 1); | |
| 27 | }); | |
| 28 | ||
| 29 | test("a joint with no target yet is not counted", () => { | |
| 30 | const t = new Tracker(0); | |
| 31 | t.sample(1, 2000, 0); | |
| 32 | expect(summarize(t.records).trackingP95Deg).toBeNull(); | |
| 33 | }); | |
| 34 | }); | |
| 35 | ||
| 36 | describe("time to arrive, overshoot, settling", () => { | |
| 37 | test("a clean approach: arrival when first within the band, no overshoot, settled on arrival", () => { | |
| 38 | const t = new Tracker(0); | |
| 39 | t.sample(1, 1000, 0); | |
| 40 | t.target(1, 1500, 0); | |
| 41 | for (let at = 10, p = 1000; p < 1500; at += 10, p = Math.min(1500, p + 50)) t.sample(1, Math.min(1500, p + 50), at); | |
| 42 | for (let at = 110; at <= 110 + SETTLE_MS; at += 50) t.sample(1, 1500, at); | |
| 43 | const j = summarize(t.records).joints[0]!; | |
| 44 | // 50 ticks a read-back: 1450 at 90 ms is still outside the band, 1500 at 100 ms is the arrival. | |
| 45 | expect(j.arriveMs.p50).toBe(100); | |
| 46 | expect(j.overshootTicks.max).toBe(0); | |
| 47 | expect(j.settleMs.p50).toBe(100); | |
| 48 | expect(j.oscillations).toBe(0); | |
| 49 | }); | |
| 50 | ||
| 51 | test("overshoot past the far side, and each exit and re-entry of the band is an oscillation", () => { | |
| 52 | const t = new Tracker(0); | |
| 53 | t.sample(1, 1000, 0); | |
| 54 | t.target(1, 1500, 0); | |
| 55 | // arrives at 100 ms, swings 40 past, back inside, 20 short, back inside. | |
| 56 | const trace: Array<[number, number]> = [[50, 1300], [100, 1495], [150, 1540], [200, 1505], [250, 1480], [300, 1500]]; | |
| 57 | for (const [at, p] of trace) t.sample(1, p, at); | |
| 58 | t.finish(400); | |
| 59 | const j = summarize(t.records).joints[0]!; | |
| 60 | expect(j.arriveMs.p50).toBe(100); | |
| 61 | expect(j.overshootTicks.max).toBe(40); | |
| 62 | expect(j.oscillations).toBe(2); | |
| 63 | expect(j.settleMs.p50).toBe(300); | |
| 64 | }); | |
| 65 | ||
| 66 | test("a target that moves during the chase is one chase, timed to the catch-up", () => { | |
| 67 | const t = new Tracker(0); | |
| 68 | t.sample(1, 1000, 0); | |
| 69 | t.target(1, 1200, 0); | |
| 70 | t.sample(1, 1100, 50); | |
| 71 | t.target(1, 1300, 60); | |
| 72 | t.sample(1, 1200, 100); | |
| 73 | t.sample(1, 1300 - ARRIVE_TICKS, 150); | |
| 74 | expect(summarize(t.records).joints[0]!.arriveMs).toMatchObject({ n: 1, p50: 150 }); | |
| 75 | }); | |
| 76 | ||
| 77 | test("a target already within the band starts no chase", () => { | |
| 78 | const t = new Tracker(0); | |
| 79 | t.sample(1, 1000, 0); | |
| 80 | t.target(1, 1005, 0); | |
| 81 | t.sample(1, 1005, 10); | |
| 82 | expect(summarize(t.records).joints[0]!.arriveMs.n).toBe(0); | |
| 83 | }); | |
| 84 | }); | |
| 85 | ||
| 86 | describe("bus to motion", () => { | |
| 87 | test("from the write to the first read-back more than 3 ticks from where it was", () => { | |
| 88 | const t = new Tracker(0); | |
| 89 | t.sample(1, 2000, 0); | |
| 90 | t.wrote(1, 10); | |
| 91 | t.sample(1, 2003, 20); // not yet | |
| 92 | t.sample(1, 2010, 35); | |
| 93 | const card = summarize(t.records); | |
| 94 | expect(card.joints[0]!.busToMoveMs.p50).toBe(25); | |
| 95 | expect(card.hops["bus→move"]!.p95).toBe(25); | |
| 96 | expect(card.latencyP95Ms).toBe(25); | |
| 97 | }); | |
| 98 | }); | |
| 99 | ||
| 100 | describe("snap-backs", () => { | |
| 101 | test("every listed cause is counted with that cause, per 100 releases", () => { | |
| 102 | const t = new Tracker(0); | |
| 103 | CAUSES.forEach((cause, i) => t.snapBack(cause, i, 1, 114)); | |
| 104 | for (let i = 0; i < 20; i++) t.release(i); | |
| 105 | const card = summarize(t.records); | |
| 106 | for (const cause of CAUSES) expect(card.snapBacks.byCause[cause]).toBe(1); | |
| 107 | expect(card.snapBacks.total).toBe(CAUSES.length); | |
| 108 | expect(card.snapBacksPer100Releases).toBe(50); | |
| 109 | expect(card.snapBacks.sizeDeg.p50).toBeCloseTo(10.02, 1); | |
| 110 | }); | |
| 111 | ||
| 112 | test("forget: a joint re-pinned (a hold, a jam) is chased by nothing, so neither error nor arrival is counted until a new target", () => { | |
| 113 | const t = new Tracker(0); | |
| 114 | t.sample(1, 2000, 0); | |
| 115 | t.sample(2, 2000, 0); | |
| 116 | t.target(1, 3000, 0); | |
| 117 | t.target(2, 3000, 0); | |
| 118 | t.sample(1, 2000, 10); | |
| 119 | t.sample(2, 2000, 10); | |
| 120 | t.forget(1); | |
| 121 | t.sample(1, 2000, 20); // left where it was pinned: no error, it is not chasing 3000 any more | |
| 122 | t.sample(1, 3000, 30); // nor an arrival | |
| 123 | t.sample(2, 3000, 30); | |
| 124 | const [one, two] = summarize(t.records).joints; | |
| 125 | expect(one!.errorTicks.n).toBe(1); | |
| 126 | expect(one!.arriveMs.n).toBe(0); | |
| 127 | expect(two!.errorTicks.n).toBe(2); | |
| 128 | expect(two!.arriveMs).toMatchObject({ n: 1, p50: 30 }); | |
| 129 | t.forget(); | |
| 130 | t.sample(2, 2500, 40); | |
| 131 | expect(summarize(t.records).joints[1]!.errorTicks.n).toBe(2); // nothing counted for either after forgetting both | |
| 132 | t.target(1, 2000, 50); | |
| 133 | t.sample(1, 2000, 60); | |
| 134 | expect(summarize(t.records).joints[0]!.arriveMs).toMatchObject({ n: 1, p50: 10 }); | |
| 135 | }); | |
| 136 | ||
| 137 | test("with no release, the rate is unknown rather than infinite", () => { | |
| 138 | const t = new Tracker(0); | |
| 139 | t.snapBack("jam", 0); | |
| 140 | expect(summarize(t.records).snapBacksPer100Releases).toBeNull(); | |
| 141 | }); | |
| 142 | }); | |
| 143 | ||
| 144 | describe("the window", () => { | |
| 145 | test("records go to the sinks too, and trim drops what is older", () => { | |
| 146 | const window = emptyRecords(); | |
| 147 | const t = new Tracker(0, [window]); | |
| 148 | t.target(1, 2048, 0); | |
| 149 | t.sample(1, 2000, 0); | |
| 150 | t.sample(1, 2040, 1000); | |
| 151 | t.snapBack("zone", 0); | |
| 152 | trim(window, 500); | |
| 153 | expect(summarize(window).joints[0]!.errorTicks).toMatchObject({ n: 1, max: 8 }); | |
| 154 | expect(summarize(window).snapBacks.total).toBe(0); | |
| 155 | expect(summarize(t.records).joints[0]!.errorTicks.n).toBe(2); | |
| 156 | expect(summarize(t.records, 500).joints[0]!.errorTicks.n).toBe(1); | |
| 157 | }); | |
| 158 | }); |
Software/so101/src/precision.ts added +288
| @@ -0,0 +1,288 @@ | ||
| 1 | /** | |
| 2 | * The precision instrument: how closely the real arm follows what its driver asks of it. Plain data in (targets, | |
| 3 | * read-backs, bus writes, snap-backs, each with its time in ms), plain data out (a scorecard). | |
| 4 | * | |
| 5 | * tracking error commanded target minus Present_Position, per joint, at every read-back of a drive session | |
| 6 | * time to arrive from a target being set (with the joint out of reach of it) to the first read-back within | |
| 7 | * ARRIVE_TICKS; then, for SETTLE_MS: the overshoot past the target, the settling time (until the | |
| 8 | * last entry into the band) and the oscillations (each exit and re-entry is one) | |
| 9 | * 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 | |
| 11 | * | |
| 12 | * One `Tracker` per drive session; `summarize` folds any span of its records into the same numbers, which is how the | |
| 13 | * rolling window and the stored session rows are made. | |
| 14 | */ | |
| 15 | ||
| 16 | import { JOINTS } from "./sts3215.ts"; | |
| 17 | ||
| 18 | /** Ticks from the target that count as arrived. */ | |
| 19 | export const ARRIVE_TICKS = 12; | |
| 20 | /** Ticks a joint must move past where it was written from to count as started. */ | |
| 21 | export const MOVE_TICKS = 3; | |
| 22 | /** How long after arriving the joint is watched for overshoot and oscillation, ms. */ | |
| 23 | export const SETTLE_MS = 1000; | |
| 24 | /** The rolling window, ms. */ | |
| 25 | export const WINDOW_MS = 10 * 60_000; | |
| 26 | /** Most samples one record list keeps per joint and kind; the oldest go first. */ | |
| 27 | const KEEP = 50_000; | |
| 28 | const TICKS_PER_DEGREE = 4096 / 360; | |
| 29 | ||
| 30 | /** Why the arm was kept from the target: a fixed list, so every count means the same thing release to release. */ | |
| 31 | export const CAUSES = ["release-park", "hold-expired", "zone", "cap", "stale-drop", "maxStep-drop", "jam", "STOP", "turn-end", "reconnect"] as const; | |
| 32 | export type Cause = (typeof CAUSES)[number]; | |
| 33 | export const isCause = (value: unknown): value is Cause => typeof value === "string" && (CAUSES as readonly string[]).includes(value); | |
| 34 | ||
| 35 | export type Kind = "error" | "arrive" | "overshoot" | "settle" | "busToMove"; | |
| 36 | /** Timestamped samples, by joint and kind: [at, value]. */ | |
| 37 | export interface Records { | |
| 38 | joints: Map<number, Record<Kind, Array<readonly [number, number]>>>; | |
| 39 | snaps: Array<{ at: number; cause: Cause; id: number | null; sizeDeg: number | null }>; | |
| 40 | releases: number[]; | |
| 41 | oscillations: Array<readonly [number, number]>; | |
| 42 | } | |
| 43 | ||
| 44 | export const emptyRecords = (): Records => ({ joints: new Map(), snaps: [], releases: [], oscillations: [] }); | |
| 45 | ||
| 46 | /** Nearest-rank percentile of unsorted values; null for none. */ | |
| 47 | export function percentile(values: readonly number[], p: number): number | null { | |
| 48 | if (!values.length) return null; | |
| 49 | const sorted = [...values].sort((a, b) => a - b); | |
| 50 | return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))]!; | |
| 51 | } | |
| 52 | ||
| 53 | export interface Spread { | |
| 54 | n: number; | |
| 55 | p50: number | null; | |
| 56 | p95: number | null; | |
| 57 | max: number | null; | |
| 58 | } | |
| 59 | ||
| 60 | const round = (v: number | null, digits = 2) => (v === null ? null : Number(v.toFixed(digits))); | |
| 61 | const spread = (values: readonly number[], digits = 2): Spread => ({ | |
| 62 | n: values.length, | |
| 63 | p50: round(percentile(values, 50), digits), | |
| 64 | p95: round(percentile(values, 95), digits), | |
| 65 | max: round(values.length ? Math.max(...values) : null, digits), | |
| 66 | }); | |
| 67 | ||
| 68 | export interface JointCard { | |
| 69 | id: number; | |
| 70 | joint: string | null; | |
| 71 | errorTicks: Spread; | |
| 72 | errorDeg: Spread; | |
| 73 | arriveMs: Spread; | |
| 74 | overshootTicks: Spread; | |
| 75 | settleMs: Spread; | |
| 76 | oscillations: number; | |
| 77 | busToMoveMs: Spread; | |
| 78 | } | |
| 79 | ||
| 80 | export interface Card { | |
| 81 | /** The headline numbers; null where nothing was measured. */ | |
| 82 | trackingP95Deg: number | null; | |
| 83 | arriveP95Ms: number | null; | |
| 84 | snapBacksPer100Releases: number | null; | |
| 85 | /** End to end: the sum of every measured hop's p95. Only the arm server's own hop is measured so far. */ | |
| 86 | latencyP95Ms: number | null; | |
| 87 | /** The joint with the highest p95 tracking error. */ | |
| 88 | worstJoint: string | null; | |
| 89 | joints: JointCard[]; | |
| 90 | snapBacks: { total: number; byCause: Record<Cause, number>; sizeDeg: Spread }; | |
| 91 | releases: number; | |
| 92 | hops: Record<string, Spread>; | |
| 93 | } | |
| 94 | ||
| 95 | /** The numbers for every record at or after `since`. */ | |
| 96 | export function summarize(records: Records, since = -Infinity): Card { | |
| 97 | const after = (list: ReadonlyArray<readonly [number, number]>) => list.filter(([at]) => at >= since).map(([, v]) => v); | |
| 98 | const joints: JointCard[] = []; | |
| 99 | const allErrors: number[] = []; | |
| 100 | const allArrive: number[] = []; | |
| 101 | const allBus: number[] = []; | |
| 102 | for (const [id, r] of [...records.joints].sort(([a], [b]) => a - b)) { | |
| 103 | const errors = after(r.error); | |
| 104 | allErrors.push(...errors); | |
| 105 | const arrive = after(r.arrive); | |
| 106 | allArrive.push(...arrive); | |
| 107 | const bus = after(r.busToMove); | |
| 108 | allBus.push(...bus); | |
| 109 | joints.push({ | |
| 110 | id, | |
| 111 | joint: JOINTS[id] ?? null, | |
| 112 | errorTicks: spread(errors, 0), | |
| 113 | errorDeg: spread(errors.map((t) => t / TICKS_PER_DEGREE)), | |
| 114 | arriveMs: spread(arrive, 0), | |
| 115 | overshootTicks: spread(after(r.overshoot), 0), | |
| 116 | settleMs: spread(after(r.settle), 0), | |
| 117 | oscillations: records.oscillations.filter(([at, j]) => at >= since && j === id).length, | |
| 118 | busToMoveMs: spread(bus, 0), | |
| 119 | }); | |
| 120 | } | |
| 121 | const snaps = records.snaps.filter((s) => s.at >= since); | |
| 122 | const byCause = Object.fromEntries(CAUSES.map((c) => [c, 0])) as Record<Cause, number>; | |
| 123 | for (const s of snaps) byCause[s.cause]++; | |
| 124 | const releases = records.releases.filter((at) => at >= since).length; | |
| 125 | const worst = joints.filter((j) => j.errorDeg.p95 !== null).sort((a, b) => b.errorDeg.p95! - a.errorDeg.p95!)[0]; | |
| 126 | const hops = { "bus→move": spread(allBus, 0) }; | |
| 127 | const measured = Object.values(hops).filter((h) => h.p95 !== null); | |
| 128 | return { | |
| 129 | trackingP95Deg: round(percentile(allErrors.map((t) => t / TICKS_PER_DEGREE), 95)), | |
| 130 | arriveP95Ms: round(percentile(allArrive, 95), 0), | |
| 131 | snapBacksPer100Releases: releases ? round((snaps.length / releases) * 100, 1) : null, | |
| 132 | latencyP95Ms: measured.length ? measured.reduce((sum, h) => sum + h.p95!, 0) : null, | |
| 133 | worstJoint: worst ? (worst.joint ?? String(worst.id)) : null, | |
| 134 | joints, | |
| 135 | snapBacks: { total: snaps.length, byCause, sizeDeg: spread(snaps.flatMap((s) => (s.sizeDeg === null ? [] : [s.sizeDeg]))) }, | |
| 136 | releases, | |
| 137 | hops, | |
| 138 | }; | |
| 139 | } | |
| 140 | ||
| 141 | /** Drops what is older than `since` from every list. */ | |
| 142 | export function trim(records: Records, since: number): void { | |
| 143 | const keep = <T>(list: T[], at: (x: T) => number) => { | |
| 144 | let n = 0; | |
| 145 | while (n < list.length && at(list[n]!) < since) n++; | |
| 146 | if (n) list.splice(0, n); | |
| 147 | }; | |
| 148 | for (const r of records.joints.values()) for (const list of Object.values(r)) keep(list, ([at]) => at); | |
| 149 | keep(records.snaps, (s) => s.at); | |
| 150 | keep(records.releases, (at) => at); | |
| 151 | keep(records.oscillations, ([at]) => at); | |
| 152 | } | |
| 153 | ||
| 154 | interface Joint { | |
| 155 | target?: number; | |
| 156 | present?: number; | |
| 157 | /** A target not yet reached: since when, and from which side (null until the first read-back says where the joint was). */ | |
| 158 | pending?: { start: number; target: number; from: number | null }; | |
| 159 | /** Arrived, and watched for SETTLE_MS. */ | |
| 160 | settling?: { start: number; arrived: number; target: number; dir: number; overshoot: number; inside: boolean; lastEntry: number; crossings: number }; | |
| 161 | /** A write not yet seen as motion. */ | |
| 162 | written?: { at: number; from: number }; | |
| 163 | } | |
| 164 | ||
| 165 | /** One drive session's measurements; every record also goes to the sinks (the rolling window). */ | |
| 166 | export class Tracker { | |
| 167 | readonly startedAt: number; | |
| 168 | readonly records = emptyRecords(); | |
| 169 | readonly : Records[]; | |
| 170 | readonly = new Map<number, Joint>(); | |
| 171 | ||
| 172 | constructor(startedAt: number, sinks: Records[] = []) { | |
| 173 | this.startedAt = startedAt; | |
| 174 | this. = sinks; | |
| 175 | } | |
| 176 | ||
| 177 | (id: number, kind: Kind, at: number, value: number): void { | |
| 178 | for (const records of [this.records, ...this.]) { | |
| 179 | let r = records.joints.get(id); | |
| 180 | if (!r) records.joints.set(id, (r = { error: [], arrive: [], overshoot: [], settle: [], busToMove: [] })); | |
| 181 | r[kind].push([at, value]); | |
| 182 | if (r[kind].length > KEEP) r[kind].shift(); | |
| 183 | } | |
| 184 | } | |
| 185 | ||
| 186 | (id: number): Joint { | |
| 187 | let j = this..get(id); | |
| 188 | if (!j) this..set(id, (j = {})); | |
| 189 | return j; | |
| 190 | } | |
| 191 | ||
| 192 | /** The driver's target for a joint, ticks, as the server commands it. */ | |
| 193 | target(id: number, ticks: number, at: number): void { | |
| 194 | const j = this.(id); | |
| 195 | j.target = ticks; | |
| 196 | if (j.settling && Math.abs(ticks - j.settling.target) > ARRIVE_TICKS) this.(id, j); | |
| 197 | if (j.present === undefined) { | |
| 198 | // Not read yet: a chase from an unknown place, confirmed or dropped by the first read-back. | |
| 199 | if (j.pending) j.pending.target = ticks; | |
| 200 | else j.pending = { start: at, target: ticks, from: null }; | |
| 201 | return; | |
| 202 | } | |
| 203 | if (Math.abs(ticks - j.present) <= ARRIVE_TICKS) { | |
| 204 | if (j.pending) j.pending.target = ticks; | |
| 205 | return; | |
| 206 | } | |
| 207 | // A target that moves while the joint chases it extends the same chase: time to arrive is time to catch up. | |
| 208 | if (j.pending) j.pending.target = ticks; | |
| 209 | else if (!j.settling) j.pending = { start: at, target: ticks, from: j.present }; | |
| 210 | } | |
| 211 | ||
| 212 | /** A Goal_Position went on the bus for this joint. */ | |
| 213 | wrote(id: number, at: number): void { | |
| 214 | const j = this.(id); | |
| 215 | if (!j.written && j.present !== undefined) j.written = { at, from: j.present }; | |
| 216 | } | |
| 217 | ||
| 218 | /** A read-back of Present_Position. */ | |
| 219 | sample(id: number, present: number, at: number): void { | |
| 220 | const j = this.(id); | |
| 221 | j.present = present; | |
| 222 | if (j.written && Math.abs(present - j.written.from) > MOVE_TICKS) { | |
| 223 | this.(id, "busToMove", at, at - j.written.at); | |
| 224 | j.written = undefined; | |
| 225 | } | |
| 226 | if (j.target === undefined) return; | |
| 227 | const error = j.target - present; | |
| 228 | this.(id, "error", at, Math.abs(error)); | |
| 229 | if (j.pending && j.pending.from === null) { | |
| 230 | // The first read-back: already there is no chase (it cannot be timed); otherwise the chase is on from here. | |
| 231 | if (Math.abs(error) <= ARRIVE_TICKS) j.pending = undefined; | |
| 232 | else j.pending.from = present; | |
| 233 | return; | |
| 234 | } | |
| 235 | if (j.pending && Math.abs(j.pending.target - present) <= ARRIVE_TICKS) { | |
| 236 | const start = j.pending.start; | |
| 237 | this.(id, "arrive", at, at - start); | |
| 238 | // The side it came from: past the target on the far side is overshoot. | |
| 239 | const dir = Math.sign(j.pending.target - (j.pending.from ?? present)) || 1; | |
| 240 | j.settling = { start, arrived: at, target: j.pending.target, dir, overshoot: Math.max(0, (present - j.pending.target) * dir), inside: true, lastEntry: at, crossings: 0 }; | |
| 241 | j.pending = undefined; | |
| 242 | return; | |
| 243 | } | |
| 244 | const s = j.settling; | |
| 245 | if (!s) return; | |
| 246 | const past = (present - s.target) * s.dir; | |
| 247 | s.overshoot = Math.max(s.overshoot, past); | |
| 248 | const inside = Math.abs(present - s.target) <= ARRIVE_TICKS; | |
| 249 | if (inside !== s.inside) { | |
| 250 | s.crossings++; | |
| 251 | if (inside) s.lastEntry = at; | |
| 252 | s.inside = inside; | |
| 253 | } | |
| 254 | if (at - s.arrived >= SETTLE_MS) this.(id, j, at); | |
| 255 | } | |
| 256 | ||
| 257 | /** The settle watch ends: overshoot, settling time and oscillations are written. */ | |
| 258 | (id: number, j: Joint, at = j.settling!.arrived): void { | |
| 259 | const s = j.settling!; | |
| 260 | j.settling = undefined; | |
| 261 | this.(id, "overshoot", s.arrived, Math.max(0, s.overshoot)); | |
| 262 | if (s.inside) this.(id, "settle", s.arrived, s.lastEntry - s.start); | |
| 263 | for (let n = 0; n < Math.floor(s.crossings / 2); n++) for (const records of [this.records, ...this.]) records.oscillations.push([at, id]); | |
| 264 | // Left the band and never came back: the joint is chasing the same target again. | |
| 265 | if (!s.inside && j.target !== undefined && j.present !== undefined) j.pending = { start: at, target: j.target, from: j.present }; | |
| 266 | } | |
| 267 | ||
| 268 | /** The arm was kept from the driver's target; `sizeDeg` is how far, when the server knows. */ | |
| 269 | snapBack(cause: Cause, at: number, id: number | null = null, sizeTicks: number | null = null): void { | |
| 270 | const entry = { at, cause, id, sizeDeg: sizeTicks === null ? null : Number((Math.abs(sizeTicks) / TICKS_PER_DEGREE).toFixed(2)) }; | |
| 271 | for (const records of [this.records, ...this.]) records.snaps.push(entry); | |
| 272 | } | |
| 273 | ||
| 274 | /** The driver let go: a dead-man hold, or the end of the stream. */ | |
| 275 | release(at: number): void { | |
| 276 | for (const records of [this.records, ...this.]) records.releases.push(at); | |
| 277 | } | |
| 278 | ||
| 279 | /** Forget the targets (a hold or a jam re-pins the joints): nothing is being chased now. */ | |
| 280 | forget(id?: number): void { | |
| 281 | for (const [jid, j] of this.) if (id === undefined || id === jid) (j.target = undefined), (j.pending = undefined), (j.settling = undefined); | |
| 282 | } | |
| 283 | ||
| 284 | /** Ends any settle watch still open, so the last arrival's overshoot counts. */ | |
| 285 | finish(at: number): void { | |
| 286 | for (const [id, j] of this.) if (j.settling) this.(id, j, at); | |
| 287 | } | |
| 288 | } |
Software/so101/src/relay.ts +32 −1
| @@ -36,6 +36,7 @@ | ||
| 36 | 36 | * POST /join {"name": "…"}: become someone here, no forge account needed (src/accounts.ts); the answer |
| 37 | 37 | * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}} |
| 38 | 38 | * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log |
| 39 | * GET /precision?hours=1-720 owner and moderators: the arm's precision scorecard (src/precision-history.ts); 404 to anyone else | |
| 39 | 40 | * GET /link {"mode": "live"|"reconnecting"|"offline"|"simulated", "host": "<host:port>"|null, "problem": "…"|null} |
| 40 | 41 | * GET /status the arm's own /status, and which arm said it: "source": "live <host:port>", "reconnecting to the arm: |
| 41 | 42 | * <why>" (the last known status, with "reconnecting": true and "seenAt"; 503 before |
| @@ -68,6 +69,7 @@ import { AccountError, sessionCookie, visitor } from "./accounts.ts"; | ||
| 68 | 69 | import { CameraSocket } from "./camera-socket.ts"; |
| 69 | 70 | import { OFFLINE_FRAME } from "./offline-frame.ts"; |
| 70 | 71 | import { handleAdmin, handleLift } from "./admin-routes.ts"; |
| 72 | import { readPrecision } from "./precision-panel.ts"; | |
| 71 | 73 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 72 | 74 | import { CameraError, CameraHub } from "./cameras.ts"; |
| 73 | 75 | import { VideoFeed, type VideoSources } from "./video-feed.ts"; |
| @@ -400,6 +402,34 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 400 | 402 | const body = (await answer.json()) as Record<string, unknown>; |
| 401 | 403 | return { code: answer.status, body: { ...body, held: gate.held ?? body.held ?? null, source: source() } }; |
| 402 | 404 | }; |
| 405 | /** The arm's GET /precision (src/precision-history.ts), from whichever arm is live; `hours` already checked. */ | |
| 406 | const armPrecision = async (hours: string | null) => | |
| 407 | fetch(`${remote && onArm() ? remote.http : simulation}/precision${hours === null ? "" : `?hours=${hours}`}`, { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 1000)) }); | |
| 408 | /** The arm's precision scorecard for the admin page, read field by field; null when the arm does not answer within a second. */ | |
| 409 | const askPrecision = async () => { | |
| 410 | try { | |
| 411 | const answer = await armPrecision(null); | |
| 412 | return answer.ok ? readPrecision(await answer.json()) : null; | |
| 413 | } catch { | |
| 414 | return null; | |
| 415 | } | |
| 416 | }; | |
| 417 | /** GET /precision: the scorecard as JSON, for the owner and moderators, who see it on /admin; to anyone else there is no such route. */ | |
| 418 | const precisionRead = async (req: IncomingMessage, res: ServerResponse, url: URL) => { | |
| 419 | if (!lobby || !lobby.who(req) || !lobby.moderates(req)) return json(res, 404, { error: "no such route" }); | |
| 420 | if (req.method !== "GET") { | |
| 421 | res.setHeader("allow", "GET"); | |
| 422 | return json(res, 405, { error: "GET" }); | |
| 423 | } | |
| 424 | const hours = url.searchParams.get("hours"); | |
| 425 | if (hours !== null && !(/^\d{1,3}$/.test(hours) && Number(hours) >= 1 && Number(hours) <= 720)) return json(res, 400, { error: "hours must be 1-720" }); | |
| 426 | try { | |
| 427 | const answer = await armPrecision(hours); | |
| 428 | return json(res, answer.status, await answer.json()); | |
| 429 | } catch (err) { | |
| 430 | return json(res, 502, { error: `the arm did not answer /precision (${reason(err)})` }); | |
| 431 | } | |
| 432 | }; | |
| 403 | 433 | const status = async (res: ServerResponse, path: string) => { |
| 404 | 434 | const { code, body } = await statusOf(path); |
| 405 | 435 | return json(res, code, body); |
| @@ -570,7 +600,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 570 | 600 | const cameraAdmin = ADMIN_CAMERA.exec(url.pathname); |
| 571 | 601 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 572 | 602 | if (lobby && url.pathname === "/admin/lift") return await handleLift(lobby, req, res, readBody); |
| 573 | if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody); | |
| 603 | if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision); | |
| 604 | if (url.pathname === "/precision") return await precisionRead(req, res, url); | |
| 574 | 605 | if (url.pathname === LEADER) return await leaderCalibration(req, res); |
| 575 | 606 | if (url.pathname === "/join") { |
| 576 | 607 | if (req.method === "POST") return await join(req, res); |
Software/so101/src/server.ts +74 −5
| @@ -31,6 +31,9 @@ | ||
| 31 | 31 | * PUT /settings change any of those |
| 32 | 32 | * POST /settings/table-here put the table (tableOffsetMm, -100..100) under the arm's lowest link now, the margin below it |
| 33 | 33 | * GET /metrics jams, blocks, stalls, peak load and temperature per joint, recent events |
| 34 | * GET /precision the precision scorecard (src/precision.ts): tracking error, time to arrive, snap-backs by cause, | |
| 35 | * latency by hop, for the session being driven, the last 10 minutes, and the stored sessions and hours; | |
| 36 | * ?hours=1-720 hourly rows (48 by default) | |
| 34 | 37 | * GET /model.json the arm model: joints, the model's floor (floorZ) and the enforced table (tableZ), where the URDF is served |
| 35 | 38 | * GET /leader-map.js the leader calibration mapping, for the browser (src/leader-map.js) |
| 36 | 39 | * GET /model/<file> the URDF and its meshes; GET /vendor/<pkg>/<file> three.js and the URDF loader |
| @@ -69,6 +72,8 @@ import { ArmModel, gripperTicksToRadians, ticksToRadians, type Violation } from | ||
| 69 | 72 | import { clamp, type Frame } from "./mapping.ts"; |
| 70 | 73 | import { MachineLog, perServo } from "./machine-log.ts"; |
| 71 | 74 | import { Metrics } from "./metrics.ts"; |
| 75 | import { ARRIVE_TICKS, type Cause, type Tracker } from "./precision.ts"; | |
| 76 | import { PrecisionHistory } from "./precision-history.ts"; | |
| 72 | 77 | import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts"; |
| 73 | 78 | import { assertPoseName, parsePoseFile, serializePoseFile, type PoseFile } from "./poses.ts"; |
| 74 | 79 | import { JOINTS, registerName, STS3215, ticksToDegrees } from "./sts3215.ts"; |
| @@ -93,6 +98,8 @@ export interface ServerOptions { | ||
| 93 | 98 | watchdogMs?: number; |
| 94 | 99 | /** How often a stream's client is pinged; one that misses a ping is a lost connection, and the arm parks. */ |
| 95 | 100 | heartbeatMs?: number; |
| 101 | /** The commit the precision history tags its rows with; found from the environment or the checkout when not given. */ | |
| 102 | commit?: string; | |
| 96 | 103 | /** Starting values for the safety settings, before what is stored (src/safety.ts). */ |
| 97 | 104 | safety?: Partial<SafetySettings>; |
| 98 | 105 | /** Speed used to catch up with the first frame of a stream, ticks/s. */ |
| @@ -182,12 +189,15 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 182 | 189 | throw new Error(`safety options: ${(err as Error).message}`); |
| 183 | 190 | } |
| 184 | 191 | const metrics = new Metrics(join(dataDir, "metrics.jsonl")); |
| 192 | const precision = new PrecisionHistory({ file: join(dataDir, "precision.sqlite"), commit: options.commit }); | |
| 193 | /** The stream's precision tracker while one drives; every Goal_Position write starts its bus-to-motion clock. */ | |
| 194 | let tracking: Tracker | null = null; | |
| 185 | 195 | // The machine, raw: every sync write as it goes on the wire, and each joint's last goal, for the Machine panel. |
| 186 | 196 | const machine = new MachineLog(); |
| 187 | 197 | const run = randomUUID(); |
| 188 | 198 | const goals = new Map<number, number>(); |
| 189 | 199 | bus.onSyncWrite = (register, values) => { |
| 190 | if (register === STS3215.Goal_Position) for (const [id, v] of values) goals.set(id, v); | |
| 200 | if (register === STS3215.Goal_Position) for (const [id, v] of values) goals.set(id, v), tracking?.wrote(id, Date.now()); | |
| 191 | 201 | machine.note("sent", registerName(register), { values: perServo(values) }); |
| 192 | 202 | }; |
| 193 | 203 | /** The stream's dead-man hold is in force: no frame came for holdAfterMs, and the arm stays where it was. */ |
| @@ -331,7 +341,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 331 | 341 | machine.note("state", "emergency stop", { by }); |
| 332 | 342 | } |
| 333 | 343 | const was = driver; |
| 334 | if (was === "stream") for (const client of wss.clients) end(client, ESTOP_CLOSE, "emergency stop"); // its close handler holds, never parks | |
| 344 | if (was === "stream") for (const client of wss.clients) stopCause.set(client, "STOP"), end(client, ESTOP_CLOSE, "emergency stop"); // its close handler holds, never parks | |
| 335 | 345 | else if (was === "record" && recording) { |
| 336 | 346 | const { done } = recording; |
| 337 | 347 | recording = null; // nothing is saved: the recording ends where it was cut |
| @@ -742,6 +752,11 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 742 | 752 | return json(res, 200, loadCalibration()); |
| 743 | 753 | case "GET /metrics": |
| 744 | 754 | return json(res, 200, metrics.summary()); |
| 755 | case "GET /precision": { | |
| 756 | const hours = url.searchParams.get("hours") ?? "48"; | |
| 757 | if (!/^\d{1,3}$/.test(hours) || Number(hours) < 1 || Number(hours) > 720) throw new HttpError(400, "hours must be 1-720"); | |
| 758 | return json(res, 200, precision.scorecard(Number(hours))); | |
| 759 | } | |
| 745 | 760 | case "GET /settings": |
| 746 | 761 | return json(res, 200, { ...settings, model: model !== null }); |
| 747 | 762 | case "PUT /settings": { |
| @@ -869,7 +884,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 869 | 884 | // Held first, before anything awaits: a frame already on its way finds the gate shut. |
| 870 | 885 | if (body.hold !== false && gate.hold(actor(body))) metrics.event("hold", { by: actor(body) }); |
| 871 | 886 | const was = driver; |
| 872 | if (was === "stream") for (const client of wss.clients) end(client, 1000, "stopped from the viewer"); // its close handler holds the arm | |
| 887 | if (was === "stream") for (const client of wss.clients) stopCause.set(client, body.hold === false ? "turn-end" : "STOP"), end(client, 1000, "stopped from the viewer"); // its close handler holds the arm | |
| 873 | 888 | else if (was === "record") { |
| 874 | 889 | const summary = await finishRecording(); |
| 875 | 890 | return json(res, 200, { stopped: was, ...summary }); |
| @@ -991,6 +1006,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 991 | 1006 | const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES }); |
| 992 | 1007 | /** Each stream's halt: what it has queued or under way stops at once, not when the close handshake comes back. */ |
| 993 | 1008 | const halts = new Map<WebSocket, () => void>(); |
| 1009 | /** Streams ended by a STOP or by a turn that ends, for the snap-back they cause. */ | |
| 1010 | const stopCause = new WeakMap<WebSocket, Cause>(); | |
| 994 | 1011 | /** Streams this server is ending for breaking the limits: whatever the sender answers, the arm holds rather than parks. */ |
| 995 | 1012 | const overLimit = new WeakSet<WebSocket>(); |
| 996 | 1013 | const end = (ws: WebSocket, code: number, why: string) => { |
| @@ -1027,6 +1044,20 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1027 | 1044 | /** Set the moment the stream ends: whatever is queued or under way gives up, and nothing more reaches the bus. */ |
| 1028 | 1045 | let closed = false; |
| 1029 | 1046 | streamStats = stats; |
| 1047 | const tracker = (tracking = precision.begin()); | |
| 1048 | /** Snap-backs are counted once per episode: a joint held at its limit, a zone refusal, a run of stale frames. */ | |
| 1049 | const capped = new Set<number>(); | |
| 1050 | let refusing = false; | |
| 1051 | let staling = false; | |
| 1052 | /** How far the arm is left from the driver's targets, the farthest joint: the size of a snap-back. */ | |
| 1053 | const shortfall = (positions: ReadonlyMap<number, number>): [number | null, number] => { | |
| 1054 | let worst: [number | null, number] = [null, 0]; | |
| 1055 | for (const [id, t] of last ?? []) { | |
| 1056 | const p = positions.get(id); | |
| 1057 | if (p !== undefined && Math.abs(t - p) > Math.abs(worst[1])) worst = [id, t - p]; | |
| 1058 | } | |
| 1059 | return worst; | |
| 1060 | }; | |
| 1030 | 1061 | const holdAfterMs = options.watchdogMs ?? settings.holdAfterMs; |
| 1031 | 1062 | const period = 1000 / settings.rateHz; |
| 1032 | 1063 | const governor = new Governor(bounds, speedLimits); |
| @@ -1049,6 +1080,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1049 | 1080 | const positions = await bus.syncRead(ids, STS3215.Present_Position); |
| 1050 | 1081 | await bus.syncWrite(STS3215.Goal_Position, ids.filter((id) => positions.has(id)).map((id) => [id, positions.get(id)!] as const)); |
| 1051 | 1082 | governor.reset(positions); |
| 1083 | const [id, short] = shortfall(positions); | |
| 1084 | if (Math.abs(short) > ARRIVE_TICKS) tracker.snapBack("hold-expired", Date.now(), id, short); | |
| 1085 | tracker.release(Date.now()); | |
| 1086 | tracker.forget(); | |
| 1052 | 1087 | last = null; |
| 1053 | 1088 | held = true; |
| 1054 | 1089 | machine.note("state", "dead-man hold", { afterMs: holdAfterMs }); |
| @@ -1058,6 +1093,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1058 | 1093 | if (closed) return; |
| 1059 | 1094 | const positions = await bus.syncRead(ids, STS3215.Present_Position); |
| 1060 | 1095 | present = new Map(positions); |
| 1096 | for (const [id, p] of positions) tracker.sample(id, p, Date.now()); | |
| 1061 | 1097 | const ready = ids.filter((id) => positions.has(id)); |
| 1062 | 1098 | await bus.syncWrite(STS3215.Goal_Position, ready.map((id) => [id, positions.get(id)!] as const)); |
| 1063 | 1099 | await bus.syncWrite(STS3215.Torque_Limit, ready.map((id) => [id, Math.round((id === 6 ? Math.min(streamTorque, settings.gripperTorquePercent) : streamTorque) * 10)] as const)); |
| @@ -1074,6 +1110,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1074 | 1110 | const windows = new Map<number, Array<{ p: number; l: number }>>(); |
| 1075 | 1111 | const observe = async (id: number, p: number, l: number, target: number | undefined): Promise<boolean> => { |
| 1076 | 1112 | present.set(id, p); |
| 1113 | tracker.sample(id, p, Date.now()); | |
| 1077 | 1114 | const w = windows.get(id) ?? []; |
| 1078 | 1115 | w.push({ p, l }); |
| 1079 | 1116 | if (w.length > JAM_WINDOW) w.shift(); |
| @@ -1085,6 +1122,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1085 | 1122 | await bus.syncWrite(STS3215.Goal_Position, [[id, p]]); |
| 1086 | 1123 | governor.pin(id, p); |
| 1087 | 1124 | jams.set(id, { position: p, direction: Math.sign(target - p) }); |
| 1125 | tracker.snapBack("jam", Date.now(), id, target - p); | |
| 1126 | tracker.forget(id); | |
| 1088 | 1127 | last?.set(id, p); |
| 1089 | 1128 | metrics.event("jam", { source: "stream", id, joint: JOINTS[id] ?? null, position: p, target, load: l / 10 }); |
| 1090 | 1129 | machine.note("clamp", "jam", { id, position: p, target, load: l / 10 }); |
| @@ -1142,7 +1181,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1142 | 1181 | for (const [id, value] of frame) { |
| 1143 | 1182 | const target = bound(b, id, value); |
| 1144 | 1183 | if (target === null) continue; |
| 1145 | if (target !== Math.round(value)) { | |
| 1184 | if (target === Math.round(value)) capped.delete(id); | |
| 1185 | else { | |
| 1186 | if (!capped.has(id)) tracker.snapBack("cap", Date.now(), id, Math.round(value) - target); | |
| 1187 | capped.add(id); | |
| 1146 | 1188 | stats.clamped++; |
| 1147 | 1189 | machine.note("clamp", "joint limit", { id, asked: Math.round(value), sent: target, source: "stream" }); |
| 1148 | 1190 | } |
| @@ -1159,6 +1201,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1159 | 1201 | machine.note("clamp", "too far in one frame", { id, asked: target, from: previous, maxStep }); |
| 1160 | 1202 | const n = (drops.get(id) ?? 0) + 1; |
| 1161 | 1203 | drops.set(id, n); |
| 1204 | if (n === 1) tracker.snapBack("maxStep-drop", Date.now(), id, target - previous); | |
| 1162 | 1205 | if (n < RESUME_AFTER_DROPS) continue; // no hand moves that far in one frame |
| 1163 | 1206 | // The leader has stayed far away (after a block or a jam): ease over to it rather than leave the joint stranded. |
| 1164 | 1207 | drops.delete(id); |
| @@ -1183,15 +1226,27 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1183 | 1226 | if (settings.zone === "enforce" && zone.violation.depth > heldDepth + 0.001) { |
| 1184 | 1227 | stats.refused++; |
| 1185 | 1228 | machine.note("clamp", "zone", { what: zone.violation.what, link: zone.violation.link, depthMm: Math.round(zone.violation.depth * 1000), refused: true, source: "stream" }); |
| 1229 | if (!refusing) { | |
| 1230 | // The size: how far the refused frame would have taken the farthest joint from where it stays. | |
| 1231 | let worst: [number | null, number] = [null, 0]; | |
| 1232 | for (const [id, t] of targets) { | |
| 1233 | const gap = t - (last?.get(id) ?? present.get(id) ?? t); | |
| 1234 | if (Math.abs(gap) >= Math.abs(worst[1])) worst = [id, gap]; | |
| 1235 | } | |
| 1236 | tracker.snapBack("zone", Date.now(), worst[0], worst[1]); | |
| 1237 | } | |
| 1238 | refusing = true; | |
| 1186 | 1239 | return; // deeper in than the arm already is: it stays at the last good targets; a frame that backs out is let through |
| 1187 | 1240 | } |
| 1188 | 1241 | } else blocked = null; |
| 1242 | refusing = false; | |
| 1189 | 1243 | heldDepth = zone?.violation?.depth ?? 0; |
| 1190 | 1244 | approach(zone); |
| 1191 | 1245 | if (ease) { |
| 1192 | 1246 | // Catch up slowly with every joint in this frame, the servos' own speed held low, then hand over to the governor. |
| 1193 | 1247 | // A joint that jams on the way is parked and no longer waited for. |
| 1194 | 1248 | easing = true; |
| 1249 | for (const [id, t] of targets) tracker.target(id, t, Date.now()); | |
| 1195 | 1250 | try { |
| 1196 | 1251 | await bus.syncWrite(STS3215.Goal_Velocity, targets.map(([id]) => [id, Math.min(easeSpeed, speedLimits().speed)] as const)); |
| 1197 | 1252 | await bus.syncWrite(STS3215.Goal_Position, targets); |
| @@ -1221,6 +1276,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1221 | 1276 | } |
| 1222 | 1277 | for (const [id, t] of targets) { |
| 1223 | 1278 | governor.aim(id, t); |
| 1279 | tracker.target(id, t, Date.now()); | |
| 1224 | 1280 | last!.set(id, t); |
| 1225 | 1281 | } |
| 1226 | 1282 | }); |
| @@ -1257,9 +1313,14 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1257 | 1313 | if (pace === "drop") return void stats.gated++; |
| 1258 | 1314 | const verdict = admission.admit(String(data)); |
| 1259 | 1315 | if (!verdict.ok) { |
| 1260 | if (verdict.drop !== "malformed") stats.gated++; | |
| 1316 | if (verdict.drop !== "malformed") { | |
| 1317 | stats.gated++; | |
| 1318 | if (!staling) tracker.snapBack("stale-drop", Date.now()); | |
| 1319 | staling = true; | |
| 1320 | } | |
| 1261 | 1321 | return; |
| 1262 | 1322 | } |
| 1323 | staling = false; | |
| 1263 | 1324 | const frame = verdict.joints; |
| 1264 | 1325 | clearTimeout(timer); |
| 1265 | 1326 | timer = setTimeout(() => void hold(), holdAfterMs); |
| @@ -1286,10 +1347,15 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1286 | 1347 | admission.close(); |
| 1287 | 1348 | clearInterval(heartbeat); |
| 1288 | 1349 | const lost = !CLEAN_CLOSE.has(code) && code !== ESTOP_CLOSE && !overLimit.has(ws); |
| 1350 | const cause: Cause | null = stopCause.get(ws) ?? (lost && armed ? "release-park" : null); | |
| 1289 | 1351 | void run(async () => { |
| 1290 | 1352 | try { |
| 1291 | 1353 | if (armed) { |
| 1292 | 1354 | const positions = await bus.syncRead(ids, STS3215.Present_Position); |
| 1355 | const [id, short] = shortfall(positions); | |
| 1356 | if (cause === "release-park") tracker.snapBack(cause, Date.now(), null, null); | |
| 1357 | else if (cause && Math.abs(short) > ARRIVE_TICKS) tracker.snapBack(cause, Date.now(), id, short); | |
| 1358 | if (!held) tracker.release(Date.now()); | |
| 1293 | 1359 | await bus.syncWrite(STS3215.Goal_Position, ids.filter((id) => positions.has(id)).map((id) => [id, positions.get(id)!] as const)); |
| 1294 | 1360 | await bus.syncWrite(STS3215.Torque_Limit, ids.map((id) => [id, id === 6 ? settings.gripperTorquePercent * 10 : 1000] as const)); |
| 1295 | 1361 | } |
| @@ -1298,6 +1364,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1298 | 1364 | held = false; |
| 1299 | 1365 | jams.clear(); |
| 1300 | 1366 | streamStats = null; |
| 1367 | if (tracking === tracker) tracking = null; | |
| 1368 | precision.end(tracker); | |
| 1301 | 1369 | metrics.event("stream", { seconds: Number(((Date.now() - startedAt) / 1000).toFixed(1)), ...stats, ...(lost ? { lost: code } : {}) }); |
| 1302 | 1370 | release(); // whatever the bus did, the arm is free for the next driver |
| 1303 | 1371 | } |
| @@ -1368,6 +1436,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1368 | 1436 | new Promise<void>((resolve) => { |
| 1369 | 1437 | clearInterval(watching); |
| 1370 | 1438 | machine.close(); |
| 1439 | precision.close(); | |
| 1371 | 1440 | bus.onSyncWrite = null; |
| 1372 | 1441 | for (const client of [...wss.clients, ...watchers.clients]) client.terminate(); |
| 1373 | 1442 | wss.close(); |
Software/so101/src/terminal.test.ts +24 −1
| @@ -12,7 +12,7 @@ import { identify, sign } from "./identity.ts"; | ||
| 12 | 12 | import { Lobby } from "./lobby.ts"; |
| 13 | 13 | import { startRelay, type RunningRelay } from "./relay.ts"; |
| 14 | 14 | import { startServer, type RunningServer } from "./server.ts"; |
| 15 | import { Door, emptyRoom, hear, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts"; | |
| 15 | import { cardReader, Door, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts"; | |
| 16 | 16 | import { jointRows } from "./ui/machine.js"; |
| 17 | 17 | import { Turns } from "./turns.ts"; |
| 18 | 18 | |
| @@ -152,6 +152,29 @@ describe("terminal table", () => { | ||
| 152 | 152 | expect(hear(emptyRoom(), { type: "error", error: "only the owner can do that" })).toEqual(["error: only the owner can do that"]); |
| 153 | 153 | }); |
| 154 | 154 | |
| 155 | test("/precision prints the scorecard /admin shows, line by line as text, or the refusal; without a reader it says so", async () => { | |
| 156 | expect(typed(emptyRoom(), "/precision")).toEqual({ precision: true }); | |
| 157 | const row = (trackingP95Deg: number) => ({ trackingP95Deg, arriveP95Ms: 200, snapBacks: 1, releases: 4, latencyP95Ms: 40, worstJoint: "elbow_flex" }); | |
| 158 | const body = { commit: "abc1234", window: { worstJoint: "wrist\x1b[31m_roll" }, sessions: [row(1), row(3)] }; | |
| 159 | const asked: Array<[string, unknown]> = []; | |
| 160 | const fetcher = (async (url: string, init: RequestInit) => (asked.push([url, init.headers]), Response.json(body))) as unknown as typeof fetch; | |
| 161 | const card = await cardReader({ PORT: "8102" }, fetcher)(); | |
| 162 | expect(asked[0]![0]).toBe("http://127.0.0.1:8102/precision"); | |
| 163 | const lines = precisionLines(card.panel!); | |
| 164 | expect(lines[0]).toMatch(/^Tracking error, p95 +3° +▁█$/); | |
| 165 | expect(lines).toContain("worst joint wrist[31m_roll · last 10 minutes, else the last session · trend over 2 sessions · commit abc1234"); | |
| 166 | const refused = await cardReader({ PORT: "8102" }, (async () => Response.json({ error: "no such route" }, { status: 404 })) as unknown as typeof fetch)(); | |
| 167 | expect(refused).toEqual({ status: 404, error: "precision is for the owner and moderators", panel: null }); | |
| 168 | const printed: string[] = []; | |
| 169 | new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, async () => card).input("/precision"); | |
| 170 | new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, async () => refused).input("/precision"); | |
| 171 | new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l)).input("/precision"); | |
| 172 | await Bun.sleep(50); | |
| 173 | expect(printed).toHaveLength(lines.length + 2); | |
| 174 | expect(printed).toContain("error: precision is for the owner and moderators"); | |
| 175 | expect(printed).toContain("error: precision is not available here"); | |
| 176 | }); | |
| 177 | ||
| 155 | 178 | test("/health asks the reader, prints a line per viewer as text, or the refusal; without a reader it says so", async () => { |
| 156 | 179 | expect(typed(emptyRoom(), "/health")).toEqual({ health: true }); |
| 157 | 180 | const row = { viewer: "v1", name: "al\x1b[31mice", rttP50: 40, rttP95: 90, sentPerS: 30, droppedPerS: 2, camFps: 14.5, frameAgeMs: 120, stalls: 1, reconnects: 2 }; |
Software/so101/src/terminal.ts +47 −4
| @@ -31,6 +31,7 @@ | ||
| 31 | 31 | * /table here admin: put the table under the arm's lowest link now (POST /settings/table-here) |
| 32 | 32 | * /table <mm> admin: set the table offset, -100..100 mm (PUT /settings tableOffsetMm) |
| 33 | 33 | * /health owner or moderator: each open page's link as it last reported it (GET /admin/health, the page's Admin -> Health) |
| 34 | * /precision owner or moderator: the precision scorecard /admin shows (GET /precision, src/precision-panel.ts) | |
| 34 | 35 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, |
| 35 | 36 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it |
| 36 | 37 | * /who /help /quit |
| @@ -40,6 +41,7 @@ | ||
| 40 | 41 | import WebSocket from "ws"; |
| 41 | 42 | import { UNPRINTABLE } from "./chat.ts"; |
| 42 | 43 | import { ID, NAME, sign } from "./identity.ts"; |
| 44 | import { headlineValue, readPrecision, sparkline, type PrecisionPanel } from "./precision-panel.ts"; | |
| 43 | 45 | import { presenceText } from "./ui/lobby-panel.js"; |
| 44 | 46 | import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js"; |
| 45 | 47 | |
| @@ -112,6 +114,35 @@ export function reader(env: Env, fetcher: typeof fetch = fetch): Read { | ||
| 112 | 114 | }; |
| 113 | 115 | } |
| 114 | 116 | |
| 117 | /** What GET /precision answered, read as the admin panel reads it; or why not (a guest is told there is no such route). */ | |
| 118 | export type Card = { status: number; error: string | null; panel: PrecisionPanel | null }; | |
| 119 | export type ReadCard = () => Promise<Card>; | |
| 120 | ||
| 121 | /** GET the precision scorecard as /admin shows it, signed afresh; the server decides who may. */ | |
| 122 | export function cardReader(env: Env, fetcher: typeof fetch = fetch): ReadCard { | |
| 123 | return async () => { | |
| 124 | try { | |
| 125 | const r = await fetcher(`${appUrl(env)}/precision`, { headers: terminalHeaders(env), signal: AbortSignal.timeout(5000) }); | |
| 126 | const body = (await r.json().catch(() => null)) as unknown; | |
| 127 | const panel = r.ok ? readPrecision(body) : null; | |
| 128 | if (panel) return { status: r.status, error: null, panel }; | |
| 129 | return { status: r.status, error: r.status === 404 ? "precision is for the owner and moderators" : plain((body as { error?: unknown } | null)?.error ?? `status ${r.status}`), panel: null }; | |
| 130 | } catch (err) { | |
| 131 | return { status: 0, error: plain((err as Error).message), panel: null }; | |
| 132 | } | |
| 133 | }; | |
| 134 | } | |
| 135 | ||
| 136 | /** The panel's lines: each headline number with its sparkline, then the worst joint and the commit. */ | |
| 137 | export function precisionLines(p: PrecisionPanel): string[] { | |
| 138 | if (!p.sessions && p.headline.every((h) => h.value === null)) return [plain(`nothing measured yet: drive the arm and the numbers appear · commit ${p.commit}`)]; | |
| 139 | const width = Math.max(...p.headline.map((h) => h.label.length)); | |
| 140 | return [ | |
| 141 | ...p.headline.map((h) => plain(`${h.label.padEnd(width)} ${headlineValue(h)} ${sparkline(h.trend)}`).trimEnd()), | |
| 142 | plain(`worst joint ${p.worstJoint ?? "—"} · last 10 minutes, else the last session · trend over ${p.sessions} session${p.sessions === 1 ? "" : "s"} · commit ${p.commit}`), | |
| 143 | ]; | |
| 144 | } | |
| 145 | ||
| 115 | 146 | /** One line per viewer, the page's columns in order; text from the room is made safe. */ |
| 116 | 147 | export function healthLines(rows: unknown[]): string[] { |
| 117 | 148 | if (!rows.length) return ["no viewer has reported yet"]; |
| @@ -176,7 +207,7 @@ const said = (room: Room, m: unknown): string => { | ||
| 176 | 207 | return from ? `${tag}${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`; |
| 177 | 208 | }; |
| 178 | 209 | |
| 179 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|<mm> (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /health (owner, moderator) · /machine [off] · /who · /quit"; | |
| 210 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|<mm> (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /health /precision (owner, moderator) · /machine [off] · /who · /quit"; | |
| 180 | 211 | |
| 181 | 212 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 182 | 213 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -312,7 +343,7 @@ function target(room: Room, word: string): string | null { | ||
| 312 | 343 | return ID.test(word) ? word : null; |
| 313 | 344 | } |
| 314 | 345 | |
| 315 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { quit: true } | null; | |
| 346 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { quit: true } | null; | |
| 316 | 347 | |
| 317 | 348 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 318 | 349 | export function typed(room: Room, input: string): Typed { |
| @@ -379,6 +410,8 @@ export function typed(room: Room, input: string): Typed { | ||
| 379 | 410 | } |
| 380 | 411 | case "health": |
| 381 | 412 | return { health: true }; |
| 413 | case "precision": | |
| 414 | return { precision: true }; | |
| 382 | 415 | case "machine": |
| 383 | 416 | if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" }; |
| 384 | 417 | return { machine: arg.toLowerCase() !== "off" }; |
| @@ -405,10 +438,12 @@ export class Door { | ||
| 405 | 438 | private readonly print: (line: string) => void; |
| 406 | 439 | private readonly post: Post | null; |
| 407 | 440 | private readonly read: Read | null; |
| 441 | private readonly readCard: ReadCard | null; | |
| 408 | 442 | |
| 409 | /** `post` reaches the app's /stop and /resume, `read` its /admin/health; without them, the door says it cannot. */ | |
| 410 | constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null) { | |
| 443 | /** `post` reaches the app's /stop and /resume, `read` its /admin/health, `readCard` its /precision; without them, the door says it cannot. */ | |
| 444 | constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null, readCard: ReadCard | null = null) { | |
| 411 | 445 | this.read = read; |
| 446 | this.readCard = readCard; | |
| 412 | 447 | this.url = url; |
| 413 | 448 | this.headers = headers; |
| 414 | 449 | this.print = print; |
| @@ -450,6 +485,7 @@ export class Door { | ||
| 450 | 485 | else if ("post" in t) void this.ask(t.post); |
| 451 | 486 | else if ("table" in t) void this.table(t.table); |
| 452 | 487 | else if ("health" in t) void this.health(); |
| 488 | else if ("precision" in t) void this.precision(); | |
| 453 | 489 | else if ("machine" in t) this.watchMachine(t.machine); |
| 454 | 490 | else this.send(t.send); |
| 455 | 491 | return true; |
| @@ -471,6 +507,13 @@ export class Door { | ||
| 471 | 507 | for (const line of r.error ? [`error: ${r.error}`] : healthLines(r.rows)) this.print(line); |
| 472 | 508 | } |
| 473 | 509 | |
| 510 | /** The server decides who may; a refusal is printed, else the scorecard. */ | |
| 511 | private async precision(): Promise<void> { | |
| 512 | if (!this.readCard) return this.print("error: precision is not available here"); | |
| 513 | const r = await this.readCard(); | |
| 514 | for (const line of r.error || !r.panel ? [`error: ${r.error ?? "no scorecard"}`] : precisionLines(r.panel)) this.print(line); | |
| 515 | } | |
| 516 | ||
| 474 | 517 | /** The server decides who may; a refusal is printed, success says the offset the server now holds. */ |
| 475 | 518 | private async table(what: "here" | number): Promise<void> { |
| 476 | 519 | if (!this.post) return this.print("error: the table is not available here"); |
Software/so101/src/tty.ts +2 −2
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import { createInterface, type Interface } from "node:readline"; |
| 7 | import { Door, HELP, liveUrl, poster, reader, terminalHeaders } from "./terminal.ts"; | |
| 7 | import { cardReader, Door, HELP, liveUrl, poster, reader, terminalHeaders } from "./terminal.ts"; | |
| 8 | 8 | |
| 9 | 9 | const env = process.env; |
| 10 | 10 | const where = env.FORGE_APP_ENV === "preview" ? `preview of #${env.FORGE_APP_PULL ?? "?"}` : (env.FORGE_APP_ENV ?? "local"); |
| @@ -17,7 +17,7 @@ const print = (line: string) => { | ||
| 17 | 17 | rl?.prompt(true); |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env)); | |
| 20 | const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env), cardReader(env)); | |
| 21 | 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); |
| 22 | 22 | try { |
| 23 | 23 | await door.open(() => { |
new above
offline