Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
/admin 'Try this P' runs the tuning experiment on the arm while nobody drives and keeps every result in the precision history #497
smith/arm:smith/486-admin-try-this-p-runs-the-tuning-experim → main 1 commit fork
14 files
changed +473
−14
Software/so101/src/admin-page.ts +1 −1
| @@ -146,7 +146,7 @@ export const adminCsp = (canEdit: boolean): string => | ||
| 146 | 146 | `default-src 'none'; style-src 'sha256-${sha(STYLE)}'; script-src 'sha256-${sha(scriptFor(canEdit))}'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`; |
| 147 | 147 | |
| 148 | 148 | /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */ |
| 149 | export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control.", restored: "Line restored.", lifted: "Lifted.", reportRemoved: "Line removed; report closed.", reportMuted: "Author muted; report closed.", reportDismissed: "Report dismissed." } as const; | |
| 149 | export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control.", restored: "Line restored.", lifted: "Lifted.", reportRemoved: "Line removed; report closed.", reportMuted: "Author muted; report closed.", reportDismissed: "Report dismissed.", tuning: "The P experiment is running on the arm: reload to follow it." } as const; | |
| 150 | 150 | export type Done = keyof typeof DONE; |
| 151 | 151 | |
| 152 | 152 | export interface Target { id: string; name: string } |
Software/so101/src/admin-relay.test.ts +14
| @@ -168,3 +168,17 @@ test("writing servo params and the factory restore are the owner's; anyone else | ||
| 168 | 168 | expect((await fetch(`${base}${path}`, { method, body: "{}", headers: as("trevato", "admin") })).status).not.toBe(404); |
| 169 | 169 | } |
| 170 | 170 | }); |
| 171 | ||
| 172 | test("the P experiment is the owner's; anyone else gets 404, on the route and on the admin form", async () => { | |
| 173 | const base = await boot(); | |
| 174 | for (const [method, path] of [["POST", "/tuning/p"], ["GET", "/tuning"]] as const) { | |
| 175 | expect((await fetch(`${base}${path}`, { method, body: method === "POST" ? "{}" : undefined })).status).toBe(404); | |
| 176 | expect((await fetch(`${base}${path}`, { method, body: method === "POST" ? "{}" : undefined, headers: as("bob", "user") })).status).toBe(404); | |
| 177 | expect((await fetch(`${base}${path}`, { method, body: method === "POST" ? "{}" : undefined, headers: as("trevato", "admin") })).status).not.toBe(404); | |
| 178 | } | |
| 179 | expect((await fetch(`${base}/admin`, form(as("bob", "user"), { action: "tune-p", joint: "1", p: "24" }))).status).toBe(404); | |
| 180 | // the owner's form reaches the arm, which nothing answers here: a sentence, not a redirect | |
| 181 | const owner = await fetch(`${base}/admin`, form(as("trevato", "admin"), { action: "tune-p", joint: "1", p: "24" })); | |
| 182 | expect(owner.status).toBe(400); | |
| 183 | expect(await owner.text()).toContain("did not answer"); | |
| 184 | }); |
Software/so101/src/admin-routes.ts +12 −1
| @@ -18,6 +18,9 @@ export type AskVideo = () => readonly VideoCard[]; | ||
| 18 | 18 | /** Asks the arm for its servos' control registers; only called for the owner. */ |
| 19 | 19 | export type AskServos = () => Promise<ServoPanel | null>; |
| 20 | 20 | |
| 21 | /** Asks the arm server to run the P experiment; answers why not as a sentence, or null when it began. */ | |
| 22 | export type TuneP = (joint: number, p: number) => Promise<string | null>; | |
| 23 | ||
| 21 | 24 | /** What a POST needs once the caller is known to be allowed on the page. */ |
| 22 | 25 | export interface AdminSession { |
| 23 | 26 | who: Person; |
| @@ -78,7 +81,7 @@ const REPORT_ACTIONS = new Set(["report-remove", "report-mute", "report-dismiss" | ||
| 78 | 81 | type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>; |
| 79 | 82 | |
| 80 | 83 | /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */ |
| 81 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision, askServos?: AskServos, askVideo?: AskVideo, versions?: () => Versions): Promise<void> { | |
| 84 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision, askServos?: AskServos, askVideo?: AskVideo, versions?: () => Versions, tune?: TuneP): Promise<void> { | |
| 82 | 85 | const session = await serveAdminPage(lobby, req, res, url, askPrecision, askServos, askVideo, versions); |
| 83 | 86 | if (!session) return; |
| 84 | 87 | const { who, canEdit, show } = session; |
| @@ -143,6 +146,14 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve | ||
| 143 | 146 | done = act === "report-remove" ? "reportRemoved" : act === "report-mute" ? "reportMuted" : "reportDismissed"; |
| 144 | 147 | break; |
| 145 | 148 | } |
| 149 | case "tune-p": { | |
| 150 | const [joint, p] = [form.get("joint") ?? "", form.get("p") ?? ""]; | |
| 151 | if (!/^\d{1,3}$/.test(joint) || !/^\d{1,3}$/.test(p)) throw new AdminError("give a joint and a whole number for P"); | |
| 152 | const refused = tune ? await tune(Number(joint), Number(p)) : "the arm is not reachable from here"; | |
| 153 | if (refused) throw new AdminError(refused); | |
| 154 | done = "tuning"; | |
| 155 | break; | |
| 156 | } | |
| 146 | 157 | default: |
| 147 | 158 | throw new AdminError("no such action"); |
| 148 | 159 | } |
Software/so101/src/precision-history.ts +24
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | import { Database } from "bun:sqlite"; |
| 8 | 8 | import { existsSync, readFileSync } from "node:fs"; |
| 9 | 9 | import { join } from "node:path"; |
| 10 | import type { PExperiment } from "./tuning-run.ts"; | |
| 10 | 11 | import { emptyRecords, summarize, trim, Tracker, WINDOW_MS, type Card, type Cause } from "./precision.ts"; |
| 11 | 12 | |
| 12 | 13 | /** The deployed commit: the forge's or CI's variable when set, else the checkout's HEAD, else "unknown". Never a shell. */ |
| @@ -47,8 +48,15 @@ export interface Row { | ||
| 47 | 48 | worstJoint: string | null; |
| 48 | 49 | } |
| 49 | 50 | |
| 51 | /** One P experiment as kept: the run's own numbers, tagged with the commit that ran it. */ | |
| 52 | export interface TuningRow extends PExperiment { | |
| 53 | commit: string; | |
| 54 | } | |
| 55 | ||
| 50 | 56 | export interface Scorecard { |
| 51 | 57 | commit: string; |
| 58 | /** The P experiments, newest first. */ | |
| 59 | tunings: TuningRow[]; | |
| 52 | 60 | /** The session being driven now, or null. */ |
| 53 | 61 | session: Card | null; |
| 54 | 62 | /** The last ten minutes, sessions pooled. */ |
| @@ -67,6 +75,8 @@ export class PrecisionHistory { | ||
| 67 | 75 | readonly : () => number; |
| 68 | 76 | readonly = emptyRecords(); |
| 69 | 77 | : Tracker | null = null; |
| 78 | /** The card of the drive session that ended last: how a sweep reads its own numbers. */ | |
| 79 | last: Card | null = null; | |
| 70 | 80 | |
| 71 | 81 | constructor(options: { file?: string; commit?: string; now?: () => number } = {}) { |
| 72 | 82 | this.commit = options.commit ?? deployedCommit(); |
| @@ -77,6 +87,7 @@ export class PrecisionHistory { | ||
| 77 | 87 | snap_backs INTEGER NOT NULL, releases INTEGER NOT NULL, latency_p95_ms REAL, worst_joint TEXT`; |
| 78 | 88 | this..run(`CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY, at TEXT NOT NULL, ${columns}, card TEXT NOT NULL)`); |
| 79 | 89 | // An hour's roll-up keeps the worst of its sessions' p95s: one bad session in the hour is what the trend must show. |
| 90 | this..run("CREATE TABLE IF NOT EXISTS tunings (id INTEGER PRIMARY KEY, commit_id TEXT NOT NULL, result TEXT NOT NULL)"); | |
| 80 | 91 | this..run(`CREATE TABLE IF NOT EXISTS hours (at TEXT NOT NULL, ${columns}, PRIMARY KEY (at, commit_id))`); |
| 81 | 92 | } |
| 82 | 93 | |
| @@ -99,6 +110,7 @@ export class PrecisionHistory { | ||
| 99 | 110 | tracker.finish(at); |
| 100 | 111 | if (this. === tracker) this. = null; |
| 101 | 112 | const card = summarize(tracker.records); |
| 113 | this.last = card; | |
| 102 | 114 | const measured = card.joints.some((j) => j.errorTicks.n > 0) || card.snapBacks.total > 0; |
| 103 | 115 | if (!measured) return card; |
| 104 | 116 | const seconds = Number(((at - tracker.startedAt) / 1000).toFixed(1)); |
| @@ -132,12 +144,24 @@ export class PrecisionHistory { | ||
| 132 | 144 | return rows.reverse().map(fromStored); |
| 133 | 145 | } |
| 134 | 146 | |
| 147 | /** Keep one finished P experiment. */ | |
| 148 | addTuning(result: PExperiment): void { | |
| 149 | this..query("INSERT INTO tunings (commit_id, result) VALUES (?, ?)").run(this.commit, JSON.stringify(result)); | |
| 150 | } | |
| 151 | ||
| 152 | /** The kept experiments, newest first. */ | |
| 153 | tunings(limit = 20): TuningRow[] { | |
| 154 | const rows = this..query("SELECT commit_id, result FROM tunings ORDER BY id DESC LIMIT ?").all(limit) as Array<{ commit_id: string; result: string }>; | |
| 155 | return rows.map((r) => ({ ...(JSON.parse(r.result) as PExperiment), commit: r.commit_id })); | |
| 156 | } | |
| 157 | ||
| 135 | 158 | /** `hours`: how many hourly rows, newest kept (two weeks of them compare one week with the last). */ |
| 136 | 159 | scorecard(hours = 48): Scorecard { |
| 137 | 160 | const now = this.(); |
| 138 | 161 | trim(this., now - WINDOW_MS); |
| 139 | 162 | return { |
| 140 | 163 | commit: this.commit, |
| 164 | tunings: this.tunings(), | |
| 141 | 165 | session: this. ? summarize(this..records) : null, |
| 142 | 166 | window: summarize(this., now - WINDOW_MS), |
| 143 | 167 | sessions: this.rows("sessions"), |
Software/so101/src/precision-panel.test.ts +11
| @@ -109,3 +109,14 @@ describe("the Precision panel on /admin", () => { | ||
| 109 | 109 | expect((await fetch(`${base}/precision`, { headers: owner })).status).toBe(502); |
| 110 | 110 | }); |
| 111 | 111 | }); |
| 112 | ||
| 113 | test("the P experiments are listed newest first as joint, P from→to, before→after and kept or put back", () => { | |
| 114 | const run = (to: number, kept: boolean) => ({ joint: 2, from: 16, to, kept, before: { p95Error: 10, overshoot: 5 }, after: { p95Error: 8, overshoot: 4 }, commit: "abc1234", at: "2026-10-21T10:00:00.000Z" }); | |
| 115 | const panel = readPrecision({ commit: "abc", sessions: [], tunings: [run(24, true), run(16, false), { joint: "x" }] })!; | |
| 116 | expect(panel.tunings).toHaveLength(2); | |
| 117 | const html = precisionSection(panel, (s) => s.replace(/</g, "<")); | |
| 118 | expect(html).toContain("shoulder_lift (2) · P 16→24 · error 10→8, overshoot 5→4 · kept"); | |
| 119 | expect(html).toContain("P 16→16"); | |
| 120 | expect(html).toContain("put back"); | |
| 121 | expect(html.indexOf("→24")).toBeLessThan(html.indexOf("put back")); | |
| 122 | }); |
Software/so101/src/precision-panel.ts +7 −2
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | * the stored sessions, oldest first, and the worst joint named. Plain text and characters; no script. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { readTuningResult, tuningList, type TuningResult } from "./tuning-panel.ts"; | |
| 8 | ||
| 7 | 9 | const SPARK = "▁▂▃▄▅▆▇█"; |
| 8 | 10 | const TREND = 24; |
| 9 | 11 | |
| @@ -20,6 +22,8 @@ export interface PrecisionPanel { | ||
| 20 | 22 | worstJoint: string | null; |
| 21 | 23 | sessions: number; |
| 22 | 24 | headline: Headline[]; |
| 25 | /** The P experiments kept, newest first. */ | |
| 26 | tunings: TuningResult[]; | |
| 23 | 27 | } |
| 24 | 28 | |
| 25 | 29 | const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); |
| @@ -43,6 +47,7 @@ export function readPrecision(body: unknown): PrecisionPanel | null { | ||
| 43 | 47 | commit: text(card.commit) ?? "unknown", |
| 44 | 48 | worstJoint: text(window.worstJoint) ?? text(last.worstJoint), |
| 45 | 49 | sessions: rows.length, |
| 50 | tunings: (Array.isArray(card.tunings) ? card.tunings : []).slice(0, 20).map(readTuningResult).filter((t): t is TuningResult => t !== null), | |
| 46 | 51 | headline: [ |
| 47 | 52 | { label: "Tracking error, p95", unit: "°", value: pick(window.trackingP95Deg, last.trackingP95Deg), trend: rows.map((r) => num(r.trackingP95Deg)) }, |
| 48 | 53 | { label: "Time to arrive, p95", unit: "ms", value: pick(window.arriveP95Ms, last.arriveP95Ms), trend: rows.map((r) => num(r.arriveP95Ms)) }, |
| @@ -67,7 +72,7 @@ export function sparkline(values: ReadonlyArray<number | null>): string { | ||
| 67 | 72 | export function precisionSection(p: PrecisionPanel | null | undefined, esc: (s: string) => string): string { |
| 68 | 73 | const head = `<section aria-labelledby="precision"><h2 id="precision">Precision</h2>`; |
| 69 | 74 | 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>`; | |
| 75 | if (!p.sessions && !p.tunings.length && 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 | 76 | const items = p.headline |
| 72 | 77 | .map((h) => { |
| 73 | 78 | const value = headlineValue(h); |
| @@ -75,5 +80,5 @@ export function precisionSection(p: PrecisionPanel | null | undefined, esc: (s: | ||
| 75 | 80 | return `<li><span>${esc(h.label)}</span><span><b>${esc(value)}</b>${spark ? ` <span aria-hidden="true">${spark}</span>` : ""}</span></li>`; |
| 76 | 81 | }) |
| 77 | 82 | .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>`; | |
| 83 | 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>${tuningList(p.tunings, esc)}</section>`; | |
| 79 | 84 | } |
Software/so101/src/relay.ts +27 −5
| @@ -74,8 +74,9 @@ import { CameraSocket } from "./camera-socket.ts"; | ||
| 74 | 74 | import { OFFLINE_FRAME } from "./offline-frame.ts"; |
| 75 | 75 | import { ServoBaseline } from "./servo-baseline.ts"; |
| 76 | 76 | import type { PiSync } from "./pi-deploy.ts"; |
| 77 | import { handleAdmin, handleLift } from "./admin-routes.ts"; | |
| 77 | import { handleAdmin, handleLift, type TuneP } from "./admin-routes.ts"; | |
| 78 | 78 | import { readPrecision } from "./precision-panel.ts"; |
| 79 | import { readTuning } from "./tuning-panel.ts"; | |
| 79 | 80 | import { readServos } from "./servo-panel.ts"; |
| 80 | 81 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 81 | 82 | import { CameraError, CameraHub } from "./cameras.ts"; |
| @@ -175,9 +176,9 @@ const PAGE = /^\/(?:index\.html)?$/; | ||
| 175 | 176 | const STATIC = /^\/(?:index\.html)?$|^\/(?:model|vendor|ui)\//; |
| 176 | 177 | const LEADER = "/leader/calibration"; |
| 177 | 178 | /** Admins only: clearing an emergency stop and changing the settings (the safety limits among them). */ |
| 178 | const ADMIN_ONLY = new Set(["POST /estop/clear", "PUT /settings", "POST /settings/table-here", "POST /settings/table-touch", "POST /settings/joint-zero", "PUT /servo-params", "POST /servo-params/factory"]); | |
| 179 | const ADMIN_ONLY = new Set(["POST /estop/clear", "PUT /settings", "POST /settings/table-here", "POST /settings/table-touch", "POST /settings/joint-zero", "PUT /servo-params", "POST /servo-params/factory", "POST /tuning/p"]); | |
| 179 | 180 | /** Routes only the owner may reach; anyone else is told there is no such page. */ |
| 180 | const OWNER_READS = new Set(["GET /servo-params", "PUT /servo-params", "POST /servo-params/factory"]); | |
| 181 | const OWNER_READS = new Set(["GET /servo-params", "PUT /servo-params", "POST /servo-params/factory", "GET /tuning", "POST /tuning/p"]); | |
| 181 | 182 | /** The driver's, and any admin's at any time. */ |
| 182 | 183 | const ADMIN_TOO = new Set(["POST /stop", "POST /resume", "POST /estop"]); |
| 183 | 184 | /** What still goes to the arm server while the link is reconnecting: stopping it. */ |
| @@ -482,11 +483,32 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 482 | 483 | } |
| 483 | 484 | return json(res, 200, options.piSync?.versions() ?? null); |
| 484 | 485 | }; |
| 486 | /** The arm's P experiment state for the admin page; null when it does not answer in time. */ | |
| 487 | const askTuning = async () => { | |
| 488 | try { | |
| 489 | const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/tuning`, { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 1000)) }); | |
| 490 | return readTuning(answer.status, await answer.json().catch(() => null)); | |
| 491 | } catch { | |
| 492 | return null; | |
| 493 | } | |
| 494 | }; | |
| 495 | /** The admin page's "Try this P": the arm server runs it, and says why not in a sentence. */ | |
| 496 | const tuneP: TuneP = async (joint, p) => { | |
| 497 | try { | |
| 498 | const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/tuning/p`, { method: "POST", body: JSON.stringify({ joint, p }), signal: AbortSignal.timeout(Math.min(readTimeoutMs, 3000)) }); | |
| 499 | if (answer.status === 202) return null; | |
| 500 | const body = (await answer.json().catch(() => null)) as { error?: unknown } | null; | |
| 501 | return typeof body?.error === "string" ? body.error.replace(/[\p{Cc}\p{Cf}]/gu, "").slice(0, 200) : `the arm server answered ${answer.status}`; | |
| 502 | } catch (err) { | |
| 503 | return `the arm server did not answer (${reason(err)})`; | |
| 504 | } | |
| 505 | }; | |
| 485 | 506 | /** The arm's servo registers for the owner's admin page; null when the arm does not answer in time. */ |
| 486 | 507 | const askServos = async () => { |
| 487 | 508 | try { |
| 488 | 509 | const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/servo-params`, { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 3000)) }); |
| 489 | return readServos(answer.status, await answer.json().catch(() => null)); | |
| 510 | const panel = readServos(answer.status, await answer.json().catch(() => null)); | |
| 511 | return { ...panel, tuning: await askTuning() }; // a sweep holds the arm, so /servo-params says 409 while the progress is the news | |
| 490 | 512 | } catch { |
| 491 | 513 | return null; |
| 492 | 514 | } |
| @@ -711,7 +733,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 711 | 733 | const cameraAdmin = ADMIN_CAMERA.exec(url.pathname); |
| 712 | 734 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 713 | 735 | if (lobby && url.pathname === "/admin/lift") return await handleLift(lobby, req, res, readBody); |
| 714 | if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision, askServos, videoCards, options.piSync ? () => options.piSync!.versions() : undefined); | |
| 736 | if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision, askServos, videoCards, options.piSync ? () => options.piSync!.versions() : undefined, tuneP); | |
| 715 | 737 | if (url.pathname === "/admin/versions") return versionsRead(req, res); |
| 716 | 738 | if (url.pathname === "/precision") return await precisionRead(req, res, url); |
| 717 | 739 | if (url.pathname === LEADER) return await leaderCalibration(req, res); |
Software/so101/src/server.ts +60 −1
| @@ -40,6 +40,9 @@ | ||
| 40 | 40 | * GET /precision the precision scorecard (src/precision.ts): tracking error, time to arrive, snap-backs by cause, |
| 41 | 41 | * latency by hop, for the session being driven, the last 10 minutes, and the stored sessions and hours; |
| 42 | 42 | * ?hours=1-720 hourly rows (48 by default) |
| 43 | * POST /tuning/p {"joint": id, "p": 1-64} run the P experiment (src/tuning-run.ts) on that joint while nobody drives: sweep, write, sweep, keep or put back; 202 at once, | |
| 44 | * 409 while a run is under way or anything drives, 423 on E-stop or hold; the result joins GET /precision's tunings | |
| 45 | * GET /tuning the run's phase while one is under way, and the last outcome | |
| 43 | 46 | * POST /precision/snap-back {"cause": one of CAUSES, "sizeDeg"}: a snap-back only the page saw, counted beside the server's own (400 for any other cause) |
| 44 | 47 | * GET /model.json the arm model: joints, the model's floor (floorZ) and the enforced table (tableZ), where the URDF is served |
| 45 | 48 | * GET /leader-map.js the leader calibration mapping, for the browser (src/leader-map.js) |
| @@ -70,7 +73,7 @@ import { dirname, extname, join, resolve } from "node:path"; | ||
| 70 | 73 | import type { Duplex } from "node:stream"; |
| 71 | 74 | import { createHash, randomUUID } from "node:crypto"; |
| 72 | 75 | import { fileURLToPath } from "node:url"; |
| 73 | import { ParamsError, factoryValues, readServoParams, recordFactory, validateWrite, writeServoParams } from "./servo-params.ts"; | |
| 76 | import { TUNABLE, ParamsError, factoryValues, readServoParams, recordFactory, validateWrite, writeServoParams } from "./servo-params.ts"; | |
| 74 | 77 | import { WebSocketServer, type WebSocket } from "ws"; |
| 75 | 78 | import { browserModule } from "./browser-modules.ts"; |
| 76 | 79 | import { Clock, CommandGate, HELD_CLOSE, isRelease } from "./command-gate.ts"; |
| @@ -83,6 +86,9 @@ import { MachineLog, perServo } from "./machine-log.ts"; | ||
| 83 | 86 | import { Metrics } from "./metrics.ts"; |
| 84 | 87 | import { ARRIVE_TICKS, parseSnapBack, type Cause, type Tracker } from "./precision.ts"; |
| 85 | 88 | import { deployedCommit, PrecisionHistory } from "./precision-history.ts"; |
| 89 | import { Tuning, TuningRefused } from "./tuning.ts"; | |
| 90 | import { sweepJoint } from "./tuning-sweep.ts"; | |
| 91 | import type { SweepResult, TuningDeps } from "./tuning-run.ts"; | |
| 86 | 92 | import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts"; |
| 87 | 93 | import { assertPoseName, parsePoseFile, serializePoseFile, type PoseFile } from "./poses.ts"; |
| 88 | 94 | import { MAX_ZERO_OFFSET_DEG, zeroOffsetDeg } from "./joint-zero.ts"; |
| @@ -108,6 +114,10 @@ export interface ServerOptions { | ||
| 108 | 114 | heartbeatMs?: number; |
| 109 | 115 | /** The commit the precision history tags its rows with; found from the environment or the checkout when not given. */ |
| 110 | 116 | commit?: string; |
| 117 | /** How long each sweep target is held, ms (1500); tests shorten it. */ | |
| 118 | tuningHoldMs?: number; | |
| 119 | /** Replaces the stream sweep of the P experiment; tests give it the numbers to decide on. */ | |
| 120 | tuningSweep?: (joint: number) => Promise<SweepResult>; | |
| 111 | 121 | /** Starting values for the safety settings, before what is stored (src/safety.ts). */ |
| 112 | 122 | safety?: Partial<SafetySettings>; |
| 113 | 123 | /** Speed used to catch up with the first frame of a stream, ticks/s. */ |
| @@ -329,6 +339,34 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 329 | 339 | driver = null; |
| 330 | 340 | current = null; |
| 331 | 341 | }; |
| 342 | const tuning = new Tuning(); | |
| 343 | /** The P experiment's hands: sweeps through the stream, reads and writes through the guarded servo-params path. */ | |
| 344 | const tuningDeps: TuningDeps = { | |
| 345 | isIdle: () => !driver && !estop && !gate.held, | |
| 346 | sweep: async (joint) => | |
| 347 | options.tuningSweep | |
| 348 | ? options.tuningSweep(joint) | |
| 349 | : sweepJoint(joint, { url: `http://127.0.0.1:${(http.address() as { port: number }).port}`, bounds: (id) => bounds().get(id), holdMs: options.tuningHoldMs ?? 1500, lastCard: () => precision.last, halted: () => (estop ? stopped(estop) : gate.held ? holding(gate.held) : null) }), | |
| 350 | readParams: async (id) => ({ P: (await readServoParams(bus, [id]))[0]?.registers.P_Coefficient ?? NaN }), | |
| 351 | writeParams: async (id, { P }) => { | |
| 352 | // Taking the arm may have to wait for a stream that is still closing; the old P must get back even so. | |
| 353 | for (let tries = 0; ; tries++) { | |
| 354 | try { | |
| 355 | claim("move"); | |
| 356 | break; | |
| 357 | } catch (err) { | |
| 358 | if (tries >= 25 || !(err instanceof HttpError) || err.status !== 409) throw err; | |
| 359 | await new Promise((r) => setTimeout(r, 200)); | |
| 360 | } | |
| 361 | } | |
| 362 | try { | |
| 363 | await writeServoParams(bus, id, { P_Coefficient: P }); | |
| 364 | machine.note("sent", "servo params tuning", { id, P }); | |
| 365 | } finally { | |
| 366 | release(); | |
| 367 | } | |
| 368 | }, | |
| 369 | }; | |
| 332 | 370 | const describe = (d: Driver) => ({ stream: "a stream", move: "a move", play: "a playback", record: "a recording", park: "the park move" })[d]; |
| 333 | 371 | |
| 334 | 372 | // ------------------------------------------------------------------ the safety envelope (src/safety.ts) |
| @@ -814,6 +852,27 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 814 | 852 | release(); |
| 815 | 853 | } |
| 816 | 854 | } |
| 855 | case "GET /tuning": | |
| 856 | return json(res, 200, tuning.state); | |
| 857 | case "POST /tuning/p": { | |
| 858 | const body = await readBody(req); | |
| 859 | const { joint, p } = body; | |
| 860 | if (typeof joint !== "number" || !ids.includes(joint)) throw new HttpError(400, `joint must be one of ${ids.join(", ")}`); | |
| 861 | const { min, max } = TUNABLE.P; | |
| 862 | if (typeof p !== "number" || !Number.isInteger(p) || p < min || p > max) throw new HttpError(400, `p must be a whole number from ${min} to ${max}`); | |
| 863 | if (estop) throw new HttpError(423, stopped(estop)); | |
| 864 | if (gate.held) throw new HttpError(423, holding(gate.held)); | |
| 865 | try { | |
| 866 | tuning.start({ joint, p }, tuningDeps, (result) => { | |
| 867 | precision.addTuning(result); | |
| 868 | machine.note("state", "tuning", { joint, from: result.from, to: result.to, kept: result.kept }); | |
| 869 | }); | |
| 870 | } catch (err) { | |
| 871 | if (err instanceof TuningRefused) throw new HttpError(err.status, err.message); | |
| 872 | throw err; | |
| 873 | } | |
| 874 | return json(res, 202, tuning.state); | |
| 875 | } | |
| 817 | 876 | case "GET /poses": |
| 818 | 877 | return json(res, 200, loadPoses()); |
| 819 | 878 | case "GET /recordings": |
Software/so101/src/servo-panel.test.ts +13
| @@ -75,3 +75,16 @@ test("while someone drives, the owner reads a sentence", async () => { | ||
| 75 | 75 | const text = await (await fetch(`http://127.0.0.1:${relay.port}/admin`, { headers: as("trevato", "admin") })).text(); |
| 76 | 76 | expect(text).toContain("Someone is driving the arm"); |
| 77 | 77 | }); |
| 78 | ||
| 79 | test("each joint has a Try this P field, and the run's progress or refusal shows as a sentence", () => { | |
| 80 | const rows = [{ id: 2, joint: "shoulder_lift", registers: { P_Coefficient: 16 }, error: null }]; | |
| 81 | const esc = (s: string) => s.replace(/</g, "<"); | |
| 82 | const idle = servosSection({ rows }, esc); | |
| 83 | expect(idle).toContain('name="action" value="tune-p"'); | |
| 84 | expect(idle).toContain('name="joint" value="2"'); | |
| 85 | expect(idle).toContain("Try this P</button>"); | |
| 86 | const busy = servosSection({ notice: "Someone is driving", tuning: { running: { joint: 2, p: 24, phase: "second sweep with the new P" }, last: null } }, esc); | |
| 87 | expect(busy).toContain("Trying P 24 on shoulder_lift (2): second sweep with the new P"); | |
| 88 | const stopped = servosSection({ rows, tuning: { running: null, last: { joint: 2, p: 24, error: "sweep stopped: STOP", result: null } } }, esc); | |
| 89 | expect(stopped).toContain("stopped: sweep stopped: STOP"); | |
| 90 | }); |
Software/so101/src/servo-panel.ts +15 −4
| @@ -4,6 +4,9 @@ | ||
| 4 | 4 | * answer shows its error in its row; a 409 (someone is driving) or an unreachable arm is one sentence. No script. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { TUNABLE } from "./servo-params.ts"; | |
| 8 | import { tuningSentence, type TuningView } from "./tuning-panel.ts"; | |
| 9 | ||
| 7 | 10 | export interface ServoRow { |
| 8 | 11 | id: number; |
| 9 | 12 | joint: string | null; |
| @@ -12,7 +15,7 @@ export interface ServoRow { | ||
| 12 | 15 | } |
| 13 | 16 | |
| 14 | 17 | /** Either the joints as read, or why there is nothing to show. */ |
| 15 | export type ServoPanel = { rows: ServoRow[] } | { notice: string }; | |
| 18 | export type ServoPanel = ({ rows: ServoRow[] } | { notice: string }) & { tuning?: TuningView | null }; | |
| 16 | 19 | |
| 17 | 20 | const MAX_ROWS = 32; |
| 18 | 21 | const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}); |
| @@ -38,12 +41,20 @@ export function readServos(status: number, body: unknown): ServoPanel { | ||
| 38 | 41 | export function servosSection(p: ServoPanel | null | undefined, esc: (s: string) => string): string { |
| 39 | 42 | const head = `<section aria-labelledby="servos"><h2 id="servos">Servos</h2>`; |
| 40 | 43 | if (!p) return `${head}<p class="empty">The arm server did not answer <code>/servo-params</code>.</p></section>`; |
| 41 | if ("notice" in p) return `${head}<p class="empty">${esc(p.notice)}</p></section>`; | |
| 44 | const said = tuningSentence(p.tuning); | |
| 45 | const status = said ? `<p role="status"><b>${esc(said)}</b></p>` : ""; | |
| 46 | if ("notice" in p) return `${head}<p class="empty">${esc(p.notice)}</p>${status}</section>`; | |
| 42 | 47 | if (!p.rows.length) return `${head}<p class="empty">The arm server listed no servos.</p></section>`; |
| 43 | 48 | const cols = [...new Set(p.rows.flatMap((r) => Object.keys(r.registers)))]; |
| 44 | 49 | const th = cols.map((c) => `<th scope="col">${esc(c.replaceAll("_", " "))}</th>`).join(""); |
| 45 | 50 | const body = p.rows |
| 46 | .map((r) => `<tr><th scope="row">${esc(r.joint ?? "?")} (${r.id})</th>${cols.map((c) => `<td>${c in r.registers ? r.registers[c] : "—"}</td>`).join("")}<td>${r.error ? `<b>${esc(r.error)}</b>` : ""}</td></tr>`) | |
| 51 | .map((r) => `<tr><th scope="row">${esc(r.joint ?? "?")} (${r.id})</th>${cols.map((c) => `<td>${c in r.registers ? r.registers[c] : "—"}</td>`).join("")}<td>${r.error ? `<b>${esc(r.error)}</b>` : ""}</td><td>${tryForm(r.id, Boolean(p.tuning?.running))}</td></tr>`) | |
| 47 | 52 | .join(""); |
| 48 | return `${head}<div class="scroll"><table aria-label="Servo control registers"><caption>Each joint's control registers, read just now; read-only.</caption><thead><tr><th scope="col">Joint</th>${th}<th scope="col">Error</th></tr></thead><tbody>${body}</tbody></table></div></section>`; | |
| 53 | return `${head}<div class="scroll"><table aria-label="Servo control registers"><caption>Each joint's control registers, read just now.</caption><thead><tr><th scope="col">Joint</th>${th}<th scope="col">Error</th><th scope="col">Try this P</th></tr></thead><tbody>${body}</tbody></table></div>${status}<p class="empty">Try this P sweeps the joint, writes the P, sweeps again and keeps it only if the tracking error and the overshoot are no worse and one is better; otherwise the old P is written back. Nobody can drive meanwhile.</p></section>`; | |
| 54 | } | |
| 55 | ||
| 56 | /** The field and button for one joint: the owner's form posts to /admin, which asks the arm server to run it. */ | |
| 57 | function tryForm(id: number, busy: boolean): string { | |
| 58 | const { min, max } = TUNABLE.P; | |
| 59 | return `<form method="post" action="/admin" class="inline"><input type="hidden" name="action" value="tune-p"><input type="hidden" name="joint" value="${id}"><input name="p" type="number" inputmode="numeric" min="${min}" max="${max}" step="1" required aria-label="P to try on joint ${id}"> <button${busy ? " disabled" : ""}>Try this P</button></form>`; | |
| 49 | 60 | } |
Software/so101/src/tuning-endpoint.test.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | import { afterEach, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } 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 { startServer, type RunningServer } from "./server.ts"; | |
| 9 | import type { SweepResult } from "./tuning-run.ts"; | |
| 10 | ||
| 11 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 12 | const r = (p95Error: number, overshoot: number): SweepResult => ({ p95Error, overshoot, timeToArrive: 1 }); | |
| 13 | let server: RunningServer | undefined; | |
| 14 | let fake: FakeBus; | |
| 15 | let base = ""; | |
| 16 | ||
| 17 | async function boot(sweeps?: SweepResult[], hold = 60) { | |
| 18 | fake = new FakeBus([1, 2]); | |
| 19 | fake.servos.get(1)![21] = 16; // P_Coefficient | |
| 20 | server = await startServer(new FeetechBus(fake), { | |
| 21 | host: "127.0.0.1", port: 0, ids: [1, 2], posesFile: join(mkdtempSync(join(tmpdir(), "so101-tuning-")), "poses.json"), watchdogMs: 60, commit: "abc1234", | |
| 22 | tuningHoldMs: hold, | |
| 23 | ...(sweeps ? { tuningSweep: async () => sweeps.shift()! } : {}), | |
| 24 | }); | |
| 25 | base = `http://127.0.0.1:${server.port}`; | |
| 26 | } | |
| 27 | afterEach(() => Promise.race([server?.close(), sleep(500)])); | |
| 28 | const post = (body: unknown) => fetch(`${base}/tuning/p`, { method: "POST", body: JSON.stringify(body) }); | |
| 29 | const finished = async () => { | |
| 30 | for (let i = 0; i < 200; i++) { | |
| 31 | const s = (await (await fetch(`${base}/tuning`)).json()) as { running: unknown; last: any }; | |
| 32 | if (!s.running && s.last) return s.last; | |
| 33 | await sleep(25); | |
| 34 | } | |
| 35 | throw new Error("the run did not finish"); | |
| 36 | }; | |
| 37 | ||
| 38 | test("a run that keeps leaves the new P, and the result is in the precision history tagged with the commit", async () => { | |
| 39 | await boot([r(10, 5), r(8, 5)]); | |
| 40 | expect((await post({ joint: 1, p: 24 })).status).toBe(202); | |
| 41 | const last = await finished(); | |
| 42 | expect(last.result).toMatchObject({ joint: 1, from: 16, to: 24, kept: true }); | |
| 43 | expect(fake.servos.get(1)![21]).toBe(24); | |
| 44 | const card = (await (await fetch(`${base}/precision`)).json()) as { tunings: Array<{ joint: number; kept: boolean; commit: string }> }; | |
| 45 | expect(card.tunings).toHaveLength(1); | |
| 46 | expect(card.tunings[0]).toMatchObject({ joint: 1, kept: true, commit: "abc1234" }); | |
| 47 | }); | |
| 48 | ||
| 49 | test("a run that does not improve puts the old P back and is kept as such, newest first", async () => { | |
| 50 | await boot([r(10, 5), r(12, 5), r(10, 5), r(8, 5)]); | |
| 51 | await post({ joint: 1, p: 24 }); | |
| 52 | expect((await finished()).result.kept).toBe(false); | |
| 53 | expect(fake.servos.get(1)![21]).toBe(16); | |
| 54 | await post({ joint: 1, p: 20 }); | |
| 55 | for (let i = 0; i < 100 && ((await (await fetch(`${base}/precision`)).json()) as { tunings: unknown[] }).tunings.length < 2; i++) await sleep(25); | |
| 56 | const card = (await (await fetch(`${base}/precision`)).json()) as { tunings: Array<{ to: number; kept: boolean }> }; | |
| 57 | expect(card.tunings.map((t) => [t.to, t.kept])).toEqual([[20, true], [16, false]]); | |
| 58 | }); | |
| 59 | ||
| 60 | test("a second run while one is under way is a 409, and a bad body a 400", async () => { | |
| 61 | await boot(); | |
| 62 | let release!: () => void; | |
| 63 | const gate = new Promise<void>((resolve) => (release = resolve)); | |
| 64 | await server!.close(); | |
| 65 | fake = new FakeBus([1, 2]); | |
| 66 | server = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, ids: [1, 2], posesFile: join(mkdtempSync(join(tmpdir(), "so101-tuning-")), "poses.json"), tuningSweep: async () => (await gate, r(1, 1)) }); | |
| 67 | base = `http://127.0.0.1:${server.port}`; | |
| 68 | expect((await post({ joint: 9, p: 24 })).status).toBe(400); | |
| 69 | expect((await post({ joint: 1, p: 99 })).status).toBe(400); | |
| 70 | expect((await post({ joint: 1, p: 24 })).status).toBe(202); | |
| 71 | const second = await post({ joint: 2, p: 24 }); | |
| 72 | expect(second.status).toBe(409); | |
| 73 | expect(((await second.json()) as { error: string }).error).toContain("already under way"); | |
| 74 | expect(((await (await fetch(`${base}/tuning`)).json()) as { running: { joint: number } }).running.joint).toBe(1); | |
| 75 | release(); | |
| 76 | await finished(); | |
| 77 | }); | |
| 78 | ||
| 79 | test("a run is refused while someone drives, and nothing is written", async () => { | |
| 80 | await boot([r(1, 1), r(1, 1)]); | |
| 81 | const ws = new WebSocket(`ws://127.0.0.1:${server!.port}/follow`); | |
| 82 | await new Promise((resolve) => ws.once("open", resolve)); | |
| 83 | ws.send(JSON.stringify({ 1: 2000 })); | |
| 84 | await sleep(50); | |
| 85 | const writes = fake.writes.length; | |
| 86 | const res = await post({ joint: 1, p: 24 }); | |
| 87 | expect(res.status).toBe(409); | |
| 88 | expect(((await res.json()) as { error: string }).error).toContain("driving"); | |
| 89 | expect(fake.writes.length).toBe(writes); | |
| 90 | ws.close(); | |
| 91 | await sleep(100); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a real sweep through the stream ends with a result and the P that result says", async () => { | |
| 95 | await boot(undefined, 120); | |
| 96 | expect((await post({ joint: 1, p: 24 })).status).toBe(202); | |
| 97 | const last = await finished(); | |
| 98 | if (last.error) throw new Error(last.error); | |
| 99 | expect(fake.servos.get(1)![21]).toBe(last.result.kept ? 24 : 16); | |
| 100 | }, 20000); |
Software/so101/src/tuning-panel.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | /** | |
| 2 | * The P experiment on /admin: the arm server's GET /tuning and the tunings in GET /precision read field by field, for | |
| 3 | * they come over the network from another machine, and drawn as sentences. Plain text; no script. | |
| 4 | */ | |
| 5 | import { JOINTS } from "./sts3215.ts"; | |
| 6 | ||
| 7 | export interface TuningResult { | |
| 8 | joint: number; | |
| 9 | from: number; | |
| 10 | to: number; | |
| 11 | kept: boolean; | |
| 12 | /** p95 tracking error in degrees, or the arm's own unit; the sweep's number as measured. */ | |
| 13 | before: number; | |
| 14 | after: number; | |
| 15 | overshootBefore: number; | |
| 16 | overshootAfter: number; | |
| 17 | commit: string | null; | |
| 18 | at: string | null; | |
| 19 | } | |
| 20 | ||
| 21 | export interface TuningView { | |
| 22 | running: { joint: number; p: number; phase: string } | null; | |
| 23 | last: { joint: number; p: number; error: string | null; result: TuningResult | null } | null; | |
| 24 | } | |
| 25 | ||
| 26 | const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}); | |
| 27 | const int = (v: unknown): number | null => (typeof v === "number" && Number.isInteger(v) && v >= 0 && v < 1000 ? v : null); | |
| 28 | const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); | |
| 29 | const short = (v: unknown, max = 120): string => [...String(v).replace(/[\p{Cc}\p{Cf}]/gu, "")].slice(0, max).join(""); | |
| 30 | ||
| 31 | /** One experiment as /precision or /tuning gave it; null when it is not one. */ | |
| 32 | export function readTuningResult(v: unknown): TuningResult | null { | |
| 33 | const r = obj(v), before = obj(r.before), after = obj(r.after); | |
| 34 | const joint = int(r.joint), from = int(r.from), to = int(r.to); | |
| 35 | const [b, a, ob, oa] = [num(before.p95Error), num(after.p95Error), num(before.overshoot), num(after.overshoot)]; | |
| 36 | if (joint === null || from === null || to === null || b === null || a === null || ob === null || oa === null || typeof r.kept !== "boolean") return null; | |
| 37 | return { joint, from, to, kept: r.kept, before: b, after: a, overshootBefore: ob, overshootAfter: oa, commit: typeof r.commit === "string" ? short(r.commit, 12) : null, at: typeof r.at === "string" ? short(r.at, 24) : null }; | |
| 38 | } | |
| 39 | ||
| 40 | /** The run state from GET /tuning; null when the arm did not answer with one. */ | |
| 41 | export function readTuning(status: number, body: unknown): TuningView | null { | |
| 42 | if (status !== 200) return null; | |
| 43 | const b = obj(body), running = obj(b.running), last = obj(b.last); | |
| 44 | const run = int(running.joint) !== null && int(running.p) !== null ? { joint: int(running.joint)!, p: int(running.p)!, phase: short(running.phase, 80) } : null; | |
| 45 | const lj = int(last.joint), lp = int(last.p); | |
| 46 | const done = lj !== null && lp !== null ? { joint: lj, p: lp, error: typeof last.error === "string" ? short(last.error) : null, result: readTuningResult(last.result) } : null; | |
| 47 | return { running: run, last: done }; | |
| 48 | } | |
| 49 | ||
| 50 | const name = (joint: number) => JOINTS[joint] ?? `joint ${joint}`; | |
| 51 | const label = (joint: number) => `${name(joint)} (${joint})`; | |
| 52 | ||
| 53 | /** One experiment as a sentence's worth of facts: "shoulder_pan (1) P 16→24 · error 10→8 · kept". */ | |
| 54 | export function resultLine(r: TuningResult): string { | |
| 55 | return `${label(r.joint)} · P ${r.from}→${r.to} · error ${r.before}→${r.after}, overshoot ${r.overshootBefore}→${r.overshootAfter} · ${r.kept ? "kept" : "put back"}`; | |
| 56 | } | |
| 57 | ||
| 58 | /** What is going on, or what just happened, as one sentence; null before any run. */ | |
| 59 | export function tuningSentence(t: TuningView | null | undefined): string | null { | |
| 60 | if (!t) return null; | |
| 61 | if (t.running) return `Trying P ${t.running.p} on ${label(t.running.joint)}: ${t.running.phase}. Reload to follow it; nobody can drive until it ends.`; | |
| 62 | if (t.last?.error) return `The last try of P ${t.last.p} on ${label(t.last.joint)} stopped: ${t.last.error}. The old P is back.`; | |
| 63 | if (t.last?.result) { | |
| 64 | const r = t.last.result; | |
| 65 | return `The last try of P ${t.last.p} on ${label(r.joint)} was ${r.kept ? "kept" : "put back"}: p95 error ${r.before}→${r.after}, overshoot ${r.overshootBefore}→${r.overshootAfter}.`; | |
| 66 | } | |
| 67 | return null; | |
| 68 | } | |
| 69 | ||
| 70 | /** The newest experiments, newest first, as the Precision panel lists them. */ | |
| 71 | export function tuningList(rows: readonly TuningResult[], esc: (s: string) => string): string { | |
| 72 | if (!rows.length) return ""; | |
| 73 | const items = rows.map((r) => `<li><span>${esc(r.at ? r.at.slice(0, 16).replace("T", " ") : "")} · ${esc(r.commit ?? "unknown")}</span><span>${esc(resultLine(r))}</span></li>`).join(""); | |
| 74 | return `<h3>P experiments</h3><ol class="bars precision" aria-label="P experiments, newest first">${items}</ol>`; | |
| 75 | } |
Software/so101/src/tuning-sweep.ts added +57
| @@ -0,0 +1,57 @@ | ||
| 1 | /** | |
| 2 | * One joint's test sweep, driven through the server's own /follow stream so the governor, the zones and the torque cap | |
| 3 | * apply as they do to a person, and the stream's precision session measures it. The targets are bench/limits-sweep.ts's. | |
| 4 | */ | |
| 5 | import WebSocket from "ws"; | |
| 6 | import type { Card } from "./precision.ts"; | |
| 7 | import type { SweepResult } from "./tuning-run.ts"; | |
| 8 | ||
| 9 | /** Ticks from the middle of the joint's bounds, each held for the hold time. */ | |
| 10 | export const OFFSETS = [0, 250, 0, -250, 0] as const; | |
| 11 | ||
| 12 | /** The joint's targets: the offsets from the middle of its bounds, kept inside them. */ | |
| 13 | export function targets(lo: number, hi: number): number[] { | |
| 14 | const mid = Math.round((lo + hi) / 2); | |
| 15 | return OFFSETS.map((o) => Math.min(hi, Math.max(lo, mid + o))); | |
| 16 | } | |
| 17 | ||
| 18 | export interface SweepSource { | |
| 19 | /** Where the stream is listening. */ | |
| 20 | url: string; | |
| 21 | bounds(joint: number): { min: number; max: number } | undefined; | |
| 22 | holdMs: number; | |
| 23 | /** The card of the session that ended last, for the numbers. */ | |
| 24 | lastCard(): Card | null; | |
| 25 | /** Why the sweep must stop now (an E-stop or a hold), or null. */ | |
| 26 | halted(): string | null; | |
| 27 | } | |
| 28 | ||
| 29 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 30 | ||
| 31 | /** Drive one joint through its targets and answer what the stream's session measured. Throws, naming why, if it is stopped. */ | |
| 32 | export async function sweepJoint(joint: number, source: SweepSource): Promise<SweepResult> { | |
| 33 | const range = source.bounds(joint); | |
| 34 | if (!range) throw new Error(`joint ${joint} has no bounds`); | |
| 35 | const before = source.lastCard(); | |
| 36 | const ws = new WebSocket(`${source.url.replace(/^http/, "ws")}/follow`); | |
| 37 | let closed: number | null = null; | |
| 38 | ws.on("close", (code) => (closed = code)); | |
| 39 | await new Promise((resolve, reject) => (ws.once("open", resolve), ws.once("error", reject), ws.once("close", (c) => reject(new Error(`the stream was refused (${c})`))))); | |
| 40 | try { | |
| 41 | for (const t of targets(range.min, range.max)) { | |
| 42 | ws.send(JSON.stringify({ [joint]: t })); | |
| 43 | await sleep(source.holdMs); | |
| 44 | const why = source.halted() ?? (closed !== null ? `the stream closed (${closed})` : null); | |
| 45 | if (why) throw new Error(`sweep stopped: ${why}`); | |
| 46 | } | |
| 47 | } finally { | |
| 48 | ws.close(1000); | |
| 49 | await new Promise((r) => (ws.readyState === WebSocket.CLOSED ? r(null) : ws.once("close", r))); | |
| 50 | } | |
| 51 | for (let waited = 0; source.lastCard() === before && waited < 3000; waited += 25) await sleep(25); // the server closes the session after the socket | |
| 52 | const card = source.lastCard(); | |
| 53 | const j = card === before ? undefined : card?.joints.find((x) => x.id === joint); | |
| 54 | if (!j || j.errorDeg.p95 === null) throw new Error("the sweep measured nothing"); | |
| 55 | if (card!.snapBacks.total) throw new Error("sweep stopped: the arm refused or held back a target"); | |
| 56 | return { p95Error: j.errorDeg.p95, overshoot: j.overshootTicks.max ?? 0, timeToArrive: j.arriveMs.p95 ?? 0 }; | |
| 57 | } |
Software/so101/src/tuning.ts added +57
| @@ -0,0 +1,57 @@ | ||
| 1 | /** The one P experiment that may run at a time on the arm server, its progress, and the last outcome. */ | |
| 2 | import { runPExperiment, type PExperiment, type TuningDeps } from "./tuning-run.ts"; | |
| 3 | ||
| 4 | export interface TuningState { | |
| 5 | running: { joint: number; p: number; phase: string } | null; | |
| 6 | /** The last run's result, or why it stopped; null before any. */ | |
| 7 | last: { joint: number; p: number; result: PExperiment } | { joint: number; p: number; error: string } | null; | |
| 8 | } | |
| 9 | ||
| 10 | /** A refusal the server answers with `status`. */ | |
| 11 | export class TuningRefused extends Error { | |
| 12 | readonly status: number; | |
| 13 | constructor(status: number, message: string) { | |
| 14 | super(message); | |
| 15 | this.status = status; | |
| 16 | } | |
| 17 | } | |
| 18 | ||
| 19 | export class Tuning { | |
| 20 | : TuningState = { running: null, last: null }; | |
| 21 | ||
| 22 | get state(): TuningState { | |
| 23 | return structuredClone(this.); | |
| 24 | } | |
| 25 | ||
| 26 | /** | |
| 27 | * Start the run in the background; a second while one is under way is a 409, as is one with someone driving. | |
| 28 | * `done` is told each finished experiment. | |
| 29 | */ | |
| 30 | start(request: { joint: number; p: number }, deps: TuningDeps, done: (result: PExperiment) => void): void { | |
| 31 | if (this..running) throw new TuningRefused(409, "a tuning run is already under way"); | |
| 32 | if (!deps.isIdle()) throw new TuningRefused(409, "someone is driving the arm; try again when nobody has a turn"); | |
| 33 | const running = { ...request, phase: "reading the joint" }; | |
| 34 | this..running = running; | |
| 35 | let sweeps = 0; | |
| 36 | const watched: TuningDeps = { | |
| 37 | ...deps, | |
| 38 | sweep: async (joint) => { | |
| 39 | running.phase = sweeps++ ? "second sweep with the new P" : "first sweep with the current P"; | |
| 40 | return deps.sweep(joint); | |
| 41 | }, | |
| 42 | writeParams: async (id, values) => { | |
| 43 | running.phase = `writing P ${values.P}`; | |
| 44 | return deps.writeParams(id, values); | |
| 45 | }, | |
| 46 | }; | |
| 47 | runPExperiment(request, watched).then( | |
| 48 | (result) => { | |
| 49 | this..last = { ...request, result }; | |
| 50 | done(result); | |
| 51 | }, | |
| 52 | (err) => { | |
| 53 | this..last = { ...request, error: err instanceof Error ? err.message : String(err) }; | |
| 54 | }, | |
| 55 | ).finally(() => (this..running = null)); | |
| 56 | } | |
| 57 | } |
new above
offline