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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

The relay's minute sample records pi:temp and pi:undervolt from the arm's GET /health/pi into facts (no chart) #551

Merged opened this

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

Merged

smith/arm:smith/545-the-relay-s-minute-sample-records-pi-tem → main 1 commit fork 1 thread · 1 unresolved

  • Merged. smith/545-the-relay-s-minute-sample-records-pi-tem was merged into main as 82abcda.

Review

Sign in to review this change.
3 files changed +68 −8
Software/so101/src/facts.test.ts +35 −3
@@ -102,16 +102,21 @@ test("a browser's visits are one row an hour, and all visits are capped", () =>
102102 expect(facts.events()).toHaveLength(1 + MAX_VISITS_PER_HOUR);
103103 });
104104
105 async function relayWith(facts: Facts, card = { session: { releases: 2, snapBacks: { byCause: { STOP: 1 } } } }) {
105 async function relayWith(facts: Facts, card = { session: { releases: 2, snapBacks: { byCause: { STOP: 1 } } } }, extra: { pi?: unknown; sampleEveryMs?: number; unreachable?: boolean } = {}) {
106106 const { Lobby } = await import("./lobby.ts");
107107 const { startRelay } = await import("./relay.ts");
108108 const { sign } = await import("./identity.ts");
109109 const key = "k".repeat(64);
110110 const identity = `id-ann|ann|admin|${Date.now() + 600_000}`;
111111 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, key) };
112 const sim = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (req) => (new URL(req.url).pathname === "/status" ? Response.json({ joints: [], held: null }) : Response.json(card)) });
112 const sim = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (req) => {
113 const path = new URL(req.url).pathname;
114 if (path === "/status") return Response.json({ joints: [], held: null });
115 if (path === "/health/pi") return extra.pi === undefined ? new Response("no", { status: 404 }) : Response.json(extra.pi);
116 return Response.json(card);
117 } });
113118 const lobby = new Lobby({ identityKey: key });
114 const relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${sim.port}`, lobby, facts });
119 const relay = await startRelay({ port: 0, simulation: extra.unreachable ? "http://127.0.0.1:1" : `http://127.0.0.1:${sim.port}`, lobby, facts, ...(extra.sampleEveryMs ? { sampleEveryMs: extra.sampleEveryMs } : {}) });
115120 const stop = async () => {
116121 await relay.close();
117122 lobby.close();
@@ -161,3 +166,30 @@ test("the relay writes app start and a turn's row with its card", async () => {
161166 await stop();
162167 }
163168 });
169
170 test("the minute sample stores the arm's pi temperature and under-voltage flag", async () => {
171 const facts = new Facts();
172 const { stop } = await relayWith(facts, undefined, { pi: { tempC: 61.5, underVoltage: true }, sampleEveryMs: 30 });
173 try {
174 for (let i = 0; i < 100 && facts.samples().length === 0; i++) await Bun.sleep(20);
175 expect(facts.samples()[0]).toMatchObject({ piTemp: 61.5, piUndervolt: true });
176 } finally {
177 await stop();
178 }
179 });
180
181 test("an unreachable arm or null answers store no pi values, and the other samples still land", async () => {
182 for (const extra of [{ unreachable: true }, { pi: { tempC: null, underVoltage: null } }, {}]) {
183 const facts = new Facts();
184 const { stop } = await relayWith(facts, undefined, { ...extra, sampleEveryMs: 30 });
185 try {
186 for (let i = 0; i < 150 && facts.samples().length === 0; i++) await Bun.sleep(20);
187 const [sample] = facts.samples();
188 expect(sample).toMatchObject({ watchers: 0, drivers: 0, queue: 0 });
189 expect(sample).not.toHaveProperty("piTemp");
190 expect(sample).not.toHaveProperty("piUndervolt");
191 } finally {
192 await stop();
193 }
194 }
195 });
Software/so101/src/facts.ts +20 −2
@@ -54,6 +54,18 @@ export interface Sample {
5454 linkLive: boolean;
5555 /** Decoded frames a second by camera id. */
5656 fps: Record<string, number>;
57 /** The Pi's temperature (°C) and under-voltage flag from the arm's GET /health/pi; absent when the arm did not say. */
58 piTemp?: number;
59 piUndervolt?: boolean;
60 }
61
62 /** The two numbers kept from the arm's GET /health/pi; each absent unless it is a real value. */
63 export function parsePiHealth(body: unknown): Pick<Sample, "piTemp" | "piUndervolt"> {
64 const root = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
65 const out: Pick<Sample, "piTemp" | "piUndervolt"> = {};
66 if (typeof root.tempC === "number" && Number.isFinite(root.tempC)) out.piTemp = root.tempC;
67 if (typeof root.underVoltage === "boolean") out.piUndervolt = root.underVoltage;
68 return out;
5769 }
5870
5971 export interface TurnRow {
@@ -90,6 +102,9 @@ export class Facts {
90102 this.#db.run("CREATE TABLE IF NOT EXISTS events (at INTEGER NOT NULL, commit_id TEXT NOT NULL, kind TEXT NOT NULL, who TEXT)");
91103 this.#db.run(`CREATE TABLE IF NOT EXISTS samples (at INTEGER NOT NULL, commit_id TEXT NOT NULL, watchers INTEGER NOT NULL, drivers INTEGER NOT NULL, queue INTEGER NOT NULL,
92104 link_live INTEGER NOT NULL, fps TEXT NOT NULL)`);
105 const have = (this.#db.query("PRAGMA table_info(samples)").all() as Array<{ name: string }>).map((c) => c.name);
106 if (!have.includes("pi_temp")) this.#db.run("ALTER TABLE samples ADD COLUMN pi_temp REAL");
107 if (!have.includes("pi_undervolt")) this.#db.run("ALTER TABLE samples ADD COLUMN pi_undervolt INTEGER");
93108 for (const t of ["turns", "events", "samples"]) this.#db.run(`CREATE INDEX IF NOT EXISTS ${t}_at ON ${t} (at)`);
94109 this.#attempt(() => this.prune());
95110 }
@@ -129,7 +144,8 @@ export class Facts {
129144
130145 sample(s: Sample): void {
131146 this.#attempt(() => {
132 this.#db.query("INSERT INTO samples (at, commit_id, watchers, drivers, queue, link_live, fps) VALUES (?, ?, ?, ?, ?, ?, ?)").run(this.#now(), this.commit, s.watchers, s.drivers, s.queue, s.linkLive ? 1 : 0, JSON.stringify(s.fps));
147 this.#db.query("INSERT INTO samples (at, commit_id, watchers, drivers, queue, link_live, fps, pi_temp, pi_undervolt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(
148 this.#now(), this.commit, s.watchers, s.drivers, s.queue, s.linkLive ? 1 : 0, JSON.stringify(s.fps), s.piTemp ?? null, s.piUndervolt === undefined ? null : s.piUndervolt ? 1 : 0);
133149 if (this.#now() - this.#pruned > 3_600_000) this.prune();
134150 });
135151 }
@@ -196,7 +212,7 @@ export class Facts {
196212 return (this.#db.query("SELECT at, commit_id, kind, who FROM events ORDER BY at, rowid").all() as Array<{ at: number; commit_id: string; kind: EventKind; who: string | null }>).map((r) => ({ at: r.at, commit: r.commit_id, kind: r.kind, who: r.who }));
197213 }
198214
199 samples(): Array<{ at: number; commit: string; watchers: number; drivers: number; queue: number; linkLive: boolean; fps: Record<string, number> }> {
215 samples(): Array<{ at: number; commit: string; watchers: number; drivers: number; queue: number; linkLive: boolean; fps: Record<string, number>; piTemp?: number; piUndervolt?: boolean }> {
200216 return (this.#db.query("SELECT * FROM samples ORDER BY at, rowid").all() as Array<Record<string, unknown>>).map((r) => ({
201217 at: r.at as number,
202218 commit: r.commit_id as string,
@@ -205,6 +221,8 @@ export class Facts {
205221 queue: r.queue as number,
206222 linkLive: r.link_live === 1,
207223 fps: JSON.parse(r.fps as string) as Record<string, number>,
224 ...(r.pi_temp === null ? {} : { piTemp: r.pi_temp as number }),
225 ...(r.pi_undervolt === null ? {} : { piUndervolt: r.pi_undervolt === 1 }),
208226 }));
209227 }
210228
Software/so101/src/relay.ts +13 −3
@@ -64,7 +64,7 @@ import { LiveMetrics } from "./live-metrics.ts";
6464 import { wallMs } from "./clock.ts";
6565 import { ArmLink, type LinkTimings } from "./arm-link.ts";
6666 import { ArmEdges } from "./arm-edges.ts";
67 import { parseCard, type Facts } from "./facts.ts";
67 import { parseCard, parsePiHealth, type Facts } from "./facts.ts";
6868 import { MachineFeed } from "./machine-feed.ts";
6969 import { refusalBatch } from "./refusals.ts";
7070 import { BROWSER_HOP, PAGE_HOP, parseSnapBack } from "./precision.ts";
@@ -1137,11 +1137,21 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
11371137 }, 1000).unref?.();
11381138 }) : undefined;
11391139 const chatFacts = facts ? lobby?.onChat((who) => facts.event("chat", who.id)) : undefined;
1140 const sampleTimer = facts ? setInterval(() => {
1140 /** The arm's Pi temperature and under-voltage flag; nothing when it is unreachable, slow or answers nulls. */
1141 const piHealth = async () => {
1142 try {
1143 const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/health/pi`, { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 1000)) });
1144 return answer.ok ? parsePiHealth(await answer.json()) : {};
1145 } catch {
1146 return {};
1147 }
1148 };
1149 const sampleTimer = facts ? setInterval(async () => {

The sample time is stamped inside facts.sample after this await, so a slow arm shifts it by up to 1 s. Harmless now; capture the time before the fetch if charts ever need exact minutes.

1150 const pi = await piHealth();
11411151 const snap = lobby?.turns.snapshot();
11421152 const fps: Record<string, number> = {};
11431153 for (const c of videoCards()) if (c.fpsP50 !== null) fps[String(c.camera)] = c.fpsP50;
1144 facts.sample({ watchers: lobby?.watching ?? 0, drivers: snap?.driver ? 1 : 0, queue: snap?.queue.length ?? 0, linkLive: mode() === "live", fps });
1154 facts.sample({ watchers: lobby?.watching ?? 0, drivers: snap?.driver ? 1 : 0, queue: snap?.queue.length ?? 0, linkLive: mode() === "live", fps, ...pi });
11451155 }, options.sampleEveryMs ?? 60_000) : undefined;
11461156 sampleTimer?.unref?.();
11471157 facts?.event("app start");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs