Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Pump: an interval-cycle schedule on the Switch interface (with #585) #596
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
quill/arm:quill/595-pump-an-interval-cycle-schedule-on-the-s → main 7 commits fork 2 threads · 2 unresolved
19 files
changed +1375
−19
Software/so101/README.md +35
| @@ -45,6 +45,41 @@ The arm closes itself too: a real arm (ARM_SERVER) that has not answered for mor | ||
| 45 | 45 | |
| 46 | 46 | `GET /status` says so for everyone: `{"open": false, "reason": "closed"|"offline", "note": "…"|null, "reopenAt": ISO|null, "lastOpenAt": ISO|null, "driver": null, "source": "The arm is resting"}`, answered without asking the arm; while open, the arm's status as before with `"open": true`. |
| 47 | 47 | |
| 48 | ## Grow light and pump (/admin → Grow) | |
| 49 | ||
| 50 | Two devices, the light and the pump, each with **one switch** and **one schedule**, run by the arm server on the Pi, so | |
| 51 | they never depend on the forge or the network. The light is a daily photoperiod (on at 06:00 for 12 h, in the Pi's | |
| 52 | time zone, DST-safe: the window is real hours from the local start). The pump is an interval cycle (N minutes on, M | |
| 53 | off, counted from the Unix epoch, so every clock agrees and a reboot lands in the same phase). Spinach is long-day | |
| 54 | sensitive: 12 h is the default, keep it at 14 h or less (the card warns above that). In the light's off hours the card | |
| 55 | says "Dark period: keep room lights off": spinach counts room light in its dark period as day. (A short photo light for | |
| 56 | night photos is not built yet.) On start the Pi sets the state each schedule says now; every change is logged (time, | |
| 57 | state, cause: schedule, override or boot) in `light.log.jsonl` / `pump.log.jsonl` beside `light.json` / `pump.json` in | |
| 58 | the arm's data, and the card shows the last twelve as a strip. A manual override holds until the next transition. Until | |
| 59 | a switch is set up the card says "Light: always on (no switch set up)" or "Pump: not run (no switch set up)". The arm | |
| 60 | server's `GET /grow` (both devices) and `POST /grow/light` · `POST /grow/pump` carry it. The Shelly host is fetched by | |
| 61 | the Pi, so every route to it is the owner's. | |
| 62 | ||
| 63 | **The hardware truth:** a Pi 4 cannot switch one USB port alone. `uhubctl` toggles all the ports of a hub together | |
| 64 | (ganged on the VL805, and on an external VIA hub; check with `uhubctl -l 1-1`), so cutting the light that way also cuts | |
| 65 | both cameras. The switch drivers: | |
| 66 | ||
| 67 | - `shelly`: a Shelly smart plug on the LAN, local HTTP, no cloud account (Gen1 `/relay/0`, Gen2 `/rpc/Switch.Set`). The recommended path, about $15. | |
| 68 | - `gpio`: a relay on a GPIO line, through libgpiod's `gpioset` / `gpioget` (needs `gpiod` v2 on the Pi), for a 5 V relay module. | |
| 69 | - `uhubctl`: only for a port that switches alone. Saving it lists the hub; it **refuses** when the hub is ganged and a camera (named in the form by USB id, or with "cam" / "video" / "UVC" in its name) is on it, and checks again before every switch. | |
| 70 | - Tapo: not included; its local protocol is encrypted and needs an account login. | |
| 71 | ||
| 72 | **From the terminal** (owner only; anyone else is told it is the owner's, exactly as for `/servos`), the same arm-server | |
| 73 | `GET /grow` and `POST /grow/<light|pump>` the page uses. With no device word, a command is the light's: | |
| 74 | ||
| 75 | - `/grow`: the light and the pump, each with what it does now, its schedule and switch, the dark-period caution and its last three changes. | |
| 76 | - `/grow [light|pump] on|off|clear`: an override until the next change, or back to the schedule. | |
| 77 | - `/grow light schedule 06:00 12` · `/grow pump schedule 5 25` · `schedule off`: a photoperiod (on at, hours) or a cycle (minutes on, minutes off). | |
| 78 | - `/grow pump switch shelly 192.168.1.40 [1|2]` · `switch gpio 17 [low]` · `switch uhubctl 1-1 2 [vid:pid…]` · `switch none`: the arm server refuses a `uhubctl` port a camera shares, and says so. | |
| 79 | ||
| 80 | `/grow`, `POST /grow/light` and `POST /grow/pump` through the app are the owner's: to anyone else they answer 404. | |
| 81 | `bench/fake-serve.ts` (what production and the previews run) runs the schedules too, on its simulated arm. | |
| 82 | ||
| 48 | 83 | ## The workshop: stations on / |
| 49 | 84 | |
| 50 | 85 | The app is a workshop: one Pi, several **stations**, each with its cameras and controls. Today there are two, **the arm** and **the grow box** (spinach under a UV light). `/` is the workshop home, a card per station with its live camera snapshot first and its controls after, and the arm's own page is at `/arm` (its URL is unchanged for anyone who has it). The page and its title say "Workshop"; it shows who is looking ("Signed in as …", or "Watching as a guest · Sign in"), has a skip link, and keeps working while the arm is closed. |
Software/so101/bench/fake-serve.ts +1 −1
| @@ -39,7 +39,7 @@ const dir = appData ? join(appData, "so101") : mkdtempSync(join(tmpdir(), "so101 | ||
| 39 | 39 | mkdirSync(dir, { recursive: true }); |
| 40 | 40 | const port = Number(process.env.PORT ?? process.argv[2] ?? 8102); |
| 41 | 41 | const host = process.env.HOST ?? "127.0.0.1"; |
| 42 | const simulation = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, posesFile: join(dir, "poses.json"), modelDir: new URL("../../../Simulation/SO101", import.meta.url).pathname }); | |
| 42 | const simulation = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, posesFile: join(dir, "poses.json"), modelDir: new URL("../../../Simulation/SO101", import.meta.url).pathname, lightMs: 15_000 }); | |
| 43 | 43 | let remote: Remote | null = null; |
| 44 | 44 | let problem: string | null = null; |
| 45 | 45 | try { |
Software/so101/src/admin-page.ts +19 −1
| @@ -14,6 +14,8 @@ import type { ViewerRow } from "./viewer-reports.ts"; | ||
| 14 | 14 | import type { Versions } from "./pi-deploy.ts"; |
| 15 | 15 | import { precisionSection, type PrecisionPanel } from "./precision-panel.ts"; |
| 16 | 16 | import { ALIGNED_DEG, REFERENCES, alignment } from "./joint-reference.ts"; |
| 17 | import { lightSections } from "./light-panel.ts"; | |
| 18 | import type { LightView } from "./light.ts"; | |
| 17 | 19 | import { servosSection, type ServoPanel } from "./servo-panel.ts"; |
| 18 | 20 | import { videoSection, type VideoCard } from "./video-panel.ts"; |
| 19 | 21 | import { NOTE_CHARS, OFFLINE_AFTER_MS, type OpenState, type Resting } from "./opening.ts"; |
| @@ -66,6 +68,19 @@ th { color: var(--dim); font-weight: 600; } | ||
| 66 | 68 | .bars.precision li { grid-template-columns: minmax(8rem, 15rem) 1fr; } |
| 67 | 69 | .bars.precision li small { color: var(--dim); font-size: .85em; } |
| 68 | 70 | .inline { display: inline; margin: 0; } |
| 71 | .strip { display: flex; flex-wrap: wrap; gap: .4rem; font-size: .8rem; font-variant-numeric: tabular-nums; } | |
| 72 | .strip li { display: block; padding: .15rem .5rem; border: 1px solid var(--line); border-radius: 6px; } | |
| 73 | .strip li.on { border-color: var(--ok); } | |
| 74 | .strip small { color: var(--dim); } | |
| 75 | details { border: 1px solid var(--line); border-radius: 8px; padding: 0 .75rem; margin: .5rem 0; } | |
| 76 | details[open] { padding-bottom: .75rem; } | |
| 77 | summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; font-weight: 600; } | |
| 78 | details form { display: grid; gap: .75rem; } | |
| 79 | details input, details select, details button { min-height: 44px; } | |
| 80 | label.check { display: flex; align-items: center; gap: .5rem; min-height: 44px; } | |
| 81 | label.check input { width: auto; min-height: 24px; min-width: 24px; } | |
| 82 | h4 { margin: 1rem 0 .25rem; font-size: .95rem; } | |
| 83 | select { font: inherit; padding: .55rem .75rem; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--fg); width: 100%; min-height: 44px; } | |
| 69 | 84 | .empty { color: var(--dim); } |
| 70 | 85 | @media (prefers-reduced-motion: reduce) { * { transition: none !important; } } |
| 71 | 86 | `; |
| @@ -194,7 +209,7 @@ export const adminCsp = (canEdit: boolean): string => | ||
| 194 | 209 | `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'`; |
| 195 | 210 | |
| 196 | 211 | /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */ |
| 197 | export const DONE = { opened: "Open: people can take turns again.", closed: "Closed: visitors see the resting card.", 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; | |
| 212 | export const DONE = { opened: "Open: people can take turns again.", closed: "Closed: visitors see the resting card.", 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.", lightSaved: "Saved: the Pi applies it within 15 seconds.", tuning: "The P experiment is running on the arm: reload to follow it." } as const; | |
| 198 | 213 | export type Done = keyof typeof DONE; |
| 199 | 214 | |
| 200 | 215 | export interface Target { id: string; name: string } |
| @@ -228,6 +243,8 @@ export interface AdminPage { | ||
| 228 | 243 | versions?: Versions; |
| 229 | 244 | /** Owner only: the servos' control registers (src/servo-panel.ts); null when the arm did not answer, absent when not asked. */ |
| 230 | 245 | servos?: ServoPanel | null; |
| 246 | /** The grow light (src/light-panel.ts); null when the arm server did not answer, absent when not asked. */ | |
| 247 | light?: { light: LightView; pump: LightView | null } | null; | |
| 231 | 248 | /** The cameras' H.264 numbers, beside it (src/video-panel.ts); absent when not asked. */ |
| 232 | 249 | video?: readonly VideoCard[]; |
| 233 | 250 | done?: Done | null; |
| @@ -400,6 +417,7 @@ ${p.canEdit && p.visitors ? visitorsSection(p.visitors) : ""} | ||
| 400 | 417 | ${p.versions ? versionsSection(p.versions) : ""} |
| 401 | 418 | ${p.precision !== undefined ? precisionSection(p.precision, esc) : ""} |
| 402 | 419 | ${p.canEdit && p.servos !== undefined ? servosSection(p.servos, esc) : ""} |
| 420 | ${p.light !== undefined ? lightSections(p.light, p.canEdit, esc) : ""} | |
| 403 | 421 | ${p.video !== undefined ? videoSection(p.video, esc) : ""} |
| 404 | 422 | <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section> |
| 405 | 423 | <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section> |
Software/so101/src/admin-relay.test.ts +23
| @@ -182,3 +182,26 @@ test("the P experiment is the owner's; anyone else gets 404, on the route and on | ||
| 182 | 182 | expect(owner.status).toBe(400); |
| 183 | 183 | expect(await owner.text()).toContain("did not answer"); |
| 184 | 184 | }); |
| 185 | ||
| 186 | test("the grow light: /grow is the owner's; light-* actions on /admin pass the owner and same-origin checks, then reach the arm", async () => { | |
| 187 | const base = await boot(); | |
| 188 | const owner = as("trevato", "admin"); | |
| 189 | const bob = as("bob", "user"); | |
| 190 | await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" })); | |
| 191 | for (const headers of [{}, bob]) { | |
| 192 | expect((await fetch(`${base}/grow`, { headers })).status).toBe(404); | |
| 193 | for (const device of ["light", "pump"]) expect((await fetch(`${base}/grow/${device}`, { method: "POST", headers, body: JSON.stringify({ override: "on" }) })).status).toBe(404); | |
| 194 | } | |
| 195 | expect((await fetch(`${base}/grow`, { headers: owner })).status).not.toBe(404); | |
| 196 | // a moderator and a stranger cannot post a light action; a foreign origin cannot either, even as the owner | |
| 197 | const action = { action: "light-override", device: "light", value: "on" }; | |
| 198 | expect((await fetch(`${base}/admin`, form(bob, action))).status).toBe(403); | |
| 199 | expect((await fetch(`${base}/admin`, form(as("eve", "user"), action))).status).toBe(404); | |
| 200 | const foreign = form(owner, action); | |
| 201 | expect((await fetch(`${base}/admin`, { ...foreign, headers: { ...foreign.headers, origin: "https://evil.example" } })).status).toBe(403); | |
| 202 | // the owner's reaches the arm server; here there is none, and the page says so instead of pretending | |
| 203 | const answer = await fetch(`${base}/admin`, form(owner, action)); | |
| 204 | expect(answer.status).toBe(400); | |
| 205 | expect(await answer.text()).toContain("the arm server did not answer"); | |
| 206 | expect((await fetch(`${base}/admin`, form(owner, { ...action, device: "toaster" }))).status).toBe(400); | |
| 207 | }); |
Software/so101/src/admin-routes.ts +23 −4
| @@ -8,6 +8,8 @@ import { sameOrigin } from "./relay.ts"; | ||
| 8 | 8 | import { adminCsp, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 9 | 9 | import type { Versions } from "./pi-deploy.ts"; |
| 10 | 10 | import type { PrecisionPanel } from "./precision-panel.ts"; |
| 11 | import { lightRequest } from "./light-panel.ts"; | |
| 12 | import type { DeviceName, LightView } from "./light.ts"; | |
| 11 | 13 | import type { ServoPanel } from "./servo-panel.ts"; |
| 12 | 14 | import type { VideoCard } from "./video-panel.ts"; |
| 13 | 15 | |
| @@ -22,6 +24,12 @@ export type AskServos = () => Promise<ServoPanel | null>; | ||
| 22 | 24 | /** Asks the arm server to run the P experiment; answers why not as a sentence, or null when it began. */ |
| 23 | 25 | export type TuneP = (joint: number, p: number) => Promise<string | null>; |
| 24 | 26 | |
| 27 | /** The grow light on the arm server: read it for the page, and send it a change (answers why not as a sentence, or null when it took). */ | |
| 28 | export interface LightHooks { | |
| 29 | read: () => Promise<{ light: LightView; pump: LightView | null } | null>; | |
| 30 | write: (device: DeviceName, body: Record<string, unknown>) => Promise<string | null>; | |
| 31 | } | |
| 32 | ||
| 25 | 33 | /** What a POST needs once the caller is known to be allowed on the page. */ |
| 26 | 34 | export interface AdminSession { |
| 27 | 35 | who: Person; |
| @@ -36,7 +44,7 @@ export interface AdminSession { | ||
| 36 | 44 | * Answer 404 to anyone not allowed, and the page itself to GET and HEAD. Returns the session for any other |
| 37 | 45 | * method by an allowed caller, and null when the response has been sent. |
| 38 | 46 | */ |
| 39 | export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, askPrecision?: AskPrecision, askServos?: AskServos, askVideo?: AskVideo, versions?: () => Versions): Promise<AdminSession | null> { | |
| 47 | export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, askPrecision?: AskPrecision, askServos?: AskServos, askVideo?: AskVideo, versions?: () => Versions, askLight?: LightHooks): Promise<AdminSession | null> { | |
| 40 | 48 | const who = lobby.who(req); |
| 41 | 49 | const html = (status: number, text: string, edit = false) => { |
| 42 | 50 | res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": adminCsp(edit) }); |
| @@ -62,8 +70,9 @@ export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: Se | ||
| 62 | 70 | const precision = (req.method === "GET" || req.method === "HEAD") && askPrecision ? await askPrecision() : undefined; |
| 63 | 71 | const servos = canEdit && (req.method === "GET" || req.method === "HEAD") && askServos ? await askServos() : undefined; |
| 64 | 72 | const video = askVideo?.(); |
| 73 | const light = (req.method === "GET" || req.method === "HEAD") && askLight ? await askLight.read() : undefined; | |
| 65 | 74 | const show = (status: number, done: Done | null, error: string | null) => |
| 66 | html(status, renderAdmin({ precision, servos, video, versions: versions?.(), who, signedIn: lobby.signedIn(req), canEdit, settings: lobby.admin.settings, opening: lobby.opening.state, resting: lobby.resting(), 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); | |
| 75 | html(status, renderAdmin({ precision, light, servos, video, versions: versions?.(), who, signedIn: lobby.signedIn(req), canEdit, settings: lobby.admin.settings, opening: lobby.opening.state, resting: lobby.resting(), 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); | |
| 67 | 76 | if (req.method === "GET" || req.method === "HEAD") { |
| 68 | 77 | const done = url.searchParams.get("done"); |
| 69 | 78 | show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); |
| @@ -82,8 +91,8 @@ const REPORT_ACTIONS = new Set(["report-remove", "report-mute", "report-dismiss" | ||
| 82 | 91 | type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>; |
| 83 | 92 | |
| 84 | 93 | /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */ |
| 85 | 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> { | |
| 86 | const session = await serveAdminPage(lobby, req, res, url, askPrecision, askServos, askVideo, versions); | |
| 94 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision, askServos?: AskServos, askVideo?: AskVideo, versions?: () => Versions, tune?: TuneP, askLight?: LightHooks): Promise<void> { | |
| 95 | const session = await serveAdminPage(lobby, req, res, url, askPrecision, askServos, askVideo, versions, askLight); | |
| 87 | 96 | if (!session) return; |
| 88 | 97 | const { who, canEdit, show } = session; |
| 89 | 98 | if (req.method !== "POST") { |
| @@ -152,6 +161,16 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve | ||
| 152 | 161 | done = act === "report-remove" ? "reportRemoved" : act === "report-mute" ? "reportMuted" : "reportDismissed"; |
| 153 | 162 | break; |
| 154 | 163 | } |
| 164 | case "light-schedule": | |
| 165 | case "light-switch": | |
| 166 | case "light-override": { | |
| 167 | const request = lightRequest(form); | |
| 168 | if (!request) throw new AdminError("no such device"); | |
| 169 | const refused = askLight ? await askLight.write(request.device, request.body) : "the arm is not reachable from here"; | |
| 170 | if (refused) throw new AdminError(refused); | |
| 171 | done = "lightSaved"; | |
| 172 | break; | |
| 173 | } | |
| 155 | 174 | case "tune-p": { |
| 156 | 175 | const [joint, p] = [form.get("joint") ?? "", form.get("p") ?? ""]; |
| 157 | 176 | if (!/^\d{1,3}$/.test(joint) || !/^\d{1,3}$/.test(p)) throw new AdminError("give a joint and a whole number for P"); |
Software/so101/src/cli.ts +1 −1
| @@ -534,7 +534,7 @@ const COMMANDS: Record<string, Command> = { | ||
| 534 | 534 | return withBus(values, async (bus) => { |
| 535 | 535 | const { startServer } = await import("./server.ts"); // lazily: it reaches bun:sqlite, which Node lacks |
| 536 | 536 | const cameraControl = (unit: number, profile: Parameters<typeof applyProfile>[1]) => applyProfile(cameraDevice(unit), profile); |
| 537 | const server = await startServer(bus, { host, port, posesFile: values.file ?? "poses.json", modelDir: values.model, gainSyncMs: 2000, cameraControl }); | |
| 537 | const server = await startServer(bus, { host, port, posesFile: values.file ?? "poses.json", modelDir: values.model, gainSyncMs: 2000, cameraControl, lightMs: 15_000 }); | |
| 538 | 538 | console.log(`serving ${bus.path} on http://${host}:${server.port} — open it in a browser; the API is listed in src/server.ts`); |
| 539 | 539 | console.log("ctrl-c to stop"); |
| 540 | 540 | await new Promise<void>((resolve) => process.once("SIGINT", () => resolve())); |
Software/so101/src/light-endpoint.test.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 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 { FeetechBus } from "./bus.ts"; | |
| 6 | import { FakeBus } from "./fake-bus.ts"; | |
| 7 | import { Light, type DeviceName } from "./light.ts"; | |
| 8 | import { lightRequest, lightSections } from "./light-panel.ts"; | |
| 9 | import { readGrow, readLight } from "./light-read.ts"; | |
| 10 | import type { Switch } from "./light-switch.ts"; | |
| 11 | import { startServer, type RunningServer } from "./server.ts"; | |
| 12 | import { esc } from "./admin-page.ts"; | |
| 13 | ||
| 14 | let server: RunningServer | undefined; | |
| 15 | afterEach(() => server?.close()); | |
| 16 | ||
| 17 | async function boot(lit: { on: boolean }) { | |
| 18 | const dir = mkdtempSync(join(tmpdir(), "so101-light-")); | |
| 19 | const fake: Switch = { on: async () => void (lit.on = true), off: async () => void (lit.on = false), state: async () => lit.on }; | |
| 20 | const make = (name: DeviceName) => new Light({ name, file: join(dir, `${name}.json`), zone: "UTC", now: () => Date.parse("2026-06-10T12:00:00Z"), make: () => fake }); | |
| 21 | server = await startServer(new FeetechBus(new FakeBus([1, 2])), { host: "127.0.0.1", port: 0, ids: [1, 2], posesFile: join(dir, "poses.json"), lights: { light: make("light"), pump: make("pump") } }); | |
| 22 | return `http://127.0.0.1:${server.port}`; | |
| 23 | } | |
| 24 | const post = (base: string, body: unknown, device = "light") => fetch(`${base}/grow/${device}`, { method: "POST", body: JSON.stringify(body) }); | |
| 25 | ||
| 26 | test("GET /light says always on until a switch is set; POST sets it, and refuses nonsense with a sentence", async () => { | |
| 27 | const lit = { on: false }; | |
| 28 | const base = await boot(lit); | |
| 29 | expect(((await (await fetch(`${base}/grow`)).json()) as { light: { text: string } }).light.text).toBe("Light: always on (no switch set up)"); | |
| 30 | const bad = await post(base, { schedule: { onAt: "25:00", hours: 12 } }); | |
| 31 | expect(bad.status).toBe(400); | |
| 32 | expect(((await bad.json()) as { error: string }).error).toMatch(/on at/); | |
| 33 | expect((await post(base, { nope: 1 })).status).toBe(400); | |
| 34 | const ok = await post(base, { switch: { driver: "shelly", host: "192.168.1.40" }, schedule: { onAt: "06:00", hours: 12 } }); | |
| 35 | expect(ok.status).toBe(200); | |
| 36 | expect(lit.on).toBe(true); | |
| 37 | expect(((await ok.json()) as { text: string }).text).toBe("On until 18:00"); | |
| 38 | const held = (await (await post(base, { override: "off" })).json()) as { text: string }; | |
| 39 | expect(held.text).toBe("Off until 18:00 (override)"); | |
| 40 | expect(lit.on).toBe(false); | |
| 41 | }); | |
| 42 | ||
| 43 | test("the card: text, strip, a link to setup when nothing is set, escaping, the long-day warning, and the pump beside the light", () => { | |
| 44 | const none = readLight({ configured: false, text: "Light: always on (no switch set up)", zone: "UTC", log: [] }, "light")!; | |
| 45 | const pump = readLight({ configured: true, driver: "gpio", text: "Off until 10:15", zone: "UTC", schedule: { onMinutes: 5, offMinutes: 25 }, log: [] }, "pump")!; | |
| 46 | expect(pump.schedule).toEqual({ onMinutes: 5, offMinutes: 25 }); | |
| 47 | expect(lightSections({ light: none, pump }, true, esc)).toContain("Set up a switch"); | |
| 48 | const view = readLight({ configured: true, driver: "shelly", text: "On until 22:00", zone: "UTC", schedule: { onAt: "06:00", hours: 16 }, log: [{ at: Date.parse("2026-06-10T06:00:00Z"), on: true, cause: "boot" }], error: "<b>x</b>" }, "light")!; | |
| 49 | const html = lightSections({ light: view, pump }, true, esc); | |
| 50 | expect(html).toContain("On until 22:00"); | |
| 51 | expect(html).toContain("Off until 10:15"); | |
| 52 | expect(html).toContain("5 min on, 25 min off"); | |
| 53 | expect(html).toContain("10/06, 06:00"); | |
| 54 | expect(html).toContain("boot"); | |
| 55 | expect(html).not.toContain("Dark period"); | |
| 56 | expect(lightSections({ light: { ...view, dark: true }, pump }, true, esc)).toContain("Dark period: keep room lights off"); | |
| 57 | expect(html).toContain("long for spinach"); | |
| 58 | expect(html).not.toContain("<b>x</b>"); | |
| 59 | expect(lightSections(null, true, esc)).toContain("did not answer"); | |
| 60 | expect(lightSections({ light: view, pump }, false, esc)).not.toContain("<form"); | |
| 61 | expect(readGrow({ light: { nope: 1 } })).toBeNull(); | |
| 62 | }); | |
| 63 | ||
| 64 | test("the card's forms become the device and the JSON the Pi takes", () => { | |
| 65 | const req = (q: string) => lightRequest(new URLSearchParams(q)); | |
| 66 | expect(req("action=light-schedule&device=light&kind=photoperiod&onAt=06:00&hours=12")).toEqual({ device: "light", body: { schedule: { onAt: "06:00", hours: 12 } } }); | |
| 67 | expect(req("action=light-schedule&device=pump&kind=cycle&onMinutes=5&offMinutes=25")).toEqual({ device: "pump", body: { schedule: { onMinutes: 5, offMinutes: 25 } } }); | |
| 68 | expect(req("action=light-schedule&device=pump&clear=1")).toEqual({ device: "pump", body: { schedule: null } }); | |
| 69 | expect(req("action=light-switch&device=pump&driver=uhubctl&hub=1-1&port=2&cameras=046d:0825, 1bcf:2c99")).toEqual({ device: "pump", body: { switch: { driver: "uhubctl", hub: "1-1", port: 2, cameras: ["046d:0825", "1bcf:2c99"] } } }); | |
| 70 | expect(req("action=light-override&device=light&value=on")).toEqual({ device: "light", body: { override: "on" } }); | |
| 71 | expect(req("action=light-override&device=toaster&value=on")).toBeNull(); | |
| 72 | expect(req("action=save")).toBeNull(); | |
| 73 | }); | |
| 74 | ||
| 75 | test("the pump runs on its own switch and an interval cycle, apart from the light", async () => { | |
| 76 | const lit = { on: false }; | |
| 77 | const base = await boot(lit); | |
| 78 | const put = await post(base, { switch: { driver: "gpio", line: 17 }, schedule: { onMinutes: 5, offMinutes: 25 } }, "pump"); | |
| 79 | expect(put.status).toBe(200); | |
| 80 | const grow = (await (await fetch(`${base}/grow`)).json()) as { light: { configured: boolean }; pump: { text: string } }; | |
| 81 | expect(grow.light.configured).toBe(false); | |
| 82 | expect(grow.pump.text).toBe("On until 12:05"); | |
| 83 | expect((await post(base, { schedule: { onMinutes: 0, offMinutes: 5 } }, "pump")).status).toBe(400); | |
| 84 | }); | |
| 85 | ||
| 86 | test("POST /grow/<device> caps the bytes it reads, whatever Content-Length says", async () => { | |
| 87 | const base = await boot({ on: false }); | |
| 88 | const chunk = new TextEncoder().encode(`{"x":"${"a".repeat(100_000)}`); | |
| 89 | let sent = 0; | |
| 90 | const body = new ReadableStream({ | |
| 91 | pull(controller) { | |
| 92 | if (sent++ < 15) controller.enqueue(chunk); // 1.5 MB with no Content-Length: chunked | |
| 93 | else controller.close(); | |
| 94 | }, | |
| 95 | }); | |
| 96 | const r = await fetch(`${base}/grow/light`, { method: "POST", body, duplex: "half" } as RequestInit).catch(() => null); | |
| 97 | if (r) expect(r.status).toBe(413); | |
| 98 | expect(((await (await fetch(`${base}/grow`)).json()) as { light: { configured: boolean } }).light.configured).toBe(false); | |
| 99 | }); |
Software/so101/src/light-panel.ts added +116
| @@ -0,0 +1,116 @@ | ||
| 1 | /** | |
| 2 | * The grow card on /admin, for the light (a daily photoperiod) and the pump (an interval cycle), each with its own switch and | |
| 3 | * schedule: what the device says now ("On until 22:00"), the strip of its last transitions, a manual | |
| 4 | * override, and the owner's forms for the schedule and the switch. Plain forms, no script; the arm server (the Pi) | |
| 5 | * checks every field, this only turns form text into the JSON it takes. Everything shown is escaped. | |
| 6 | */ | |
| 7 | import { DEVICES, type DeviceName, type LightView } from "./light.ts"; | |
| 8 | import { isCycle } from "./light-schedule.ts"; | |
| 9 | ||
| 10 | /** Spinach bolts on long days: modern lines at about 16 h, older ones at 14 h or more. */ | |
| 11 | export const SPINACH_MAX_HOURS = 14; | |
| 12 | export const DEFAULT_SCHEDULE = { onAt: "06:00", hours: 12 }; | |
| 13 | const DEFAULT_CYCLE = { onMinutes: 5, offMinutes: 25 }; | |
| 14 | const TITLE: Record<DeviceName, string> = { light: "Grow light", pump: "Pump" }; | |
| 15 | /** The switch form on this same card. */ | |
| 16 | const SETUP = "#light"; | |
| 17 | ||
| 18 | /** The device and the JSON the arm server's POST /grow/<device> takes, from one of the card's forms; null when the form is not one of them. */ | |
| 19 | export function lightRequest(form: URLSearchParams): { device: DeviceName; body: Record<string, unknown> } | null { | |
| 20 | const device = DEVICES.find((d) => d === form.get("device")); | |
| 21 | const body = device ? requestBody(form) : null; | |
| 22 | return device && body ? { device, body } : null; | |
| 23 | } | |
| 24 | ||
| 25 | function requestBody(form: URLSearchParams): Record<string, unknown> | null { | |
| 26 | const get = (k: string) => (form.get(k) ?? "").trim(); | |
| 27 | const num = (k: string) => (/^\d{1,4}$/.test(get(k)) ? Number(get(k)) : null); | |
| 28 | switch (form.get("action")) { | |
| 29 | case "light-schedule": | |
| 30 | if (form.get("clear")) return { schedule: null }; | |
| 31 | return { schedule: get("kind") === "cycle" ? { onMinutes: num("onMinutes"), offMinutes: num("offMinutes") } : { onAt: get("onAt"), hours: num("hours") } }; | |
| 32 | case "light-override": | |
| 33 | return { override: get("value") }; | |
| 34 | case "light-switch": | |
| 35 | switch (get("driver")) { | |
| 36 | case "none": | |
| 37 | return { switch: null }; | |
| 38 | case "shelly": | |
| 39 | return { switch: { driver: "shelly", host: get("host"), gen: get("gen") === "1" ? 1 : 2 } }; | |
| 40 | case "gpio": | |
| 41 | return { switch: { driver: "gpio", chip: get("chip") || "gpiochip0", line: num("line"), activeLow: form.get("activeLow") === "on" } }; | |
| 42 | case "uhubctl": | |
| 43 | return { switch: { driver: "uhubctl", hub: get("hub"), port: num("port"), cameras: get("cameras").split(/[\s,]+/).filter(Boolean) } }; | |
| 44 | default: | |
| 45 | return { switch: { driver: get("driver") } }; | |
| 46 | } | |
| 47 | default: | |
| 48 | return null; | |
| 49 | } | |
| 50 | } | |
| 51 | ||
| 52 | const stamp = (at: number, zone: string) => new Intl.DateTimeFormat("en-GB", { timeZone: zone, hourCycle: "h23", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(at)); | |
| 53 | ||
| 54 | const post = (device: DeviceName, action: string, extra: string, text: string, cls = "") => | |
| 55 | `<form method="post" action="/admin" class="inline"><input type="hidden" name="action" value="${action}"><input type="hidden" name="device" value="${device}">${extra}<button${cls ? ` class="${cls}"` : ""}>${text}</button></form>`; | |
| 56 | ||
| 57 | /** The grow card: the light, then the pump. null is the arm server not answering. */ | |
| 58 | export function lightSections(grow: { light: LightView; pump: LightView | null } | null, canEdit: boolean, esc: (s: string) => string): string { | |
| 59 | const head = `<section aria-labelledby="light"><h2 id="light">Grow</h2>`; | |
| 60 | if (!grow) return `${head}<p class="empty">The arm server did not answer, so the schedules cannot be read. They run on the Pi and do not need this page.</p></section>`; | |
| 61 | const pump = grow.pump ? deviceCard(grow.pump, canEdit, esc) : `<h3>Pump</h3><p class="empty">The arm server is older than the pump: it will appear after the Pi updates.</p>`; | |
| 62 | return `${head}${deviceCard(grow.light, canEdit, esc)}${pump}</section>`; | |
| 63 | } | |
| 64 | ||
| 65 | /** One driver's own form in a details element (open when it is the one in use), so a phone shows only the fields it needs and no script is wanted. */ | |
| 66 | function driverForm(device: DeviceName, driver: string, title: string, current: string, fields: string): string { | |
| 67 | return `<details${current === driver ? " open" : ""}><summary>${title}${current === driver ? " · in use" : ""}</summary><form method="post" action="/admin"><input type="hidden" name="action" value="light-switch"><input type="hidden" name="device" value="${device}"><input type="hidden" name="driver" value="${driver}">${fields}<div class="save"><button class="go">Use this switch</button></div></form></details>`; | |
| 68 | } | |
| 69 | ||
| 70 | function deviceCard(view: LightView, canEdit: boolean, esc: (s: string) => string): string { | |
| 71 | const d = view.name; | |
| 72 | const head = `<h3>${TITLE[d]}</h3>`; | |
| 73 | const text = view.configured ? esc(view.text) : `${esc(view.text)}. <a href="${SETUP}">Set up a switch</a>`; | |
| 74 | const strip = view.log.length | |
| 75 | ? `<ol class="strip" aria-label="Last ${d} transitions, oldest first">${view.log.slice(-12).map((e) => `<li class="${e.on ? "on" : "off"}"><time>${esc(stamp(e.at, view.zone))}</time> <b>${e.on ? "on" : "off"}</b> <small>${esc(e.cause)}</small></li>`).join("")}</ol>` | |
| 76 | : `<p class="empty">No transitions yet.</p>`; | |
| 77 | const err = view.error ? `<p class="flash bad" role="alert">The switch failed: ${esc(view.error)}. It is tried again every 15 seconds.</p>` : ""; | |
| 78 | const cycle = view.schedule && isCycle(view.schedule) ? view.schedule : null; | |
| 79 | const photo = view.schedule && !isCycle(view.schedule) ? view.schedule : null; | |
| 80 | const what = view.schedule ? `<p class="empty">${cycle ? `Every cycle: ${cycle.onMinutes} min on, ${cycle.offMinutes} min off.` : `Daily: on at ${esc(photo!.onAt)} for ${photo!.hours} h (${esc(view.zone)}).`}</p>` : ""; | |
| 81 | const long = d === "light" && photo && photo.hours > SPINACH_MAX_HOURS ? `<p class="flash bad" role="note">${photo.hours} hours is long for spinach: it bolts on long days (modern lines at about 16 h, older ones from 14 h). Keep it at ${DEFAULT_SCHEDULE.hours}–${SPINACH_MAX_HOURS} h for a leaf crop.</p>` : ""; | |
| 82 | const over = view.configured && canEdit | |
| 83 | ? `<div class="actions">${view.override ? post(d, "light-override", `<input type="hidden" name="value" value="clear">`, "Back to the schedule") : ""}${post(d, "light-override", `<input type="hidden" name="value" value="on">`, "On until the next change")}${post(d, "light-override", `<input type="hidden" name="value" value="off">`, "Off until the next change")}</div>` | |
| 84 | : ""; | |
| 85 | const dark = view.dark ? `<p class="flash bad" role="note"><b>Dark period: keep room lights off.</b> Spinach counts light in its dark hours as day, and that can push it to bolt.</p>` : ""; | |
| 86 | const body = `${head}<p><b>${text}</b></p>${dark}${what}${err}${long}${over}${strip}`; | |
| 87 | if (!canEdit) return body; | |
| 88 | const driver = view.driver ?? "none"; | |
| 89 | const opt = (v: string, t: string) => `<option value="${v}"${driver === v ? " selected" : ""}>${t}</option>`; | |
| 90 | const sched = photo ?? DEFAULT_SCHEDULE; | |
| 91 | const cyc = cycle ?? DEFAULT_CYCLE; | |
| 92 | const kind = cycle || d === "pump" ? "cycle" : "photoperiod"; | |
| 93 | const kopt = (v: string, t: string) => `<option value="${v}"${kind === v ? " selected" : ""}>${t}</option>`; | |
| 94 | const forms = `<form method="post" action="/admin"><input type="hidden" name="action" value="light-schedule"><input type="hidden" name="device" value="${d}"> | |
| 95 | <div class="grid"> | |
| 96 | <label>Schedule<small>a daily photoperiod, or an interval cycle</small><select name="kind">${kopt("photoperiod", "Daily: on at a time, for hours")}${kopt("cycle", "Cycle: minutes on, minutes off")}</select></label> | |
| 97 | <label>On at<small>photoperiod; ${esc(view.zone)}, the Pi's time zone</small><input name="onAt" type="time" value="${esc(sched.onAt)}"></label> | |
| 98 | <label>Hours on<small>photoperiod, 1–23${d === "light" ? `; spinach likes ${DEFAULT_SCHEDULE.hours}, no more than ${SPINACH_MAX_HOURS}` : ""}</small><input name="hours" type="number" inputmode="numeric" min="1" max="23" step="1" value="${sched.hours}"></label> | |
The pump card shows the photoperiod fields (On at, Hours on) alongside the cycle fields. All five inputs always show, so on a phone a person has to scroll past fields that do not apply. Next, hide the unused pair with a |
||
| 99 | <label>Minutes on<small>cycle, 1–1440</small><input name="onMinutes" type="number" inputmode="numeric" min="1" max="1440" step="1" value="${cyc.onMinutes}"></label> | |
| 100 | <label>Minutes off<small>cycle, 1–1440</small><input name="offMinutes" type="number" inputmode="numeric" min="1" max="1440" step="1" value="${cyc.offMinutes}"></label> | |
| 101 | </div> | |
| 102 | <div class="save"><button class="go">Save schedule</button>${view.schedule ? ` <button name="clear" value="1" formnovalidate>Remove schedule</button>` : ""}</div> | |
| 103 | </form> | |
| 104 | <h4>Switch: ${d === "pump" ? "the pump's" : "the light's"} (now ${esc(driver === "none" ? "none" : driver)})</h4> | |
| 105 | ${driverForm(d, "shelly", "Shelly plug (LAN)", driver, `<label>Plug address<small>its LAN address, like 192.168.1.40</small><input name="host" required maxlength="80" inputmode="url" autocapitalize="none" autocomplete="off" spellcheck="false" pattern="[A-Za-z0-9][A-Za-z0-9.\\-]*(:[0-9]{1,5})?" placeholder="192.168.1.40"></label> | |
| 106 | <label>Generation<small>2 for a Plus or Pro plug, 1 for an older one</small><select name="gen"><option value="2">2</option><option value="1">1</option></select></label>`)} | |
| 107 | ${driverForm(d, "gpio", "GPIO relay", driver, `<label>GPIO line<small>the pin's line number, 0–63</small><input name="line" type="number" required min="0" max="63" step="1" inputmode="numeric" placeholder="17"></label> | |
| 108 | <label>Chip<small>optional, default gpiochip0</small><input name="chip" maxlength="12" autocapitalize="none" autocomplete="off" pattern="gpiochip[0-9]{1,2}" placeholder="gpiochip0"></label> | |
| 109 | <label class="check"><input name="activeLow" type="checkbox"> Relay closes on 0 (active low)</label>`)} | |
| 110 | ${driverForm(d, "uhubctl", "USB port (uhubctl)", driver, `<p class="empty">Refused if a camera shares the port: a Pi 4 gangs its USB ports.</p> | |
| 111 | <label>USB hub<small>from <code>uhubctl</code>, like 1-1</small><input name="hub" required maxlength="20" autocapitalize="none" autocomplete="off" pattern="[0-9]+(-[0-9]+(\\.[0-9]+)*)?" placeholder="1-1"></label> | |
| 112 | <label>USB port<small>1–32</small><input name="port" type="number" required min="1" max="32" step="1" inputmode="numeric"></label> | |
| 113 | <label>Camera USB ids<small>optional, like 046d:0825, separated by commas; cameras are also found by name</small><input name="cameras" maxlength="200" autocapitalize="none" autocomplete="off" pattern="([0-9A-Fa-f]{4}:[0-9A-Fa-f]{4}[ ,]*)*" placeholder="046d:0825"></label>`)} | |
| 114 | <form method="post" action="/admin"><input type="hidden" name="action" value="light-switch"><input type="hidden" name="device" value="${d}"><input type="hidden" name="driver" value="none"><button${driver === "none" ? " disabled" : ""}>No switch</button></form>`; | |
| 115 | return `${body}${forms}`; | |
| 116 | } |
Software/so101/src/light-read.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** The arm server's GET /light, read field by field so a wrong answer shows as less, never as markup or a crash. */ | |
| 2 | import type { DeviceName, LightView, Transition } from "./light.ts"; | |
| 3 | ||
| 4 | const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}); | |
| 5 | const text = (v: unknown, max: number): string => (typeof v === "string" ? v.replace(/[\p{Cc}\p{Cf}]/gu, "").slice(0, max) : ""); | |
| 6 | ||
| 7 | /** GET /grow: the light and the pump; null when the light's answer is not one. */ | |
| 8 | export function readGrow(body: unknown): { light: LightView; pump: LightView | null } | null { | |
| 9 | const b = obj(body); | |
| 10 | const light = readLight(b.light, "light"); | |
| 11 | return light ? { light, pump: readLight(b.pump, "pump") } : null; | |
| 12 | } | |
| 13 | ||
| 14 | export function readLight(body: unknown, name: DeviceName): LightView | null { | |
| 15 | const b = obj(body); | |
| 16 | if (typeof b.configured !== "boolean" || typeof b.text !== "string") return null; | |
| 17 | const s = obj(b.schedule); | |
| 18 | const schedule = typeof s.onAt === "string" && /^\d\d:\d\d$/.test(s.onAt) && typeof s.hours === "number" ? { onAt: s.onAt, hours: s.hours } : typeof s.onMinutes === "number" && typeof s.offMinutes === "number" ? { onMinutes: s.onMinutes, offMinutes: s.offMinutes } : null; | |
| 19 | const o = obj(b.override); | |
| 20 | const log: Transition[] = (Array.isArray(b.log) ? b.log : []).slice(-48).flatMap((e: unknown) => { | |
| 21 | const t = obj(e); | |
| 22 | return typeof t.at === "number" && typeof t.on === "boolean" && (t.cause === "schedule" || t.cause === "override" || t.cause === "boot") ? [{ at: t.at, on: t.on, cause: t.cause }] : []; | |
| 23 | }); | |
| 24 | const zone = text(b.zone, 64); | |
| 25 | try { | |
| 26 | new Intl.DateTimeFormat("en-GB", { timeZone: zone }); | |
| 27 | } catch { | |
| 28 | return null; | |
| 29 | } | |
| 30 | return { | |
| 31 | name, | |
| 32 | configured: b.configured, | |
| 33 | driver: text(b.driver, 20) || null, | |
| 34 | schedule, | |
| 35 | zone, | |
| 36 | on: typeof b.on === "boolean" ? b.on : null, | |
| 37 | text: text(b.text, 100), | |
| 38 | override: typeof o.on === "boolean" && typeof o.until === "number" ? { on: o.on, until: o.until } : null, | |
| 39 | dark: b.dark === true, | |
| 40 | error: text(b.error, 300) || null, | |
| 41 | log, | |
| 42 | }; | |
| 43 | } |
Software/so101/src/light-schedule.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** | |
| 2 | * The photoperiod: on at a wall-clock time every day for a fixed number of hours, in one IANA time zone (the Pi's). | |
| 3 | * Pure: the state at an instant and the next change come from the schedule and the instant alone, so a reboot, a DST | |
| 4 | * change or a missed tick cannot make the light disagree with the clock. The window is `hours` of real time from | |
| 5 | * the local start, so on a DST day the light still gets its full photoperiod. | |
| 6 | */ | |
| 7 | ||
| 8 | /** A daily photoperiod: on at a wall-clock time for some hours (the grow light). */ | |
| 9 | export interface Photoperiod { | |
| 10 | /** "HH:MM", 24-hour, in the zone. */ | |
| 11 | onAt: string; | |
| 12 | /** Hours of light, 1 to 23. */ | |
| 13 | hours: number; | |
| 14 | } | |
| 15 | /** An interval cycle: on for N minutes, off for M, over and over from the Unix epoch, so any clock agrees (the pump). */ | |
| 16 | export interface Cycle { | |
| 17 | onMinutes: number; | |
| 18 | offMinutes: number; | |
| 19 | } | |
| 20 | export type Schedule = Photoperiod | Cycle; | |
| 21 | export const isCycle = (s: Schedule): s is Cycle => "onMinutes" in s; | |
| 22 | ||
| 23 | export interface Phase { | |
| 24 | on: boolean; | |
| 25 | /** The instant (ms) the state next flips. */ | |
| 26 | until: number; | |
| 27 | } | |
| 28 | ||
| 29 | export class ScheduleError extends Error {} | |
| 30 | ||
| 31 | const HOUR = 3_600_000; | |
| 32 | const DAY = 24 * HOUR; | |
| 33 | ||
| 34 | /** Check a schedule from outside; throws ScheduleError naming the field. */ | |
| 35 | export function parseSchedule(input: unknown): Schedule { | |
| 36 | if (typeof input !== "object" || input === null || Array.isArray(input)) throw new ScheduleError("a schedule is an object"); | |
| 37 | if ("onMinutes" in input || "offMinutes" in input) { | |
| 38 | const { onMinutes, offMinutes, ...other } = input as Record<string, unknown>; | |
| 39 | const stray = Object.keys(other)[0]; | |
| 40 | if (stray) throw new ScheduleError(`no schedule field "${stray.slice(0, 40)}"`); | |
| 41 | for (const [label, v] of [["minutes on", onMinutes], ["minutes off", offMinutes]] as const) | |
| 42 | if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 1440) throw new ScheduleError(`${label} is a whole number from 1 to 1440`); | |
| 43 | return { onMinutes: onMinutes as number, offMinutes: offMinutes as number }; | |
| 44 | } | |
| 45 | const { onAt, hours, ...rest } = input as Record<string, unknown>; | |
| 46 | const extra = Object.keys(rest)[0]; | |
| 47 | if (extra) throw new ScheduleError(`no schedule field "${extra.slice(0, 40)}"`); | |
| 48 | if (typeof onAt !== "string" || !/^([01]\d|2[0-3]):[0-5]\d$/.test(onAt)) throw new ScheduleError("on at is a time like 06:00"); | |
| 49 | if (typeof hours !== "number" || !Number.isInteger(hours) || hours < 1 || hours > 23) throw new ScheduleError("hours of light is a whole number from 1 to 23"); | |
| 50 | return { onAt, hours }; | |
| 51 | } | |
| 52 | ||
| 53 | /** The zone's offset from UTC at an instant, in ms. */ | |
| 54 | export function offsetAt(ms: number, zone: string): number { | |
| 55 | const p = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" }).formatToParts(new Date(ms)); | |
| 56 | const n = (t: string) => Number(p.find((x) => x.type === t)!.value); | |
| 57 | return Date.UTC(n("year"), n("month") - 1, n("day"), n("hour"), n("minute"), n("second")) - Math.floor(ms / 1000) * 1000; | |
| 58 | } | |
| 59 | ||
| 60 | /** The instant a wall-clock time on a calendar day happens in the zone. A time the clock skips (spring forward) lands just after the gap. */ | |
| 61 | export function wallToUtc(year: number, month: number, day: number, hour: number, minute: number, zone: string): number { | |
| 62 | const guess = Date.UTC(year, month - 1, day, hour, minute); | |
| 63 | const first = guess - offsetAt(guess, zone); | |
| 64 | const second = guess - offsetAt(first, zone); | |
| 65 | // Inside a skipped hour the two guesses disagree; the later one is just after the gap. | |
| 66 | return second + offsetAt(second, zone) === guess ? second : Math.max(first, second); | |
| 67 | } | |
| 68 | ||
| 69 | /** The zone's calendar date of an instant. */ | |
| 70 | function dateIn(ms: number, zone: string): [number, number, number] { | |
| 71 | const local = new Date(ms + offsetAt(ms, zone)); | |
| 72 | return [local.getUTCFullYear(), local.getUTCMonth() + 1, local.getUTCDate()]; | |
| 73 | } | |
| 74 | ||
| 75 | /** Every on-window that could touch `ms`: yesterday's, today's and tomorrow's, as [start, end) in order. */ | |
| 76 | function windows(s: Photoperiod, ms: number, zone: string): Array<[number, number]> { | |
| 77 | const [h, m] = s.onAt.split(":").map(Number) as [number, number]; | |
| 78 | const [y, mo, d] = dateIn(ms, zone); | |
| 79 | return [-1, 0, 1, 2].map((k) => { | |
| 80 | const day = new Date(Date.UTC(y, mo - 1, d + k)); | |
| 81 | const start = wallToUtc(day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), h, m, zone); | |
| 82 | return [start, start + s.hours * HOUR] as [number, number]; | |
| 83 | }); | |
| 84 | } | |
| 85 | ||
| 86 | /** Whether the light is on at `ms`, and when that next changes. */ | |
| 87 | export function phaseAt(s: Schedule, ms: number, zone: string): Phase { | |
| 88 | if (isCycle(s)) { | |
| 89 | const on = s.onMinutes * 60_000; | |
| 90 | const period = on + s.offMinutes * 60_000; | |
| 91 | const pos = ((ms % period) + period) % period; | |
| 92 | return pos < on ? { on: true, until: ms - pos + on } : { on: false, until: ms - pos + period }; | |
| 93 | } | |
| 94 | const all = windows(s, ms, zone); | |
| 95 | const inside = all.find(([a, b]) => a <= ms && ms < b); | |
| 96 | if (inside) return { on: true, until: inside[1] }; | |
| 97 | const next = all.find(([a]) => a > ms); | |
| 98 | return { on: false, until: next ? next[0] : ms + DAY }; | |
| 99 | } | |
| 100 | ||
| 101 | /** "HH:MM" of an instant in the zone. */ | |
| 102 | export function clockIn(ms: number, zone: string): string { | |
| 103 | return new Intl.DateTimeFormat("en-GB", { timeZone: zone, hourCycle: "h23", hour: "2-digit", minute: "2-digit" }).format(new Date(ms)); | |
| 104 | } |
Software/so101/src/light-switch.ts added +211
| @@ -0,0 +1,211 @@ | ||
| 1 | /** | |
| 2 | * The grow light's switch: one interface, `Switch { on(), off(), state() }`, and the drivers behind it. | |
| 3 | * shelly a Shelly smart plug on the LAN, local HTTP, no cloud account (Gen1 /relay/0, Gen2 /rpc/Switch.Set) | |
| 4 | * gpio a relay on a GPIO line, through libgpiod's gpioset/gpioget | |
| 5 | * uhubctl a USB port's power, only when the port switches alone: a Pi 4 gangs its ports, so cutting the light that way | |
| 6 | * would cut a camera with it, and the check refuses then | |
| 7 | * Tapo's local protocol is encrypted and wants an account login, so it is not here. | |
| 8 | * Everything that reaches a machine is injected (`Run`, `fetch`), so the tests use a fake Switch and fake commands. | |
| 9 | */ | |
| 10 | import { execFile } from "node:child_process"; | |
| 11 | ||
| 12 | export interface Switch { | |
| 13 | on(): Promise<void>; | |
| 14 | off(): Promise<void>; | |
| 15 | /** What the hardware says now. */ | |
| 16 | state(): Promise<boolean>; | |
| 17 | /** Setup check; throws SwitchError when this switch must not be used. */ | |
| 18 | verify?(): Promise<void>; | |
| 19 | } | |
| 20 | ||
| 21 | export class SwitchError extends Error {} | |
| 22 | ||
| 23 | export type DriverConfig = | |
| 24 | | { driver: "shelly"; host: string; gen: 1 | 2 } | |
| 25 | | { driver: "gpio"; chip: string; line: number; activeLow: boolean } | |
| 26 | | { driver: "uhubctl"; hub: string; port: number; cameras: string[] }; | |
| 27 | ||
| 28 | /** Runs a command; resolves with its exit code and output. */ | |
| 29 | export type Run = (cmd: string, args: readonly string[]) => Promise<{ code: number; out: string }>; | |
| 30 | ||
| 31 | export const run: Run = (cmd, args) => | |
| 32 | new Promise((resolve) => { | |
| 33 | execFile(cmd, [...args], { timeout: 10_000, maxBuffer: 1 << 20 }, (err, stdout, stderr) => { | |
| 34 | const code = err ? (typeof (err as { code?: unknown }).code === "number" ? (err as { code: number }).code : 127) : 0; | |
| 35 | resolve({ code, out: `${stdout}${stderr}` }); | |
| 36 | }); | |
| 37 | }); | |
| 38 | ||
| 39 | const HOST = /^(?:\d{1,3}(?:\.\d{1,3}){3}|[A-Za-z0-9](?:[A-Za-z0-9.-]{0,60}[A-Za-z0-9])?)(?::\d{1,5})?$/; | |
| 40 | const HUB = /^\d+(?:-\d+(?:\.\d+)*)?$/; | |
| 41 | const VIDPID = /^[0-9a-f]{4}:[0-9a-f]{4}$/; | |
| 42 | ||
| 43 | /** Check a driver config from outside; throws SwitchError naming the field. */ | |
| 44 | export function parseDriver(input: unknown): DriverConfig { | |
| 45 | if (typeof input !== "object" || input === null || Array.isArray(input)) throw new SwitchError("a switch is an object"); | |
| 46 | const c = input as Record<string, unknown>; | |
| 47 | const only = (...keys: string[]) => { | |
| 48 | const extra = Object.keys(c).find((k) => k !== "driver" && !keys.includes(k)); | |
| 49 | if (extra) throw new SwitchError(`no switch field "${extra.slice(0, 40)}"`); | |
| 50 | }; | |
| 51 | switch (c.driver) { | |
| 52 | case "shelly": { | |
| 53 | only("host", "gen"); | |
| 54 | if (typeof c.host !== "string" || !HOST.test(c.host)) throw new SwitchError("the plug's host is an address like 192.168.1.40"); | |
| 55 | const gen = c.gen ?? 2; | |
| 56 | if (gen !== 1 && gen !== 2) throw new SwitchError("the Shelly generation is 1 or 2"); | |
| 57 | return { driver: "shelly", host: c.host, gen }; | |
| 58 | } | |
| 59 | case "gpio": { | |
| 60 | only("chip", "line", "activeLow"); | |
| 61 | const chip = c.chip ?? "gpiochip0"; | |
| 62 | if (typeof chip !== "string" || !/^gpiochip\d{1,2}$/.test(chip)) throw new SwitchError("the chip is like gpiochip0"); | |
| 63 | if (typeof c.line !== "number" || !Number.isInteger(c.line) || c.line < 0 || c.line > 63) throw new SwitchError("the GPIO line is a whole number from 0 to 63"); | |
| 64 | if (c.activeLow !== undefined && typeof c.activeLow !== "boolean") throw new SwitchError("active low is true or false"); | |
| 65 | return { driver: "gpio", chip, line: c.line, activeLow: c.activeLow === true }; | |
| 66 | } | |
| 67 | case "uhubctl": { | |
| 68 | only("hub", "port", "cameras"); | |
| 69 | if (typeof c.hub !== "string" || !HUB.test(c.hub)) throw new SwitchError("the hub is a location like 1-1"); | |
| 70 | if (typeof c.port !== "number" || !Number.isInteger(c.port) || c.port < 1 || c.port > 32) throw new SwitchError("the port is a whole number from 1 to 32"); | |
| 71 | const cameras = c.cameras ?? []; | |
| 72 | if (!Array.isArray(cameras) || cameras.length > 16 || !cameras.every((x) => typeof x === "string" && VIDPID.test(x.toLowerCase()))) throw new SwitchError("cameras are USB ids like 046d:0825"); | |
| 73 | return { driver: "uhubctl", hub: c.hub, port: c.port, cameras: cameras.map((x: string) => x.toLowerCase()) }; | |
| 74 | } | |
| 75 | default: | |
| 76 | throw new SwitchError("the driver is shelly, gpio or uhubctl"); | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | export interface Deps { | |
| 81 | run?: Run; | |
| 82 | fetch?: typeof fetch; | |
| 83 | } | |
| 84 | ||
| 85 | export function makeSwitch(config: DriverConfig, deps: Deps = {}): Switch { | |
| 86 | switch (config.driver) { | |
| 87 | case "shelly": | |
| 88 | return new ShellySwitch(config, deps.fetch ?? fetch); | |
| 89 | case "gpio": | |
| 90 | return new GpioSwitch(config, deps.run ?? run); | |
| 91 | case "uhubctl": | |
| 92 | return new UhubctlSwitch(config, deps.run ?? run); | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | class ShellySwitch implements Switch { | |
| 97 | private readonly c: Extract<DriverConfig, { driver: "shelly" }>; | |
| 98 | private readonly get: typeof fetch; | |
| 99 | constructor(c: Extract<DriverConfig, { driver: "shelly" }>, get: typeof fetch) { | |
| 100 | this.c = c; | |
| 101 | this.get = get; | |
| 102 | } | |
| 103 | private async call(path: string): Promise<unknown> { | |
| 104 | try { | |
| 105 | const r = await this.get(`http://${this.c.host}${path}`, { signal: AbortSignal.timeout(4000), redirect: "error" }); | |
| 106 | if (!r.ok) throw new Error(`HTTP ${r.status}`); | |
| 107 | return await r.json(); | |
| 108 | } catch (err) { | |
| 109 | throw new SwitchError(`the Shelly plug at ${this.c.host} did not answer (${err instanceof Error ? err.message : String(err)})`); | |
| 110 | } | |
| 111 | } | |
| 112 | private set(on: boolean) { | |
| 113 | return this.c.gen === 1 ? this.call(`/relay/0?turn=${on ? "on" : "off"}`) : this.call(`/rpc/Switch.Set?id=0&on=${on}`); | |
| 114 | } | |
| 115 | async on() { await this.set(true); } | |
| 116 | async off() { await this.set(false); } | |
| 117 | async state() { | |
| 118 | const body = (await (this.c.gen === 1 ? this.call("/relay/0") : this.call("/rpc/Switch.GetStatus?id=0"))) as { ison?: unknown; output?: unknown }; | |
| 119 | const v = this.c.gen === 1 ? body.ison : body.output; | |
| 120 | if (typeof v !== "boolean") throw new SwitchError("the Shelly plug did not say whether it is on"); | |
| 121 | return v; | |
| 122 | } | |
| 123 | } | |
| 124 | ||
| 125 | class GpioSwitch implements Switch { | |
| 126 | private readonly c: Extract<DriverConfig, { driver: "gpio" }>; | |
| 127 | private readonly exec: Run; | |
| 128 | constructor(c: Extract<DriverConfig, { driver: "gpio" }>, exec: Run) { | |
| 129 | this.c = c; | |
| 130 | this.exec = exec; | |
| 131 | } | |
| 132 | private async set(on: boolean) { | |
| 133 | const level = on !== this.c.activeLow ? 1 : 0; | |
| 134 | const r = await this.exec("gpioset", ["-c", this.c.chip, "-t", "0", `${this.c.line}=${level}`]); | |
| 135 | if (r.code !== 0) throw new SwitchError(`gpioset failed: ${r.out.trim().slice(0, 200)}`); | |
| 136 | } | |
| 137 | async on() { await this.set(true); } | |
| 138 | async off() { await this.set(false); } | |
| 139 | async state() { | |
| 140 | const r = await this.exec("gpioget", ["-c", this.c.chip, String(this.c.line)]); | |
| 141 | if (r.code !== 0) throw new SwitchError(`gpioget failed: ${r.out.trim().slice(0, 200)}`); | |
| 142 | const high = /=\s*active|=\s*1|^1$/m.test(r.out.trim()); | |
| 143 | return high !== this.c.activeLow; | |
| 144 | } | |
| 145 | } | |
| 146 | ||
| 147 | export interface HubPort { | |
| 148 | port: number; | |
| 149 | /** "vid:pid" and the text after it, when a device is connected. */ | |
| 150 | device?: { id: string; name: string }; | |
| 151 | } | |
| 152 | export interface HubListing { | |
| 153 | /** Per-port power switching ("ppps"); false when the ports are ganged. */ | |
| 154 | perPort: boolean; | |
| 155 | ports: HubPort[]; | |
| 156 | } | |
| 157 | ||
| 158 | /** Read `uhubctl -l <hub>` output. */ | |
| 159 | export function parseHub(out: string): HubListing { | |
| 160 | const head = out.match(/^Current status for hub .*$/m)?.[0] ?? ""; | |
| 161 | const ports: HubPort[] = []; | |
| 162 | for (const m of out.matchAll(/^\s*Port (\d+): [0-9a-f]{4}\b(.*)$/gim)) { | |
| 163 | const dev = m[2]!.match(/\[([0-9a-f]{4}:[0-9a-f]{4})(?:\s+([^\]]*))?\]/i); | |
| 164 | ports.push({ port: Number(m[1]), ...(dev ? { device: { id: dev[1]!.toLowerCase(), name: (dev[2] ?? "").trim() } } : {}) }); | |
| 165 | } | |
| 166 | return { perPort: /\bppps\b/.test(head), ports }; | |
| 167 | } | |
| 168 | ||
| 169 | const CAMERA_WORDS = /cam|video|uvc|realsense/i; | |
| 170 | ||
| 171 | /** The devices that lose power when `port` is switched, and the cameras among them. */ | |
| 172 | export function dropped(hub: HubListing, port: number, cameraIds: readonly string[]): { devices: string[]; cameras: string[] } { | |
| 173 | // Ganged: every port on the hub switches together, so every other connected device drops. Per-port: only this one switches. | |
| 174 | const others = hub.perPort ? [] : hub.ports.filter((p) => p.port !== port && p.device); | |
| 175 | const devices = others.map((p) => `port ${p.port}: ${p.device!.id} ${p.device!.name}`.trim()); | |
| 176 | const cameras = others.filter((p) => cameraIds.includes(p.device!.id) || CAMERA_WORDS.test(p.device!.name)).map((p) => `port ${p.port}: ${p.device!.id} ${p.device!.name}`.trim()); | |
| 177 | return { devices, cameras }; | |
| 178 | } | |
| 179 | ||
| 180 | class UhubctlSwitch implements Switch { | |
| 181 | private readonly c: Extract<DriverConfig, { driver: "uhubctl" }>; | |
| 182 | private readonly exec: Run; | |
| 183 | constructor(c: Extract<DriverConfig, { driver: "uhubctl" }>, exec: Run) { | |
| 184 | this.c = c; | |
| 185 | this.exec = exec; | |
| 186 | } | |
| 187 | private async list(): Promise<HubListing> { | |
| 188 | const r = await this.exec("uhubctl", ["-l", this.c.hub]); | |
| 189 | if (r.code !== 0) throw new SwitchError(`uhubctl -l ${this.c.hub} failed: ${r.out.trim().slice(0, 200)}`); | |
| 190 | const hub = parseHub(r.out); | |
| 191 | if (!hub.ports.some((p) => p.port === this.c.port)) throw new SwitchError(`hub ${this.c.hub} has no port ${this.c.port}`); | |
| 192 | return hub; | |
| 193 | } | |
| 194 | async verify() { | |
| 195 | const hit = dropped(await this.list(), this.c.port, this.c.cameras); | |
| 196 | if (hit.cameras.length) throw new SwitchError(`switching port ${this.c.port} of hub ${this.c.hub} would also cut a camera (${hit.cameras.join("; ")}): a Pi 4 cannot switch one USB port alone. Use a smart plug or a relay`); | |
| 197 | } | |
| 198 | private async set(on: boolean) { | |
| 199 | await this.verify(); // every time: a camera plugged in later must not be cut by the next transition | |
| 200 | const r = await this.exec("uhubctl", ["-l", this.c.hub, "-p", String(this.c.port), "-a", on ? "on" : "off"]); | |
| 201 | if (r.code !== 0) throw new SwitchError(`uhubctl failed: ${r.out.trim().slice(0, 200)}`); | |
| 202 | } | |
| 203 | async on() { await this.set(true); } | |
| 204 | async off() { await this.set(false); } | |
| 205 | async state() { | |
| 206 | await this.list(); | |
| 207 | const line = (await this.exec("uhubctl", ["-l", this.c.hub, "-p", String(this.c.port)])).out.match(new RegExp(`^\\s*Port ${this.c.port}: [0-9a-f]{4} (.*)$`, "im")); | |
| 208 | if (!line) throw new SwitchError("uhubctl did not say the port's state"); | |
| 209 | return /\bpower\b/.test(line[1]!); | |
| 210 | } | |
| 211 | } |
Software/so101/src/light.test.ts added +279
| @@ -0,0 +1,279 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, readFileSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { Light, LightError } from "./light.ts"; | |
| 6 | import { clockIn, parseSchedule, phaseAt, wallToUtc, type Schedule } from "./light-schedule.ts"; | |
| 7 | import { makeSwitch, parseDriver, parseHub, SwitchError, type Run, type Switch } from "./light-switch.ts"; | |
| 8 | ||
| 9 | const NY = "America/New_York"; | |
| 10 | const at = (iso: string) => Date.parse(iso); | |
| 11 | const s16: Schedule = { onAt: "06:00", hours: 16 }; | |
| 12 | ||
| 13 | describe("schedule math", () => { | |
| 14 | test("a day: on at 06:00 for 16 h", () => { | |
| 15 | expect(phaseAt(s16, at("2026-06-10T12:00:00Z"), "UTC")).toEqual({ on: true, until: at("2026-06-10T22:00:00Z") }); | |
| 16 | expect(phaseAt(s16, at("2026-06-10T23:00:00Z"), "UTC")).toEqual({ on: false, until: at("2026-06-11T06:00:00Z") }); | |
| 17 | expect(phaseAt(s16, at("2026-06-10T03:00:00Z"), "UTC")).toEqual({ on: false, until: at("2026-06-10T06:00:00Z") }); | |
| 18 | }); | |
| 19 | test("a window across midnight", () => { | |
| 20 | const s = { onAt: "20:00", hours: 8 }; | |
| 21 | expect(phaseAt(s, at("2026-06-10T23:30:00Z"), "UTC")).toEqual({ on: true, until: at("2026-06-11T04:00:00Z") }); | |
| 22 | expect(phaseAt(s, at("2026-06-11T01:00:00Z"), "UTC")).toEqual({ on: true, until: at("2026-06-11T04:00:00Z") }); | |
| 23 | expect(phaseAt(s, at("2026-06-11T05:00:00Z"), "UTC")).toEqual({ on: false, until: at("2026-06-11T20:00:00Z") }); | |
| 24 | }); | |
| 25 | test("spring forward keeps the local start and the full 16 hours", () => { | |
| 26 | // 2026-03-08: New York jumps 02:00 -> 03:00. Start 06:00 EDT = 10:00Z; yesterday's 06:00 EST = 11:00Z. | |
| 27 | expect(wallToUtc(2026, 3, 8, 6, 0, NY)).toBe(at("2026-03-08T10:00:00Z")); | |
| 28 | expect(wallToUtc(2026, 3, 7, 6, 0, NY)).toBe(at("2026-03-07T11:00:00Z")); | |
| 29 | expect(phaseAt(s16, at("2026-03-08T09:59:00Z"), NY).on).toBe(false); | |
| 30 | expect(phaseAt(s16, at("2026-03-08T10:00:00Z"), NY)).toEqual({ on: true, until: at("2026-03-09T02:00:00Z") }); | |
| 31 | expect(clockIn(at("2026-03-09T02:00:00Z"), NY)).toBe("22:00"); | |
| 32 | }); | |
| 33 | test("fall back", () => { | |
| 34 | // 2026-11-01: 06:00 is EST (11:00Z); the night is 25 h, the light still gets 16. | |
| 35 | expect(phaseAt(s16, at("2026-11-01T10:59:00Z"), NY)).toEqual({ on: false, until: at("2026-11-01T11:00:00Z") }); | |
| 36 | expect(phaseAt(s16, at("2026-11-01T12:00:00Z"), NY)).toEqual({ on: true, until: at("2026-11-02T03:00:00Z") }); | |
| 37 | }); | |
| 38 | test("a start time the clock skips lands after the gap", () => { | |
| 39 | expect(wallToUtc(2026, 3, 8, 2, 30, NY)).toBe(at("2026-03-08T07:30:00Z")); // 03:30 EDT | |
| 40 | }); | |
| 41 | test("a cycle: N minutes on, M off, aligned to the epoch, the same on any clock", () => { | |
| 42 | const c = { onMinutes: 5, offMinutes: 25 }; | |
| 43 | expect(phaseAt(c, at("2026-06-10T12:02:00Z"), NY)).toEqual({ on: true, until: at("2026-06-10T12:05:00Z") }); | |
| 44 | expect(phaseAt(c, at("2026-06-10T12:05:00Z"), NY)).toEqual({ on: false, until: at("2026-06-10T12:30:00Z") }); | |
| 45 | expect(phaseAt(c, at("2026-06-10T12:29:59Z"), "UTC").until).toBe(at("2026-06-10T12:30:00Z")); | |
| 46 | expect(phaseAt(c, at("2026-03-08T07:02:00Z"), NY).on).toBe(true); // DST changes nothing for a cycle | |
| 47 | }); | |
| 48 | test("validation", () => { | |
| 49 | expect(() => parseSchedule({ onMinutes: 0, offMinutes: 5 })).toThrow(); | |
| 50 | expect(() => parseSchedule({ onMinutes: 5 })).toThrow(); | |
| 51 | expect(() => parseSchedule({ onMinutes: 5, offMinutes: 5, onAt: "06:00" })).toThrow(); | |
| 52 | expect(parseSchedule({ onMinutes: 5, offMinutes: 25 })).toEqual({ onMinutes: 5, offMinutes: 25 }); | |
| 53 | expect(() => parseSchedule({ onAt: "6:00", hours: 16 })).toThrow(); | |
| 54 | expect(() => parseSchedule({ onAt: "06:00", hours: 24 })).toThrow(); | |
| 55 | expect(() => parseSchedule({ onAt: "06:00", hours: 16, x: 1 })).toThrow(); | |
| 56 | expect(parseSchedule({ onAt: "06:00", hours: 12 })).toEqual({ onAt: "06:00", hours: 12 }); | |
| 57 | }); | |
| 58 | }); | |
| 59 | ||
| 60 | class Fake implements Switch { | |
| 61 | lit = false; | |
| 62 | calls: string[] = []; | |
| 63 | fail = false; | |
| 64 | async on() { if (this.fail) throw new SwitchError("unplugged"); this.lit = true; this.calls.push("on"); } | |
| 65 | async off() { if (this.fail) throw new SwitchError("unplugged"); this.lit = false; this.calls.push("off"); } | |
| 66 | async state() { return this.lit; } | |
| 67 | } | |
| 68 | ||
| 69 | function rig(zone = "UTC", start = "2026-06-10T12:00:00Z") { | |
| 70 | const dir = mkdtempSync(join(tmpdir(), "light-")); | |
| 71 | const file = join(dir, "light.json"); | |
| 72 | const clock = { t: at(start) }; | |
| 73 | const fake = new Fake(); | |
| 74 | const make = () => new Light({ file, zone, now: () => clock.t, make: () => fake }); | |
| 75 | return { dir, file, clock, fake, make }; | |
| 76 | } | |
| 77 | const shelly = { driver: "shelly", host: "192.168.1.40" }; | |
| 78 | ||
| 79 | describe("light controller", () => { | |
| 80 | test("with no switch the card says always on and nothing is touched", () => { | |
| 81 | const { make } = rig(); | |
| 82 | expect(make().view().text).toBe("Light: always on (no switch set up)"); | |
| 83 | }); | |
| 84 | test("shows On until / Off until, and transitions are logged with their cause", async () => { | |
| 85 | const { make, clock, fake } = rig(); | |
| 86 | const light = make(); | |
| 87 | await light.configure({ switch: shelly, schedule: s16 }); | |
| 88 | expect(fake.lit).toBe(true); | |
| 89 | expect(light.view().text).toBe("On until 22:00"); | |
| 90 | expect(light.view().dark).toBe(false); | |
| 91 | clock.t = at("2026-06-10T22:00:00Z"); | |
| 92 | await light.tick(); | |
| 93 | expect(fake.lit).toBe(false); | |
| 94 | expect(light.view().text).toBe("Off until 06:00"); | |
| 95 | expect(light.view().dark).toBe(true); | |
| 96 | await light.tick(); // no change, no second command | |
| 97 | expect(fake.calls).toEqual(["on", "off"]); | |
| 98 | expect(light.view().log.map((e) => [e.on, e.cause])).toEqual([[true, "schedule"], [false, "schedule"]]); | |
| 99 | }); | |
| 100 | test("reboot catch-up: boot sets the state the schedule says now and logs it", async () => { | |
| 101 | const { make, clock, fake, file } = rig(); | |
| 102 | const first = make(); | |
| 103 | await first.configure({ switch: shelly, schedule: s16 }); | |
| 104 | clock.t = at("2026-06-11T01:00:00Z"); // the Pi was off over the 22:00 change; the plug lost its state | |
| 105 | fake.lit = true; | |
| 106 | const second = make(); | |
| 107 | await second.boot(); | |
| 108 | expect(fake.lit).toBe(false); | |
| 109 | expect(second.view().log.at(-1)).toEqual({ at: clock.t, on: false, cause: "boot" }); | |
| 110 | expect(JSON.parse(readFileSync(file, "utf8")).schedule).toEqual(s16); | |
| 111 | expect(readFileSync(file.replace(".json", ".log.jsonl"), "utf8")).toContain('"cause":"boot"'); | |
| 112 | }); | |
| 113 | test("an override holds until the next transition, then the schedule resumes", async () => { | |
| 114 | const { make, clock, fake } = rig(); | |
| 115 | const light = make(); | |
| 116 | await light.configure({ switch: shelly, schedule: s16 }); | |
| 117 | await light.override("off"); | |
| 118 | expect(fake.lit).toBe(false); | |
| 119 | expect(light.view().text).toBe("Off until 22:00 (override)"); | |
| 120 | clock.t = at("2026-06-10T21:59:00Z"); | |
| 121 | await light.tick(); | |
| 122 | expect(fake.lit).toBe(false); | |
| 123 | clock.t = at("2026-06-10T22:00:00Z"); // the override ends; the schedule says off too: no change | |
| 124 | await light.tick(); | |
| 125 | expect(light.view().override).toBeNull(); | |
| 126 | clock.t = at("2026-06-11T06:00:00Z"); | |
| 127 | await light.tick(); | |
| 128 | expect(fake.lit).toBe(true); | |
| 129 | expect(light.view().log.map((e) => e.cause)).toEqual(["schedule", "override", "schedule"]); | |
| 130 | }); | |
| 131 | test("an override survives a reboot; clearing gives it back", async () => { | |
| 132 | const { make, fake } = rig(); | |
| 133 | const a = make(); | |
| 134 | await a.configure({ switch: shelly, schedule: s16 }); | |
| 135 | await a.override("off"); | |
| 136 | const b = make(); | |
| 137 | await b.boot(); | |
| 138 | expect(fake.lit).toBe(false); | |
| 139 | await b.override("clear"); | |
| 140 | expect(fake.lit).toBe(true); | |
| 141 | }); | |
| 142 | test("a switch that fails is retried on the next tick and the error is shown", async () => { | |
| 143 | const { make, clock, fake } = rig(); | |
| 144 | const light = make(); | |
| 145 | await light.configure({ switch: shelly, schedule: s16 }); | |
| 146 | fake.fail = true; | |
| 147 | clock.t = at("2026-06-10T22:00:00Z"); | |
| 148 | await light.tick(); | |
| 149 | expect(light.view().error).toContain("unplugged"); | |
| 150 | fake.fail = false; | |
| 151 | await light.tick(); | |
| 152 | expect(fake.lit).toBe(false); | |
| 153 | expect(light.view().error).toBeNull(); | |
| 154 | }); | |
| 155 | test("bad input is refused and nothing changes", async () => { | |
| 156 | const { make } = rig(); | |
| 157 | const light = make(); | |
| 158 | await expect(light.configure({ schedule: { onAt: "99:00", hours: 3 } })).rejects.toBeInstanceOf(LightError); | |
| 159 | await expect(light.override("on")).rejects.toBeInstanceOf(LightError); // no switch yet | |
| 160 | await expect(light.configure({ switch: { driver: "tapo" } })).rejects.toBeInstanceOf(LightError); | |
| 161 | }); | |
| 162 | }); | |
| 163 | ||
| 164 | describe("pump controller (an interval cycle)", () => { | |
| 165 | const cycle = { onMinutes: 5, offMinutes: 25 }; | |
| 166 | function pumpRig(start = "2026-06-10T12:02:00Z") { | |
| 167 | const r = rig("UTC", start); | |
| 168 | const file = join(r.dir, "pump.json"); | |
| 169 | return { ...r, file, make: () => new Light({ name: "pump", file, zone: "UTC", now: () => r.clock.t, make: () => r.fake }) }; | |
| 170 | } | |
| 171 | test("with no switch the pump says it is not run, and its card never warns of a dark period", async () => { | |
| 172 | const { make, clock, fake } = pumpRig(); | |
| 173 | expect(make().view().text).toBe("Pump: not run (no switch set up)"); | |
| 174 | const pump = make(); | |
| 175 | await pump.configure({ switch: shelly, schedule: cycle }); | |
| 176 | expect(pump.view().text).toBe("On until 12:05"); | |
| 177 | await pump.tick(); | |
| 178 | expect(fake.calls).toEqual(["on"]); | |
| 179 | clock.t = at("2026-06-10T12:06:00Z"); | |
| 180 | await pump.tick(); | |
| 181 | expect(fake.lit).toBe(false); | |
| 182 | expect(pump.view().dark).toBe(false); // off, but the dark period is the light's alone | |
| 183 | }); | |
| 184 | test("reboot catch-up: boot sets the state the cycle says now, in its own pump.json and pump.log.jsonl", async () => { | |
| 185 | const { make, clock, fake, file } = pumpRig(); | |
| 186 | await make().configure({ switch: shelly, schedule: cycle }); | |
| 187 | expect(fake.lit).toBe(true); | |
| 188 | clock.t = at("2026-06-10T13:11:00Z"); // off since 13:05: the Pi slept through four changes | |
| 189 | const again = make(); | |
| 190 | await again.boot(); | |
| 191 | expect(fake.lit).toBe(false); | |
| 192 | expect(again.view().text).toBe("Off until 13:30"); | |
| 193 | expect(again.view().log.at(-1)).toEqual({ at: clock.t, on: false, cause: "boot" }); | |
| 194 | expect(JSON.parse(readFileSync(file, "utf8")).schedule).toEqual(cycle); | |
| 195 | expect(readFileSync(file.replace(".json", ".log.jsonl"), "utf8")).toContain('"cause":"boot"'); | |
| 196 | }); | |
| 197 | test("an override holds until the cycle's next change, then the cycle resumes", async () => { | |
| 198 | const { make, clock, fake } = pumpRig(); | |
| 199 | const pump = make(); | |
| 200 | await pump.configure({ switch: shelly, schedule: cycle }); | |
| 201 | await pump.override("off"); | |
| 202 | expect(pump.view().text).toBe("Off until 12:05 (override)"); | |
| 203 | clock.t = at("2026-06-10T12:04:59Z"); | |
| 204 | await pump.tick(); | |
| 205 | expect(fake.lit).toBe(false); | |
| 206 | clock.t = at("2026-06-10T12:05:00Z"); // the override ends where the cycle turns off anyway | |
| 207 | await pump.tick(); | |
| 208 | expect(pump.view().override).toBeNull(); | |
| 209 | expect(pump.view().text).toBe("Off until 12:30"); | |
| 210 | clock.t = at("2026-06-10T12:30:00Z"); | |
| 211 | await pump.tick(); | |
| 212 | expect(fake.lit).toBe(true); | |
| 213 | expect(pump.view().log.map((e) => e.cause)).toEqual(["schedule", "override", "schedule"]); | |
| 214 | }); | |
| 215 | }); | |
| 216 | ||
| 217 | const GANGED = `Current status for hub 1-1 [2109:3431 VIA Labs, Inc. USB2.0 Hub, USB 2.10, 4 ports, ganged] | |
| 218 | Port 1: 0503 power highspeed enable connect [046d:0825 Logitech Webcam C270 CAM1] | |
| 219 | Port 2: 0100 power | |
| 220 | Port 3: 0503 power highspeed enable connect [1bcf:2c99 USB Camera] | |
| 221 | Port 4: 0100 power | |
| 222 | `; | |
| 223 | const PPPS = GANGED.replace("ganged", "ppps"); | |
| 224 | ||
| 225 | function fakeRun(listing: string): { run: Run; calls: string[][] } { | |
| 226 | const calls: string[][] = []; | |
| 227 | return { calls, run: async (_cmd, args) => (calls.push([...args]), { code: 0, out: listing }) }; | |
| 228 | } | |
| 229 | const uhub = { driver: "uhubctl", hub: "1-1", port: 2, cameras: [] }; | |
| 230 | ||
| 231 | describe("drivers", () => { | |
| 232 | test("uhubctl refuses when a camera shares the switch, and never sends the switch command", async () => { | |
| 233 | const { run, calls } = fakeRun(GANGED); | |
| 234 | const sw = makeSwitch(parseDriver(uhub), { run }); | |
| 235 | await expect(sw.verify!()).rejects.toThrow(/would also cut a camera/); | |
| 236 | await expect(sw.on()).rejects.toBeInstanceOf(SwitchError); | |
| 237 | expect(calls.some((a) => a.includes("-a"))).toBe(false); | |
| 238 | }); | |
| 239 | test("uhubctl refuses on a camera named by its USB id even when its name says nothing", async () => { | |
| 240 | const listing = GANGED.replace("Logitech Webcam C270 CAM1", "Acme 7").replace("USB Camera", "Thing"); | |
| 241 | const sw = makeSwitch(parseDriver({ ...uhub, cameras: ["046D:0825"] }), { run: fakeRun(listing).run }); | |
| 242 | await expect(sw.verify!()).rejects.toThrow(/046d:0825/); | |
| 243 | }); | |
| 244 | test("uhubctl switches a port that switches alone", async () => { | |
| 245 | const { run, calls } = fakeRun(PPPS); | |
| 246 | const sw = makeSwitch(parseDriver(uhub), { run }); | |
| 247 | await sw.verify!(); | |
| 248 | await sw.off(); | |
| 249 | expect(calls.at(-1)).toEqual(["-l", "1-1", "-p", "2", "-a", "off"]); | |
| 250 | expect(await sw.state()).toBe(true); | |
| 251 | }); | |
| 252 | test("configure() keeps the old switch when the new uhubctl one is refused", async () => { | |
| 253 | const dir = mkdtempSync(join(tmpdir(), "light-")); | |
| 254 | const light = new Light({ file: join(dir, "l.json"), zone: "UTC", deps: { run: fakeRun(GANGED).run } }); | |
| 255 | await expect(light.configure({ switch: uhub })).rejects.toThrow(/camera/); | |
| 256 | expect(light.view().configured).toBe(false); | |
| 257 | }); | |
| 258 | test("parseHub", () => { | |
| 259 | const h = parseHub(GANGED); | |
| 260 | expect(h.perPort).toBe(false); | |
| 261 | expect(h.ports.map((p) => p.device?.id)).toEqual(["046d:0825", undefined, "1bcf:2c99", undefined]); | |
| 262 | }); | |
| 263 | test("shelly gen2 and gen1 urls; gpio commands", async () => { | |
| 264 | const urls: string[] = []; | |
| 265 | const get = (async (url: string) => (urls.push(url), new Response(JSON.stringify({ output: true, ison: true })))) as unknown as typeof fetch; | |
| 266 | await makeSwitch(parseDriver(shelly), { fetch: get }).on(); | |
| 267 | await makeSwitch(parseDriver({ ...shelly, gen: 1 }), { fetch: get }).off(); | |
| 268 | expect(urls).toEqual(["http://192.168.1.40/rpc/Switch.Set?id=0&on=true", "http://192.168.1.40/relay/0?turn=off"]); | |
| 269 | expect(await makeSwitch(parseDriver(shelly), { fetch: get }).state()).toBe(true); | |
| 270 | const g = fakeRun(""); | |
| 271 | await makeSwitch(parseDriver({ driver: "gpio", line: 17, activeLow: true }), { run: g.run }).on(); | |
| 272 | expect(g.calls[0]).toEqual(["-c", "gpiochip0", "-t", "0", "17=0"]); | |
| 273 | }); | |
| 274 | test("driver validation", () => { | |
| 275 | expect(() => parseDriver({ driver: "shelly", host: "a b" })).toThrow(); | |
| 276 | expect(() => parseDriver({ driver: "gpio", line: 99 })).toThrow(); | |
| 277 | expect(() => parseDriver({ driver: "uhubctl", hub: "1-1; rm", port: 1 })).toThrow(); | |
| 278 | }); | |
| 279 | }); |
Software/so101/src/light.ts added +229
| @@ -0,0 +1,229 @@ | ||
| 1 | /** | |
| 2 | * The grow light (or the pump): a schedule driving a Switch, run by the arm server on the Pi so it never depends on the | |
| 3 | * forge or the network. `tick()` sets the state the schedule (or an override) says now, and logs a transition | |
| 4 | * (time, state, cause) only when the state changes; `boot()` sets it once on start-up, whatever it was before, so a | |
| 5 | * reboot or a power cut catches up. An override holds until the next schedule transition, then the schedule resumes. | |
| 6 | * Settings and the log are kept beside the arm's other data. | |
| 7 | */ | |
| 8 | import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 9 | import { dirname } from "node:path"; | |
| 10 | import { clockIn, isCycle, parseSchedule, phaseAt, ScheduleError, type Schedule } from "./light-schedule.ts"; | |
| 11 | import { makeSwitch, parseDriver, SwitchError, type Deps, type DriverConfig, type Switch } from "./light-switch.ts"; | |
| 12 | ||
| 13 | /** What a switch runs: the grow light on a photoperiod, the pump on an interval cycle. Each has its own switch and its own schedule. */ | |
| 14 | export type DeviceName = "light" | "pump"; | |
| 15 | export const DEVICES: readonly DeviceName[] = ["light", "pump"]; | |
| 16 | ||
| 17 | export type Cause = "schedule" | "override" | "boot"; | |
| 18 | export interface Transition { | |
| 19 | at: number; | |
| 20 | on: boolean; | |
| 21 | cause: Cause; | |
| 22 | } | |
| 23 | interface Stored { | |
| 24 | schedule: Schedule | null; | |
| 25 | driver: DriverConfig | null; | |
| 26 | override: { on: boolean; until: number } | null; | |
| 27 | /** The last state we set, so a tick only acts on a change. */ | |
| 28 | applied: boolean | null; | |
| 29 | } | |
| 30 | ||
| 31 | export interface LightView { | |
| 32 | name: DeviceName; | |
| 33 | /** A switch is set up: without one the light is simply always on. */ | |
| 34 | configured: boolean; | |
| 35 | driver: string | null; | |
| 36 | schedule: Schedule | null; | |
| 37 | zone: string; | |
| 38 | on: boolean | null; | |
| 39 | /** "On until 22:00", "Off until 06:00", or why there is nothing to say. */ | |
| 40 | text: string; | |
| 41 | override: { on: boolean; until: number } | null; | |
| 42 | /** The photoperiod is in its off hours: the card tells people to keep room lights off. */ | |
| 43 | dark: boolean; | |
| 44 | error: string | null; | |
| 45 | log: Transition[]; | |
| 46 | } | |
| 47 | ||
| 48 | export class LightError extends Error {} | |
| 49 | ||
| 50 | const KEEP = 48; | |
| 51 | ||
| 52 | export interface LightOptions { | |
| 53 | name?: DeviceName; | |
| 54 | file: string; | |
| 55 | zone?: string; | |
| 56 | now?: () => number; | |
| 57 | /** Builds the Switch for a config; tests give a fake. */ | |
| 58 | make?: (config: DriverConfig) => Switch; | |
| 59 | deps?: Deps; | |
| 60 | } | |
| 61 | ||
| 62 | export class Light { | |
| 63 | private s: Stored = { schedule: null, driver: null, override: null, applied: null }; | |
| 64 | private sw: Switch | null = null; | |
| 65 | private error: string | null = null; | |
| 66 | private log: Transition[] = []; | |
| 67 | private busy: Promise<void> = Promise.resolve(); | |
| 68 | readonly zone: string; | |
| 69 | readonly name: DeviceName; | |
| 70 | private readonly now: () => number; | |
| 71 | private readonly logFile: string; | |
| 72 | private readonly make: (config: DriverConfig) => Switch; | |
| 73 | ||
| 74 | private readonly o: LightOptions; | |
| 75 | ||
| 76 | constructor(o: LightOptions) { | |
| 77 | this.o = o; | |
| 78 | this.name = o.name ?? "light"; | |
| 79 | this.zone = o.zone ?? Intl.DateTimeFormat().resolvedOptions().timeZone; | |
| 80 | this.now = o.now ?? Date.now; | |
| 81 | this.logFile = o.file.replace(/(\.json)?$/, ".log.jsonl"); | |
| 82 | this.make = o.make ?? ((c) => makeSwitch(c, o.deps)); | |
| 83 | this.load(); | |
| 84 | if (this.s.driver) this.sw = this.make(this.s.driver); | |
| 85 | } | |
| 86 | ||
| 87 | /** What the schedule (or a live override) wants now. Null: nothing is set up, the light is left alone. */ | |
| 88 | private want(): { on: boolean; cause: Cause } | null { | |
| 89 | const t = this.now(); | |
| 90 | if (this.s.override && t < this.s.override.until) return { on: this.s.override.on, cause: "override" }; | |
| 91 | if (!this.s.schedule) return null; | |
| 92 | return { on: phaseAt(this.s.schedule, t, this.zone).on, cause: "schedule" }; | |
| 93 | } | |
| 94 | ||
| 95 | /** Run one thing at a time against the hardware. */ | |
| 96 | private serial<T>(job: () => Promise<T>): Promise<T> { | |
| 97 | const next = this.busy.then(job, job); | |
| 98 | this.busy = next.then(() => undefined, () => undefined); | |
| 99 | return next; | |
| 100 | } | |
| 101 | ||
| 102 | private async apply(cause: Cause, force: boolean): Promise<void> { | |
| 103 | const want = this.want(); | |
| 104 | if (!this.sw || !want) return; | |
| 105 | if (!force && this.s.applied === want.on) return; | |
| 106 | try { | |
| 107 | await (want.on ? this.sw.on() : this.sw.off()); | |
| 108 | this.error = null; | |
| 109 | } catch (err) { | |
| 110 | this.error = err instanceof Error ? err.message : String(err); | |
| 111 | console.error(`${this.name}: ${this.error}`); | |
| 112 | return; // not applied: the next tick tries again | |
| 113 | } | |
| 114 | const changed = this.s.applied !== want.on; | |
| 115 | this.s.applied = want.on; | |
| 116 | this.save(); | |
| 117 | // A transition is a change of state; the boot catch-up is logged even when nothing changed, to say the Pi came back. | |
| 118 | if (changed || cause === "boot") this.record({ at: this.now(), on: want.on, cause: cause === "boot" ? "boot" : want.cause }); | |
| 119 | } | |
| 120 | ||
| 121 | /** On start-up: set the state the schedule says now. */ | |
| 122 | boot(): Promise<void> { | |
| 123 | return this.serial(() => this.apply("boot", true)); | |
| 124 | } | |
| 125 | ||
| 126 | /** Called every few seconds: act when the schedule or an expired override has changed the wanted state. */ | |
| 127 | tick(): Promise<void> { | |
| 128 | return this.serial(() => this.apply("schedule", false)); | |
| 129 | } | |
| 130 | ||
| 131 | /** Replace the schedule and/or the switch (null removes it). The switch is verified before it is kept. */ | |
| 132 | async configure(change: { schedule?: unknown; switch?: unknown }): Promise<void> { | |
| 133 | let schedule = this.s.schedule; | |
| 134 | let driver = this.s.driver; | |
| 135 | let sw = this.sw; | |
| 136 | try { | |
| 137 | if (change.schedule !== undefined) schedule = change.schedule === null ? null : parseSchedule(change.schedule); | |
| 138 | if (change.switch !== undefined) { | |
| 139 | driver = change.switch === null ? null : parseDriver(change.switch); | |
| 140 | sw = driver ? this.make(driver) : null; | |
| 141 | await sw?.verify?.(); | |
| 142 | } | |
| 143 | } catch (err) { | |
| 144 | if (err instanceof ScheduleError || err instanceof SwitchError) throw new LightError(err.message); | |
| 145 | throw err; | |
| 146 | } | |
| 147 | this.s = { ...this.s, schedule, driver, override: change.switch !== undefined ? null : this.s.override, applied: change.switch !== undefined ? null : this.s.applied }; | |
| 148 | this.sw = sw; | |
| 149 | this.save(); | |
| 150 | await this.tick(); | |
| 151 | } | |
| 152 | ||
| 153 | /** Hold the light on or off until the next schedule transition; "clear" gives it back to the schedule. */ | |
| 154 | async override(value: unknown): Promise<void> { | |
| 155 | if (value !== "on" && value !== "off" && value !== "clear") throw new LightError("override is on, off or clear"); | |
| 156 | if (value === "clear") this.s.override = null; | |
| 157 | else { | |
| 158 | if (!this.sw) throw new LightError("set up a switch first"); | |
| 159 | // With no schedule there is no next transition: the override holds until cleared (a week at most). | |
| 160 | const until = this.s.schedule ? phaseAt(this.s.schedule, this.now(), this.zone).until : this.now() + 7 * 86_400_000; | |
| 161 | this.s.override = { on: value === "on", until }; | |
| 162 | } | |
| 163 | this.save(); | |
| 164 | await this.tick(); | |
| 165 | } | |
| 166 | ||
| 167 | view(): LightView { | |
| 168 | const t = this.now(); | |
| 169 | const want = this.want(); | |
| 170 | const live = this.s.override && t < this.s.override.until ? this.s.override : null; | |
| 171 | let text = this.name === "light" ? "Light: always on (no switch set up)" : "Pump: not run (no switch set up)"; | |
| 172 | if (this.sw) { | |
| 173 | const until = live ? live.until : this.s.schedule ? phaseAt(this.s.schedule, t, this.zone).until : null; | |
| 174 | const word = want ? (want.on ? "On" : "Off") : "Unscheduled"; | |
| 175 | text = until === null ? `${word} (no schedule set)` : `${word} until ${clockIn(until, this.zone)}${live ? " (override)" : ""}`; | |
| 176 | } | |
| 177 | return { name: this.name, configured: this.sw !== null, driver: this.s.driver?.driver ?? null, schedule: this.s.schedule, zone: this.zone, on: this.sw ? this.s.applied : null, text, override: live, dark: this.name === "light" && this.sw !== null && this.s.schedule !== null && !isCycle(this.s.schedule) && !phaseAt(this.s.schedule, t, this.zone).on, error: this.error, log: this.log.slice(-KEEP) }; | |
| 178 | } | |
| 179 | ||
| 180 | private record(e: Transition): void { | |
| 181 | this.log.push(e); | |
| 182 | if (this.log.length > KEEP) this.log.splice(0, this.log.length - KEEP); | |
| 183 | try { | |
| 184 | mkdirSync(dirname(this.logFile), { recursive: true }); | |
| 185 | appendFileSync(this.logFile, `${JSON.stringify(e)}\n`); | |
| 186 | } catch (err) { | |
| 187 | console.error(`${this.name}: could not log to ${this.logFile}: ${err instanceof Error ? err.message : String(err)}`); | |
| 188 | } | |
| 189 | } | |
| 190 | ||
| 191 | private load(): void { | |
| 192 | try { | |
| 193 | const raw = JSON.parse(readFileSync(this.o.file, "utf8")) as Record<string, unknown>; | |
| 194 | // Field by field: one bad value must not throw away the rest. | |
| 195 | const tryit = <T>(f: () => T): T | null => { | |
| 196 | try { | |
| 197 | return f(); | |
| 198 | } catch { | |
| 199 | return null; | |
| 200 | } | |
| 201 | }; | |
| 202 | this.s.schedule = raw.schedule ? tryit(() => parseSchedule(raw.schedule)) : null; | |
| 203 | this.s.driver = raw.driver ? tryit(() => parseDriver(raw.driver)) : null; | |
| 204 | const ov = raw.override as { on?: unknown; until?: unknown } | null; | |
| 205 | if (ov && typeof ov.on === "boolean" && typeof ov.until === "number") this.s.override = { on: ov.on, until: ov.until }; | |
| 206 | } catch { | |
| 207 | /* none yet, or unreadable: nothing set up */ | |
| 208 | } | |
| 209 | try { | |
| 210 | for (const line of readFileSync(this.logFile, "utf8").trimEnd().split("\n").slice(-KEEP)) { | |
| 211 | try { | |
| 212 | const e = JSON.parse(line) as Transition; | |
| 213 | if (typeof e.at === "number" && typeof e.on === "boolean" && ["schedule", "override", "boot"].includes(e.cause)) this.log.push(e); | |
| 214 | } catch { | |
| 215 | /* a torn line */ | |
| 216 | } | |
| 217 | } | |
| 218 | } catch { | |
| 219 | /* no log yet */ | |
| 220 | } | |
| 221 | } | |
| 222 | ||
| 223 | private save(): void { | |
| 224 | mkdirSync(dirname(this.o.file), { recursive: true }); | |
| 225 | const { schedule, driver, override } = this.s; | |
| 226 | writeFileSync(`${this.o.file}.tmp`, JSON.stringify({ schedule, driver, override }, null, 1)); | |
| 227 | renameSync(`${this.o.file}.tmp`, this.o.file); | |
| 228 | } | |
| 229 | } |
Software/so101/src/relay.ts +27 −4
| @@ -98,7 +98,8 @@ import type { PiSync } from "./pi-deploy.ts"; | ||
| 98 | 98 | import { serveData } from "./data-api.ts"; |
| 99 | 99 | import { serveDataPage } from "./data-page.ts"; |
| 100 | 100 | import { serveStory, weekNumbers, type StoryNumbers } from "./story.ts"; |
| 101 | import { handleAdmin, handleLift, type TuneP } from "./admin-routes.ts"; | |
| 101 | import { readGrow } from "./light-read.ts"; | |
| 102 | import { handleAdmin, handleLift, type LightHooks, type TuneP } from "./admin-routes.ts"; | |
| 102 | 103 | import { readPrecision } from "./precision-panel.ts"; |
| 103 | 104 | import { readTuning } from "./tuning-panel.ts"; |
| 104 | 105 | import { readServos } from "./servo-panel.ts"; |
| @@ -222,9 +223,9 @@ const PAGE = /^\/(?:index\.html|arm)?$/; | ||
| 222 | 223 | const STATIC = /^\/(?:index\.html)?$|^\/(?:model|vendor|ui)\//; |
| 223 | 224 | const LEADER = "/leader/calibration"; |
| 224 | 225 | /** Admins only: clearing an emergency stop and changing the settings (the safety limits among them). */ |
| 225 | 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"]); | |
| 226 | 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", "POST /grow/light", "POST /grow/pump"]); | |
| 226 | 227 | /** Routes only the owner may reach; anyone else is told there is no such page. */ |
| 227 | const OWNER_READS = new Set(["GET /servo-params", "PUT /servo-params", "POST /servo-params/factory", "GET /tuning", "POST /tuning/p"]); | |
| 228 | const OWNER_READS = new Set(["GET /servo-params", "PUT /servo-params", "POST /servo-params/factory", "GET /tuning", "POST /tuning/p", "GET /grow", "POST /grow/light", "POST /grow/pump"]); | |
| 228 | 229 | /** The driver's, and any admin's at any time. */ |
| 229 | 230 | const ADMIN_TOO = new Set(["POST /stop", "POST /resume", "POST /estop"]); |
| 230 | 231 | /** The forge's own paths (/__forge/signin and the like): the forge answers them in front of the app. */ |
| @@ -592,6 +593,28 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 592 | 593 | return `the arm server did not answer (${reason(err)})`; |
| 593 | 594 | } |
| 594 | 595 | }; |
| 596 | /** The grow light lives on the arm server (the Pi runs its schedule); this reads and changes it for the admin page. */ | |
| 597 | const armGrow = (path = "") => `${remote && onArm() ? remote.http : simulation}/grow${path}`; | |
| 598 | const lightHooks: LightHooks = { | |
| 599 | read: async () => { | |
| 600 | try { | |
| 601 | const answer = await fetch(armGrow(), { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 1000)) }); | |
| 602 | return answer.ok ? readGrow(await answer.json().catch(() => null)) : null; | |
| 603 | } catch { | |
| 604 | return null; | |
| 605 | } | |
| 606 | }, | |
| 607 | write: async (device, body) => { | |
| 608 | try { | |
| 609 | const answer = await fetch(armGrow(`/${device}`), { method: "POST", body: JSON.stringify(body), signal: AbortSignal.timeout(Math.min(readTimeoutMs, 8000)) }); | |
| 610 | if (answer.ok) return null; | |
| 611 | const err = (await answer.json().catch(() => null)) as { error?: unknown } | null; | |
| 612 | return typeof err?.error === "string" ? err.error.replace(/[\p{Cc}\p{Cf}]/gu, "").slice(0, 300) : `the arm server answered ${answer.status}`; | |
| 613 | } catch (err) { | |
| 614 | return `the arm server did not answer (${reason(err)})`; | |
| 615 | } | |
| 616 | }, | |
| 617 | }; | |
| 595 | 618 | /** The arm's servo registers for the owner's admin page; null when the arm does not answer in time. */ |
| 596 | 619 | const askServos = async () => { |
| 597 | 620 | try { |
| @@ -943,7 +966,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 943 | 966 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1]), cameraAdmin[2] !== undefined); |
| 944 | 967 | if (CAMERA_PROFILE.test(url.pathname)) return json(res, 404, { error: "no such route" }); |
| 945 | 968 | if (lobby && url.pathname === "/admin/lift") return await handleLift(lobby, req, res, readBody); |
| 946 | 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); | |
| 969 | 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, lightHooks); | |
| 947 | 970 | if (serveStory(req, res, url.pathname, { cameras: () => (restingNow() ? [] : cameras.list()), numbers: storyNumbers, signedIn: lobby && !lobby.local ? (r) => lobby.signedIn(r) : undefined })) return; |
| 948 | 971 | if (url.pathname === "/admin/versions") return versionsRead(req, res); |
| 949 | 972 | if (lobby && url.pathname === "/admin/data") return serveDataPage(lobby, req, res); |
Software/so101/src/server.ts +30
| @@ -46,6 +46,9 @@ | ||
| 46 | 46 | * ?hours=1-720 hourly rows (48 by default) |
| 47 | 47 | * 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, |
| 48 | 48 | * 409 while a run is under way or anything drives, 423 on E-stop or hold; the result joins GET /precision's tunings |
| 49 | * GET /grow the grow light and the pump (src/light.ts): schedule, switch driver, "On until 22:00", override and the last transitions | |
| 50 | * POST /grow/light {"schedule"?: {"onAt": "06:00", "hours": 12}|null, "switch"?: {"driver": "shelly"|"gpio"|"uhubctl", ...}|null} or {"override": "on"|"off"|"clear"}; 400 says why not | |
| 51 | * POST /grow/pump the same, with an interval schedule {"onMinutes": 5, "offMinutes": 25} | |
| 49 | 52 | * GET /tuning the run's phase while one is under way, and the last outcome |
| 50 | 53 | * GET /precision/trace?session=<id> a kept session's 5 Hz intent and read-back per joint, ticks: {session, t0, hz, joints} (400 bad id, 404 unknown or evicted; the last 20 sessions) |
| 51 | 54 | * 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) |
| @@ -94,6 +97,7 @@ import { MachineLog, perServo } from "./machine-log.ts"; | ||
| 94 | 97 | import { Metrics } from "./metrics.ts"; |
| 95 | 98 | import { wallMs } from "./clock.ts"; |
| 96 | 99 | import { readPiHealth } from "./pi-health.ts"; |
| 100 | import { DEVICES, Light, LightError, type DeviceName } from "./light.ts"; | |
| 97 | 101 | import { ARRIVE_TICKS, LINK_HOPS, parseSnapBack, READ_BACK_HOP, RELAY_HOP, type Cause, type Tracker } from "./precision.ts"; |
| 98 | 102 | import { deployedCommit, PrecisionHistory, TRACE_HZ } from "./precision-history.ts"; |
| 99 | 103 | import { Tuning, TuningRefused } from "./tuning.ts"; |
| @@ -128,6 +132,10 @@ export interface ServerOptions { | ||
| 128 | 132 | commit?: string; |
| 129 | 133 | /** How often the arm is checked for servos whose gains need writing, ms; unset, the gains are not written (the CLI sets 2000). */ |
| 130 | 134 | gainSyncMs?: number; |
| 135 | /** How often the grow light's schedule is checked, ms; unset, it is not run (the CLI sets 15000). The light then catches up at start. */ | |
| 136 | lightMs?: number; | |
| 137 | /** The grow light and the pump, for tests that give them a fake switch. */ | |
| 138 | lights?: Record<DeviceName, Light>; | |
| 131 | 139 | /** How long each sweep target is held, ms (1500); tests shorten it. */ |
| 132 | 140 | tuningHoldMs?: number; |
| 133 | 141 | /** Replaces the stream sweep of the P experiment; tests give it the numbers to decide on. */ |
| @@ -227,6 +235,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 227 | 235 | throw new Error(`safety options: ${(err as Error).message}`); |
| 228 | 236 | } |
| 229 | 237 | const metrics = new Metrics(join(dataDir, "metrics.jsonl")); |
| 238 | const lights = options.lights ?? { light: new Light({ name: "light", file: join(dataDir, "light.json") }), pump: new Light({ name: "pump", file: join(dataDir, "pump.json") }) }; | |
| 230 | 239 | const precision = new PrecisionHistory({ file: join(dataDir, "precision.sqlite"), commit: options.commit }); |
| 231 | 240 | /** The stream's precision tracker while one drives; every Goal_Position write starts its bus-to-motion clock. */ |
| 232 | 241 | let tracking: Tracker | null = null; |
| @@ -921,6 +930,24 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 921 | 930 | release(); |
| 922 | 931 | } |
| 923 | 932 | } |
| 933 | case "GET /grow": | |
| 934 | return json(res, 200, { light: lights.light.view(), pump: lights.pump.view() }); | |
| 935 | case "POST /grow/light": | |
| 936 | case "POST /grow/pump": { | |
| 937 | const device = lights[route.slice("POST /grow/".length) as DeviceName]; | |
| 938 | const { schedule, switch: sw, override, ...rest } = await readBody(req); | |
| 939 | const extra = Object.keys(rest)[0]; | |
| 940 | try { | |
| 941 | if (extra) throw new LightError(`no field "${extra.slice(0, 40)}"`); | |
| 942 | if (override !== undefined && (schedule !== undefined || sw !== undefined)) throw new LightError("an override is its own request"); | |
| 943 | if (override !== undefined) await device.override(override); | |
| 944 | else await device.configure({ schedule, switch: sw }); | |
| 945 | } catch (err) { | |
| 946 | if (err instanceof LightError) throw new HttpError(400, err.message); | |
| 947 | throw err; | |
| 948 | } | |
| 949 | return json(res, 200, device.view()); | |
| 950 | } | |
| 924 | 951 | case "GET /tuning": |
| 925 | 952 | return json(res, 200, tuning.state); |
| 926 | 953 | case "POST /tuning/p": { |
| @@ -1718,6 +1745,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1718 | 1745 | await new Promise<void>((resolve) => http.listen(options.port ?? 8101, options.host ?? "0.0.0.0", resolve)); |
| 1719 | 1746 | const gainTimer = options.gainSyncMs ? setInterval(() => void gainSync.tick(), options.gainSyncMs) : undefined; |
| 1720 | 1747 | if (gainTimer) void gainSync.tick(); |
| 1748 | const lightTimer = options.lightMs ? setInterval(() => DEVICES.forEach((d) => void lights[d].tick()), options.lightMs) : undefined; | |
| 1749 | if (options.lightMs) DEVICES.forEach((d) => void lights[d].boot()); | |
| 1721 | 1750 | const address = http.address(); |
| 1722 | 1751 | const port = typeof address === "object" && address ? address.port : options.port ?? 8101; |
| 1723 | 1752 | return { |
| @@ -1726,6 +1755,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1726 | 1755 | new Promise<void>((resolve) => { |
| 1727 | 1756 | clearInterval(watching); |
| 1728 | 1757 | clearInterval(gainTimer); |
| 1758 | clearInterval(lightTimer); | |
| 1729 | 1759 | machine.close(); |
| 1730 | 1760 | precision.close(); |
| 1731 | 1761 | bus.onSyncWrite = null; |
Software/so101/src/stations.test.ts +1 −1
| @@ -205,7 +205,7 @@ test("the terminal lists stations and the owner sets them; the door prints refus | ||
| 205 | 205 | }) as unknown as typeof fetch; |
| 206 | 206 | expect(stationLines([{ name: "The arm", kind: "arm", present: false, cameras: [] }])).toEqual(["The arm (arm): not connected, 0 camera(s)"]); |
| 207 | 207 | const printed: string[] = []; |
| 208 | const door = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, null, null, null, null, null, null, null, stationsReader({ PORT: "8102" }, fetcher)); | |
| 208 | const door = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, null, null, null, null, null, null, null, null, stationsReader({ PORT: "8102" }, fetcher)); | |
| 209 | 209 | door.input("/stations"); |
| 210 | 210 | door.input('/stations set [{"id":"a"}]'); |
| 211 | 211 | door.input("/stations nonsense"); |
Software/so101/src/terminal.test.ts +41 −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 { traceLines, traceReader, alignReader, cardReader, Door, tuningReader, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed, who } from "./terminal.ts"; | |
| 15 | import { growBody, growLines, growReader, traceLines, traceReader, alignReader, cardReader, Door, tuningReader, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed, who } from "./terminal.ts"; | |
| 16 | 16 | import { jointRows } from "./ui/machine.js"; |
| 17 | 17 | import { Turns } from "./turns.ts"; |
| 18 | 18 | |
| @@ -820,3 +820,43 @@ describe("open and closed in the terminal", () => { | ||
| 820 | 820 | expect(state(null)).toEqual(["the arm is open again"]); |
| 821 | 821 | }); |
| 822 | 822 | }); |
| 823 | ||
| 824 | describe("/grow", () => { | |
| 825 | const view = (name: "light" | "pump", extra = {}) => ({ name, configured: true, driver: "shelly", schedule: { onAt: "06:00", hours: 12 }, zone: "UTC", on: true, text: "On until 18:00", override: null, dark: false, error: null, log: [{ at: Date.parse("2026-06-10T06:00:00Z"), on: true, cause: "boot" }], ...extra }); | |
| 826 | test("what is typed becomes the body the arm server takes, and bad lines print the usage", () => { | |
| 827 | expect(growBody(["on"])).toEqual({ override: "on" }); | |
| 828 | expect(growBody(["schedule", "6:00", "12"])).toEqual({ schedule: { onAt: "06:00", hours: 12 } }); | |
| 829 | expect(growBody(["schedule", "5", "25"])).toEqual({ schedule: { onMinutes: 5, offMinutes: 25 } }); | |
| 830 | expect(growBody(["schedule", "off"])).toEqual({ schedule: null }); | |
| 831 | expect(growBody(["switch", "shelly", "192.168.1.40", "1"])).toEqual({ switch: { driver: "shelly", host: "192.168.1.40", gen: 1 } }); | |
| 832 | expect(growBody(["switch", "gpio", "17", "low"])).toEqual({ switch: { driver: "gpio", line: 17, activeLow: true } }); | |
| 833 | expect(growBody(["switch", "uhubctl", "1-1", "2", "046d:0825"])).toEqual({ switch: { driver: "uhubctl", hub: "1-1", port: 2, cameras: ["046d:0825"] } }); | |
| 834 | expect(growBody(["switch", "none"])).toEqual({ switch: null }); | |
| 835 | expect(growBody(["schedule", "x", "y"])).toBeNull(); | |
| 836 | expect(growBody(["on", "extra"])).toBeNull(); | |
| 837 | expect(typed(emptyRoom(), "/grow toaster on")).toHaveProperty("print"); | |
| 838 | expect(typed(emptyRoom(), "/grow on")).toEqual({ grow: { device: "light", body: { override: "on" } } }); | |
| 839 | expect(typed(emptyRoom(), "/grow pump schedule 5 25")).toEqual({ grow: { device: "pump", body: { schedule: { onMinutes: 5, offMinutes: 25 } } } }); | |
| 840 | expect(typed(emptyRoom(), "/grow")).toEqual({ grow: null }); | |
| 841 | }); | |
| 842 | test("the owner reads both and changes one through the same POST /grow/<device>; a guest is told it is the owner's", async () => { | |
| 843 | const printed: string[] = []; | |
| 844 | const asked: unknown[] = []; | |
| 845 | const post = async (path: string, body: unknown) => (asked.push([path, body]), { status: 200, error: null }); | |
| 846 | const read = async () => ({ error: null, lines: growLines({ light: view("light", { dark: true }) as never, pump: view("pump", { schedule: { onMinutes: 5, offMinutes: 25 }, text: "Off until 10:15" }) as never }) }); | |
| 847 | const door = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), post as never, null, null, null, null, null, null, null, null, read); | |
| 848 | door.input("/grow"); | |
| 849 | door.input("/grow pump schedule 10 20"); | |
| 850 | await new Promise((r) => setTimeout(r, 20)); | |
| 851 | expect(printed.join("\n")).toContain("On until 18:00 · on at 06:00 for 12 h (UTC) · switch: shelly"); | |
| 852 | expect(printed.join("\n")).toContain("Dark period: keep room lights off"); | |
| 853 | expect(printed.join("\n")).toContain("5 min on, 25 min off"); | |
| 854 | expect(asked).toEqual([["/grow/pump", { schedule: { onMinutes: 10, offMinutes: 20 } }]]); | |
| 855 | const guest = await growReader({ PORT: "8102" }, (async () => Response.json({ error: "not found" }, { status: 404 })) as unknown as typeof fetch)(); | |
| 856 | expect(guest).toEqual({ error: "the grow light is for the owner", lines: [] }); | |
| 857 | const refused: string[] = []; | |
| 858 | new Door("ws://127.0.0.1:1/live", {}, (l) => refused.push(l), (async () => ({ status: 404, error: "not found" })) as never, null, null, null, null, null, null, null, null, read).input("/grow light off"); | |
| 859 | await new Promise((r) => setTimeout(r, 20)); | |
| 860 | expect(refused).toEqual(["error: not found"]); | |
| 861 | }); | |
| 862 | }); |
Software/so101/src/terminal.ts +91 −4
| @@ -42,6 +42,10 @@ | ||
| 42 | 42 | * /precision owner or moderator: the precision scorecard /admin shows (GET /precision, src/precision-panel.ts) |
| 43 | 43 | * /servos owner: each joint's servo control registers /admin shows (GET /servo-params, src/servo-panel.ts); 404 to anyone else |
| 44 | 44 | * /tune <joint> <P> owner: the P experiment /admin's Servos "Try this P" runs (POST /tuning/p): sweep, write, sweep, keep or put back; 404 to anyone else |
| 45 | * /grow owner: the light and the pump as /admin's Grow card shows them (GET /grow); 404 to anyone else | |
| 46 | * /grow [light|pump] on|off|clear owner: (no device word is the light) override until the next change, or give it back to the schedule (POST /grow/<device>) | |
| 47 | * /grow <light|pump> schedule 06:00 12 | 5 25 | off owner: a daily photoperiod (on at, hours) or an interval cycle (minutes on, off), or none | |
| 48 | * /grow <light|pump> switch none | shelly <host> [1|2] | gpio <line> [low] | uhubctl <hub> <port> [vid:pid…] owner: the switch; uhubctl is refused when a camera shares it | |
| 45 | 49 | * /tune owner: the run's progress and the last result (GET /tuning, src/tuning-panel.ts) |
| 46 | 50 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, |
| 47 | 51 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it |
| @@ -58,6 +62,9 @@ import { dataLines, RANGES, turnLines, type Range } from "./data-lines.ts"; | ||
| 58 | 62 | import { ID, NAME, sign } from "./identity.ts"; |
| 59 | 63 | import { readVia, signedInText, type Via } from "./signed-in.ts"; |
| 60 | 64 | import { readServos, type ServoPanel } from "./servo-panel.ts"; |
| 65 | import { readGrow } from "./light-read.ts"; | |
| 66 | import { isCycle } from "./light-schedule.ts"; | |
| 67 | import type { DeviceName, LightView } from "./light.ts"; | |
| 61 | 68 | import { readTuning, tuningSentence, type TuningView } from "./tuning-panel.ts"; |
| 62 | 69 | import { JOINTS } from "./sts3215.ts"; |
| 63 | 70 | import { headlineValue, hopLines, NO_HOPS, P95_RULE, readPrecision, sampleSize, sparkline, type PrecisionPanel } from "./precision-panel.ts"; |
| @@ -98,7 +105,7 @@ function appPort(env: Env): number { | ||
| 98 | 105 | return port; |
| 99 | 106 | } |
| 100 | 107 | |
| 101 | export type Path = "/stop" | "/resume" | "/settings/table-here" | "/settings/table-touch" | "/settings/joint-zero" | "/settings" | "/tuning/p"; | |
| 108 | export type Path = "/stop" | "/resume" | "/settings/table-here" | "/settings/table-touch" | "/settings/joint-zero" | "/settings" | "/tuning/p" | "/grow/light" | "/grow/pump"; | |
| 102 | 109 | /** `tableOffsetMm` is the offset the server holds after a settings call, when it said. */ |
| 103 | 110 | export type Post = (path: Path, body?: Record<string, unknown>) => Promise<{ status: number; error: string | null; tableOffsetMm?: number; offsetDeg?: number; heightMm?: number; tiltDeg?: number; applied?: boolean }>; |
| 104 | 111 | |
| @@ -242,6 +249,63 @@ export function tuningReader(env: Env, fetcher: typeof fetch = fetch): ReadTunin | ||
| 242 | 249 | }; |
| 243 | 250 | } |
| 244 | 251 | |
| 252 | /** What GET /grow answered, as lines; a guest is told there is no such route, as for /servos. */ | |
| 253 | export type Grow = { error: string | null; lines: string[] }; | |
| 254 | export type ReadGrow = () => Promise<Grow>; | |
| 255 | ||
| 256 | /** The light and the pump as the grow card says them: what each does now, its schedule and switch, the dark-period caution, the last changes. */ | |
| 257 | export function growLines(grow: { light: LightView; pump: LightView | null }): string[] { | |
| 258 | const lines: string[] = []; | |
| 259 | for (const v of [grow.light, grow.pump]) { | |
| 260 | if (!v) continue; | |
| 261 | const s = v.schedule; | |
| 262 | const sched = !s ? "no schedule" : isCycle(s) ? `${s.onMinutes} min on, ${s.offMinutes} min off` : `on at ${s.onAt} for ${s.hours} h (${v.zone})`; | |
| 263 | lines.push(`${plain(v.text)} · ${sched} · switch: ${v.driver ?? "none"}`); | |
| 264 | if (v.dark) lines.push(` Dark period: keep room lights off`); | |
| 265 | if (v.error) lines.push(` the switch failed: ${plain(v.error)}`); | |
| 266 | for (const e of v.log.slice(-3)) lines.push(` ${new Date(e.at).toISOString().slice(5, 16).replace("T", " ")}Z ${e.on ? "on" : "off"} (${e.cause})`); | |
| 267 | } | |
| 268 | return lines; | |
| 269 | } | |
| 270 | ||
| 271 | /** GET the grow card's state as /admin shows it, signed afresh; the server decides who may (the owner only). */ | |
| 272 | export function growReader(env: Env, fetcher: typeof fetch = fetch): ReadGrow { | |
| 273 | return async () => { | |
| 274 | try { | |
| 275 | const r = await fetcher(`${appUrl(env)}/grow`, { headers: terminalHeaders(env), signal: AbortSignal.timeout(5000) }); | |
| 276 | const body = (await r.json().catch(() => null)) as { error?: unknown } | null; | |
| 277 | if (r.status === 404) return { error: "the grow light is for the owner", lines: [] }; | |
| 278 | const grow = r.ok ? readGrow(body) : null; | |
| 279 | return grow ? { error: null, lines: growLines(grow) } : { error: plain(body?.error ?? `status ${r.status}`), lines: [] }; | |
| 280 | } catch (err) { | |
| 281 | return { error: plain((err as Error).message), lines: [] }; | |
| 282 | } | |
| 283 | }; | |
| 284 | } | |
| 285 | ||
| 286 | const GROW_USAGE = "usage: /grow · /grow [light|pump] on|off|clear · schedule off | schedule 06:00 12 (light: on at, hours) | schedule 5 25 (pump: minutes on, off) · switch none | shelly <host> [1|2] | gpio <line> [low] | uhubctl <hub> <port> [vid:pid…]"; | |
| 287 | ||
| 288 | /** `/grow <device> …` as the body POST /grow/<device> takes; null when it does not parse. The arm server checks every field again. */ | |
| 289 | export function growBody(words: string[]): Record<string, unknown> | null { | |
| 290 | const [what = "", ...a] = words; | |
| 291 | const n = (w: string | undefined) => (w !== undefined && /^\d{1,4}$/.test(w) ? Number(w) : null); | |
| 292 | if (what === "on" || what === "off" || what === "clear") return a.length ? null : { override: what }; | |
| 293 | if (what === "schedule") { | |
| 294 | if (a.length === 1 && a[0] === "off") return { schedule: null }; | |
| 295 | if (a.length !== 2) return null; | |
| 296 | if (/^\d{1,2}:\d{2}$/.test(a[0]!)) return n(a[1]) === null ? null : { schedule: { onAt: a[0]!.padStart(5, "0"), hours: n(a[1]) } }; | |
| 297 | return n(a[0]) === null || n(a[1]) === null ? null : { schedule: { onMinutes: n(a[0]), offMinutes: n(a[1]) } }; | |
| 298 | } | |
| 299 | if (what === "switch") { | |
| 300 | const [driver, x, y, ...ids] = a; | |
| 301 | if (driver === "none" && a.length === 1) return { switch: null }; | |
| 302 | if (driver === "shelly" && x && a.length <= 3) return { switch: { driver, host: x, gen: y === "1" ? 1 : 2 } }; | |
| 303 | if (driver === "gpio" && n(x) !== null && a.length <= 3) return { switch: { driver, line: n(x), activeLow: y === "low" } }; | |
| 304 | if (driver === "uhubctl" && x && n(y) !== null) return { switch: { driver, hub: x, port: n(y), cameras: ids } }; | |
| 305 | } | |
| 306 | return null; | |
| 307 | } | |
| 308 | ||
| 245 | 309 | /** What GET /precision/trace answered for one session, or why not. */ |
| 246 | 310 | export type TraceView = { error: string | null; lines: string[] }; |
| 247 | 311 | export type ReadTrace = (session: number) => Promise<TraceView>; |
| @@ -425,7 +489,7 @@ export function whoami(room: Room): string { | ||
| 425 | 489 | /** The terminal holds no session to end: the forge signs who is at the keyboard afresh on every connection. */ |
| 426 | 490 | export const SIGNOUT_NOTE = "the terminal keeps no session: you are whoever your SSH key signs in as, each time you connect; /quit to leave, and connect with another key to be someone else"; |
| 427 | 491 | |
| 428 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] /align [joint] (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) · /close [note] /open (owner) · /health /precision /trace <session> /data [hour|day|week|all|#<turn>] /versions (owner, moderator) · /servos /tune [<joint> <P>] (owner) · /stations [set <json>] (set: owner) · /machine [off] · /who /whoami · /quit"; | |
| 492 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] /align [joint] (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) · /close [note] /open (owner) · /health /precision /trace <session> /data [hour|day|week|all|#<turn>] /versions (owner, moderator) · /servos /tune [<joint> <P>] /grow [light|pump …] (owner) · /stations [set <json>] (set: owner) · /machine [off] · /who /whoami · /quit"; | |
| 429 | 493 | |
| 430 | 494 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 431 | 495 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -581,7 +645,7 @@ function target(room: Room, word: string): string | null { | ||
| 581 | 645 | return ID.test(word) ? word : null; |
| 582 | 646 | } |
| 583 | 647 | |
| 584 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number | { touch: 1 | 2 | 3 } } | { zero: { joint: string; referenceDeg: number } } | { align: string | null } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { trace: number } | { data: DataAsk } | { servos: true } | { tune: { joint: number; p: number } | null } | { versions: true } | { stations: string | null } | { quit: true } | null; | |
| 648 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number | { touch: 1 | 2 | 3 } } | { zero: { joint: string; referenceDeg: number } } | { align: string | null } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { trace: number } | { data: DataAsk } | { servos: true } | { grow: { device: DeviceName; body: Record<string, unknown> } | null } | { tune: { joint: number; p: number } | null } | { versions: true } | { stations: string | null } | { quit: true } | null; | |
| 585 | 649 | |
| 586 | 650 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 587 | 651 | export function typed(room: Room, input: string): Typed { |
| @@ -609,6 +673,14 @@ export function typed(room: Room, input: string): Typed { | ||
| 609 | 673 | if (joint === undefined || rest.length !== 1 || !/^\d{1,3}$/.test(rest[0]!)) return { print: TUNE_USAGE }; |
| 610 | 674 | return { tune: { joint: Number(joint), p: Number(rest[0]) } }; |
| 611 | 675 | } |
| 676 | if (/^grow$/i.test(verb)) { | |
| 677 | if (!arg) return { grow: null }; | |
| 678 | // No device word is the light, as /grow on|off|schedule|switch was before the pump. | |
| 679 | const word = arg.toLowerCase(); | |
| 680 | const device: DeviceName = word === "pump" ? "pump" : "light"; | |
| 681 | const body = growBody(word === "light" || word === "pump" ? rest : [word, ...rest]); | |
| 682 | return body ? { grow: { device, body } } : { print: GROW_USAGE }; | |
| 683 | } | |
| 612 | 684 | if (/^data$/i.test(verb) && rest.length) return { print: DATA_USAGE }; |
| 613 | 685 | // The owner's switch (src/opening.ts): the note is the rest of the line, spaces and all; the server checks it. |
| 614 | 686 | if (/^close$/i.test(verb)) return { send: { type: "open", open: false, note: line.slice(1 + verb.length).trim() } }; |
| @@ -727,9 +799,11 @@ export class Door { | ||
| 727 | 799 | private readonly readStations: ReadStations | null; |
| 728 | 800 | private readonly readAlign: ReadAlign | null; |
| 729 | 801 | private readonly readData: ReadData | null; |
| 802 | private readonly readGrow: ReadGrow | null; | |
| 730 | 803 | |
| 731 | 804 | /** `post` reaches the app's /stop and /resume, `read` its /admin/health, `readCard` its /precision; without them, the door says it cannot. */ |
| 732 | constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null, readCard: ReadCard | null = null, readServos: ReadServos | null = null, readVersions: ReadVersions | null = null, readAlign: ReadAlign | null = null, readTuning: ReadTuning | null = null, readTrace: ReadTrace | null = null, readData: ReadData | null = null, readStations: ReadStations | null = null) { | |
| 805 | constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null, readCard: ReadCard | null = null, readServos: ReadServos | null = null, readVersions: ReadVersions | null = null, readAlign: ReadAlign | null = null, readTuning: ReadTuning | null = null, readTrace: ReadTrace | null = null, readData: ReadData | null = null, readGrow: ReadGrow | null = null, readStations: ReadStations | null = null) { | |
| 806 | this.readGrow = readGrow; | |
| 733 | 807 | this.readData = readData; |
| 734 | 808 | this.readTrace = readTrace; |
| 735 | 809 | this.readAlign = readAlign; |
| @@ -786,6 +860,7 @@ export class Door { | ||
| 786 | 860 | else if ("trace" in t) void this.trace(t.trace); |
| 787 | 861 | else if ("data" in t) void this.data(t.data); |
| 788 | 862 | else if ("servos" in t) void this.servos(); |
| 863 | else if ("grow" in t) void this.grow(t.grow); | |
| 789 | 864 | else if ("tune" in t) void this.tune(t.tune); |
| 790 | 865 | else if ("versions" in t) void this.versions(); |
| 791 | 866 | else if ("stations" in t) void this.stations(t.stations); |
| @@ -852,6 +927,18 @@ export class Door { | ||
| 852 | 927 | for (const line of r.error || !r.panel ? [`error: ${r.error ?? "no servos"}`] : servosLines(r.panel)) this.print(line); |
| 853 | 928 | } |
| 854 | 929 | |
| 930 | /** The server decides who may; a change is posted as /admin's forms post it, then the card is read again. */ | |
| 931 | private async grow(change: { device: DeviceName; body: Record<string, unknown> } | null): Promise<void> { | |
| 932 | if (!this.readGrow) return this.print("error: the grow light is not available here"); | |
| 933 | if (change) { | |
| 934 | if (!this.post) return this.print("error: the grow light is not available here"); | |
| 935 | const r = await this.post(`/grow/${change.device}`, change.body); | |
| 936 | if (r.error) return this.print(`error: ${r.error}`); | |
| 937 | } | |
| 938 | const r = await this.readGrow(); | |
| 939 | for (const line of r.error ? [`error: ${r.error}`] : r.lines) this.print(line); | |
| 940 | } | |
| 941 | ||
| 855 | 942 | /** The server decides who may; with a joint and a P a run starts (a refusal is printed), else the run's state is. */ |
| 856 | 943 | private async tune(run: { joint: number; p: number } | null): Promise<void> { |
| 857 | 944 | if (run) { |
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 { alignReader, cardReader, dataReader, Door, HELP, liveUrl, poster, reader, servosReader, stationsReader, terminalHeaders, traceReader, tuningReader, versionsReader } from "./terminal.ts"; | |
| 7 | import { alignReader, cardReader, dataReader, Door, growReader, HELP, liveUrl, poster, reader, servosReader, stationsReader, terminalHeaders, traceReader, tuningReader, versionsReader } 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), cardReader(env), servosReader(env), versionsReader(env), alignReader(env), tuningReader(env), traceReader(env), dataReader(env), stationsReader(env)); | |
| 20 | const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env), cardReader(env), servosReader(env), versionsReader(env), alignReader(env), tuningReader(env), traceReader(env), dataReader(env), growReader(env), stationsReader(env)); | |
| 21 | 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); |
| 22 | 22 | try { |
| 23 | 23 | await door.open(() => { |
new above
offline
For a moderator (
canEditfalse) this link points at forms that are not rendered. Show the link only whencanEdit, and give everyone else plain text like "No switch set up".