Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Grow care: a plant profile (spinach first), reminders from it, a log book, and metrics with target bands; manual now, sensors later #598
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
smith/arm:smith/585-grow-care-a-plant-profile-spinach-first → main 4 commits fork
15 files
changed +1316
−7
Software/so101/README.md +13
| @@ -87,6 +87,7 @@ The app is a workshop: one Pi, several **stations**, each with its cameras and c | ||
| 87 | 87 | - **Any subset present.** The grow box has nothing to enumerate (the light is USB power only), so it is always there. The arm's card is there only while the link to the Pi's `so101 serve` is live; unplugged, closed by the owner or unreachable it says why ("The arm: not connected", "The arm is resting") and offers no controls, and the owner sees **Open now** on it. Plugging the arm back in brings its card back by itself, with no restart. `so101 serve` with no servo board waits for one ("arm not connected; waiting for its servo board") instead of exiting, so the Pi's service stays up for the cameras. |
| 88 | 88 | - **"Camera can't see the plants."** On the grow box's card, each still is checked in the browser once it has loaded: the part inside the camera's box (set on Tune, `/admin/camera-list`) is counted for blown-out and black pixels (`visibility` in src/ui/still-frame.js), and when the plants cannot be seen the card says so over the foot of the still, with a link to Tune (src/ui/grow-hint.js). The relay never decodes a JPEG, so the terminal and the JSON doors cannot show this hint; they have no pixels to count. |
| 89 | 89 | - **The config** is `so101/stations.json` under `FORGE_APP_DATA`: a list of `{id, name, kind: "arm"|"grow", cameras: [camera ids], controls: [{label, href}]}` (src/stations.ts). Without a file it is the arm (camera 1) and the grow box (camera 2, from the camera list): edit it to match the cameras. With only an arm in it, `/` is the arm's page as before. |
| 90 | - **Live.** `GET /care/events` is a server-sent stream that says `care` after every change to the book, from any door; the page listens with a few lines of script and refreshes itself (not while a field has focus). Without the script the page works the same, on reload. A refused form returns to `/care?error=…` with the message in an alert line. | |
| 90 | 91 | - **Three doors.** The page `/admin/stations/edit` (owner; a raw JSON box that needs JavaScript, so it is awkward on a phone: prefer a laptop or the terminal), `GET /stations` (anyone: each station's `present`, why not, and its camera ids and names) and `PUT /admin/stations` (owner; at most 16 KB, 400 on bad JSON or a bad station), and in the terminal `/stations` to list and `/stations set <json list>` (owner) to replace them. |
| 91 | 92 | |
| 92 | 93 | ## The grow box's stills, timelapse and log (on the Grow box card) |
| @@ -95,6 +96,18 @@ The hosted app takes a still from the grow station's first camera every 10 minut | ||
| 95 | 96 | |
| 96 | 97 | `GET /grow/stills?from=&to=&after=&limit=&dark=1` pages stills (`{stills, next, count, bytes, capBytes}`), `GET /grow/stills/<ms>.jpg` one still, `GET /grow/log` the log and chart numbers; `POST /grow/log {planted?, note?}` and `POST /grow/canopy {readings}` are the owner's, and same-origin only. The chart is empty until the owner has opened the card once, since only that browser works out the readings. Without JavaScript the card shows the latest still and a link to `/grow/log`. From the terminal: `/grow log` reads the log, `/grow planted <YYYY-MM-DD>|none` and `/grow note <text>` (owner) write it through the same routes; the card shows a note on its next load. |
| 97 | 98 | |
| 99 | ## Plant care: /care | |
| 100 | ||
| 101 | The grow box's care app: a plant profile, reminders worked out from it and the log, a typed log book, and charts against target bands. All figures are **typical ranges, not guaranteed**. It is a separate page from the grow light and stills (`/grow`); the grow box's card on `/` has a **Care** button for it (a `stations.json` saved before this needs `{label: "Care", href: "/care"}` added to the grow station's controls). | |
| 102 | ||
| 103 | - **The page `/care`** (anyone may read; only the owner has the buttons): the health strip (green, or what is off, like "pH 7.1, above 6.5, measured 2 d ago"), the reminders with Done and Snooze, one-tap "Topped off", "Changed water" and "Watered", forms for a measurement, an action, a note, a problem and the transplant, charts of the last 30 days with the band shaded, and the log book as a timeline with the stage headings. It needs no JavaScript. | |
| 104 | - **Stages.** A station starts as a rockwool seedling; logging a **transplant** (system, litres, sites, pump) moves it to the hydroponic stage and the first harvest after that to the harvest stage. Each stage has its own bands and reminders, and the history stays in the log. A vertical tower measures every 36 h and tops off every 24 h; the pump reminder shows only if the transplant said there is a pump. | |
| 105 | - **Reminders** fall due a set time after the last log entry that counts for them (a top-off resets "top off", a watering resets the moisture check), or after the stage began. Done, Snooze and a different cadence (`POST /care/reminder {id, action: "done"|"snooze"|"every", hours}`) are the owner's. | |
| 106 | - **Profiles are files.** `src/care-profiles/spinach.json` ships with the app; put another plant (lettuce, basil) as `FORGE_APP_DATA/so101/care-profiles/<name>.json` in the same shape (stages, `bands`, `reminders` with `everyHours`, optional `tower`, `needs`, `resets`; see src/care-profile.ts, which names what is wrong with a bad file and skips it). `CARE_PROFILE=<id>` picks which one the app runs (default `spinach`). | |
| 107 | - **The log book** is `FORGE_APP_DATA/so101/care.json`. Entries are `measurement` (ph, ec, waterTemp, airTemp, level, lightHours), `action` (sow, water, topoff, change, nutrients, thin, harvest, airstone, pumpcheck, transplant), `observation` and `problem`, each with a time (now unless given). A measurement is a `Reading {kind, value, at, source: manual|sensor}`, so a sensor can write the same later. Photos on observations and the pump schedule are not part of it yet. | |
| 108 | - **Live.** `GET /care/events` is a server-sent stream that says `care` after every change to the book, from any door; the page listens with a few lines of script and refreshes itself (not while a field has focus). Without the script the page works the same, on reload. A refused form returns to `/care?error=…` with the message in an alert line. | |
| 109 | - **Three doors.** The page; JSON: `GET /care/api` (anyone), `POST /care/log`, `PUT` or `DELETE /care/log/<id>` and `POST /care/reminder` (owner, same-origin only, 8 KB at most); and in the terminal `/care` (stage, health, what is due, the last entries with their ids) for anyone, with `/care log ph 6.1`, `/care did topoff`, `/care did harvest 40`, `/care note <text>`, `/care problem algae [detail]`, `/care done <reminder>`, `/care snooze <reminder> [hours]` and `/care delete <id>` for the owner. All three act on the same log, so a write in one shows in the others at once. | |
| 110 | ||
| 98 | 111 | ## The story page: /story |
| 99 | 112 | |
| 100 | 113 | `/story` on the hosted app is the arm explained for anyone: the hook, how it works (with a diagram of browser → forge → Pi → servos, and what latency, the queue, STOP and the safety zone mean), how to build your own (the [](https://huggingface.co/docs/lerobot/so101), this repository, `bun so101 setup`) and what the crew built. Anyone may read it; it is linked from the Chat tab's footer (hidden while you drive) and the Queue tab. |
Software/so101/bench/fake-serve.ts +4 −1
| @@ -26,6 +26,8 @@ import { Moderator, modelFromEnv } from "../src/moderator.ts"; | ||
| 26 | 26 | import { parseRemote, parseVideo, startRelay, type Remote } from "../src/relay.ts"; |
| 27 | 27 | import { piSyncFromEnv } from "../src/pi-deploy.ts"; |
| 28 | 28 | import { Facts } from "../src/facts.ts"; |
| 29 | import { CareLog } from "../src/care-log.ts"; | |
| 30 | import { BUILT_IN_DIR, loadProfiles } from "../src/care-profile.ts"; | |
| 29 | 31 | import { GrowLog } from "../src/grow-log.ts"; |
| 30 | 32 | import { GrowStills, parseEvery } from "../src/grow-stills.ts"; |
| 31 | 33 | import { startServer } from "../src/server.ts"; |
| @@ -77,6 +79,7 @@ try { | ||
| 77 | 79 | const facts = new Facts({ file: join(dir, "facts.sqlite") }); |
| 78 | 80 | const piSync = piSyncFromEnv(process.env, remote?.http ?? null, remote?.host ?? null, () => lobby.turns.snapshot().driver === null, dir); |
| 79 | 81 | const grow = { stills: new GrowStills(join(dir, "grow-stills"), { capBytes: Number(process.env.GROW_STILLS_CAP_MB) * 1e6 || undefined }), log: new GrowLog(join(dir, "grow-log.json")), everyMs: parseEvery(process.env.GROW_STILL_MINUTES) }; |
| 80 | const relay = await startRelay({ grow, stations: new StationHub(join(dir, "stations.json")), facts, piSync: piSync ?? undefined, host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, cameras, leaders, video, summaryEveryMs: 60_000, holdFile: join(dir, "hold.json"), baselineFile: join(dir, "servo-factory.json") }); | |
| 82 | const careProfile = loadProfiles(BUILT_IN_DIR, join(dir, "care-profiles")).find((p) => p.id === (process.env.CARE_PROFILE ?? "spinach")); | |
| 83 | const relay = await startRelay({ care: careProfile ? { log: new CareLog(join(dir, "care.json")), profile: careProfile } : undefined, grow, stations: new StationHub(join(dir, "stations.json")), facts, piSync: piSync ?? undefined, host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, cameras, leaders, video, summaryEveryMs: 60_000, holdFile: join(dir, "hold.json"), baselineFile: join(dir, "servo-factory.json") }); | |
| 81 | 84 | const { mode, host: armHost } = relay.link(); |
| 82 | 85 | console.log(`arm on http://${host}:${relay.port} (${mode === "simulated" ? "simulated" : `arm ${armHost}: ${mode}`}; data in ${dir}${local ? "; local: every visitor drives as the owner" : ""})`); |
Software/so101/src/care-log.ts added +207
| @@ -0,0 +1,207 @@ | ||
| 1 | /** | |
| 2 | * The grow log book: typed, timestamped entries kept in one file under the data dir (care.json), plus the reminders' | |
| 3 | * snoozes and cadence edits. A measurement is a Reading, so a sensor later writes the same thing a hand does. | |
| 4 | */ | |
| 5 | ||
| 6 | import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 7 | import { dirname } from "node:path"; | |
| 8 | import { MEASURES, type Measure } from "./care-profile.ts"; | |
| 9 | ||
| 10 | export const MAX_ENTRIES = 5000; | |
| 11 | export const ACTIONS = ["sow", "water", "topoff", "change", "nutrients", "thin", "harvest", "airstone", "pumpcheck", "transplant", "done"] as const; | |
| 12 | export const PROBLEMS = ["bolting", "tip burn", "root rot", "algae", "yellowing", "leggy"] as const; | |
| 13 | export const SYSTEMS = ["vertical tower", "DWC", "NFT", "Kratky", "ebb-and-flow"] as const; | |
| 14 | export type Action = (typeof ACTIONS)[number]; | |
| 15 | ||
| 16 | /** What a sensor will also produce. */ | |
| 17 | export interface Reading { | |
| 18 | kind: Measure; | |
| 19 | value: number; | |
| 20 | at: number; | |
| 21 | source: "manual" | "sensor"; | |
| 22 | } | |
| 23 | ||
| 24 | export interface Transplant { | |
| 25 | system: (typeof SYSTEMS)[number]; | |
| 26 | litres: number; | |
| 27 | sites: number; | |
| 28 | pump: boolean; | |
| 29 | } | |
| 30 | ||
| 31 | export type Entry = { id: number; at: number } & ( | |
| 32 | | ({ type: "measurement" } & Omit<Reading, "at">) | |
| 33 | | { type: "action"; what: Action; amount?: number; ref?: string; transplant?: Transplant } | |
| 34 | | { type: "observation"; text: string } | |
| 35 | | { type: "problem"; what: (typeof PROBLEMS)[number]; text?: string } | |
| 36 | ); | |
| 37 | ||
| 38 | /** An entry without its id (Omit would collapse the union). */ | |
| 39 | export type EntryBody = Entry extends infer E ? (E extends unknown ? Omit<E, "id"> : never) : never; | |
| 40 | ||
| 41 | export class LogError extends Error {} | |
| 42 | ||
| 43 | /** Plausible limits per measure: a typo like 71 for 7.1 is refused at the door. */ | |
| 44 | const LIMITS: Record<Measure, [number, number]> = { ph: [0, 14], ec: [0, 10], waterTemp: [0, 45], airTemp: [-10, 55], level: [0, 100], lightHours: [0, 24] }; | |
| 45 | ||
| 46 | const text = (v: unknown, what: string, max: number, required = true): string | undefined => { | |
| 47 | if (v === undefined || v === "") { | |
| 48 | if (required) throw new LogError(`${what} is needed`); | |
| 49 | return undefined; | |
| 50 | } | |
| 51 | if (typeof v !== "string" || v.length > max || /[\u0000-\u0008\u000b-\u001f\u007f]/.test(v)) throw new LogError(`${what} is up to ${max} characters`); | |
| 52 | return v.trim(); | |
| 53 | }; | |
| 54 | const positive = (v: unknown, what: string, max: number): number => { | |
| 55 | if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > max) throw new LogError(`${what} is a number above 0, up to ${max}`); | |
| 56 | return v; | |
| 57 | }; | |
| 58 | ||
| 59 | /** Any JSON → an entry (without its id); throws a LogError saying what is wrong. */ | |
| 60 | export function parseEntry(input: unknown, now = Date.now()): EntryBody { | |
| 61 | if (!input || typeof input !== "object" || Array.isArray(input)) throw new LogError("an entry is an object"); | |
| 62 | const e = input as Record<string, unknown>; | |
| 63 | let at = now; | |
| 64 | if (e.at !== undefined) { | |
| 65 | at = typeof e.at === "number" ? e.at : Date.parse(String(e.at)); | |
| 66 | if (!Number.isFinite(at) || at > now + 60_000 || at < now - 3650 * 86_400_000) throw new LogError("at is a time in the past"); | |
| 67 | } | |
| 68 | switch (e.type) { | |
| 69 | case "measurement": { | |
| 70 | if (!MEASURES.includes(e.kind as Measure)) throw new LogError(`kind is one of ${MEASURES.join(", ")}`); | |
| 71 | const [lo, hi] = LIMITS[e.kind as Measure]; | |
| 72 | if (typeof e.value !== "number" || !Number.isFinite(e.value) || e.value < lo || e.value > hi) throw new LogError(`${e.kind} is a number from ${lo} to ${hi}`); | |
| 73 | return { at, type: "measurement", kind: e.kind as Measure, value: e.value, source: "manual" }; | |
| 74 | } | |
| 75 | case "action": { | |
| 76 | if (!ACTIONS.includes(e.what as Action)) throw new LogError(`what is one of ${ACTIONS.join(", ")}`); | |
| 77 | const base = { at, type: "action" as const, what: e.what as Action }; | |
| 78 | if (e.what === "transplant") { | |
| 79 | if (!SYSTEMS.includes(e.system as never)) throw new LogError(`system is one of ${SYSTEMS.join(", ")}`); | |
| 80 | const sites = positive(e.sites, "sites", 500); | |
| 81 | if (!Number.isInteger(sites)) throw new LogError("sites is a whole number"); | |
| 82 | return { ...base, transplant: { system: e.system as Transplant["system"], litres: positive(e.litres, "litres", 2000), sites, pump: e.pump === true } }; | |
| 83 | } | |
| 84 | if (e.what === "done") { | |
| 85 | const ref = text(e.ref, "ref", 32); | |
| 86 | if (!/^[a-z0-9][a-z0-9-]*$/.test(ref!)) throw new LogError("ref is a reminder id"); | |
| 87 | return { ...base, ref }; | |
| 88 | } | |
| 89 | return { ...base, ...(e.amount !== undefined ? { amount: positive(e.amount, "amount", 100000) } : {}) }; | |
| 90 | } | |
| 91 | case "observation": | |
| 92 | return { at, type: "observation", text: text(e.text, "text", 1000)! }; | |
| 93 | case "problem": { | |
| 94 | if (!PROBLEMS.includes(e.what as never)) throw new LogError(`what is one of ${PROBLEMS.join(", ")}`); | |
| 95 | const note = text(e.text, "text", 1000, false); | |
| 96 | return { at, type: "problem", what: e.what as (typeof PROBLEMS)[number], ...(note ? { text: note } : {}) }; | |
| 97 | } | |
| 98 | default: | |
| 99 | throw new LogError("type is measurement, action, observation or problem"); | |
| 100 | } | |
| 101 | } | |
| 102 | ||
| 103 | /** The key reminders reset on: "measurement:ph", "action:topoff", "done:<reminder>". */ | |
| 104 | export function keyOf(e: Entry): string | null { | |
| 105 | if (e.type === "measurement") return `measurement:${e.kind}`; | |
| 106 | if (e.type === "action") return e.what === "done" ? `done:${e.ref}` : `action:${e.what}`; | |
| 107 | return null; | |
| 108 | } | |
| 109 | ||
| 110 | interface Saved { | |
| 111 | startedAt: number; | |
| 112 | nextId: number; | |
| 113 | entries: Entry[]; | |
| 114 | snoozes: Record<string, number>; | |
| 115 | every: Record<string, number>; | |
| 116 | } | |
| 117 | ||
| 118 | export class CareLog { | |
| 119 | private data: Saved; | |
| 120 | private readonly file: string | undefined; | |
| 121 | private readonly clock: () => number; | |
| 122 | ||
| 123 | constructor(file?: string, clock: () => number = Date.now) { | |
| 124 | this.file = file; | |
| 125 | this.clock = clock; | |
| 126 | this.data = { startedAt: clock(), nextId: 1, entries: [], snoozes: {}, every: {} }; | |
| 127 | if (file && existsSync(file)) { | |
| 128 | try { | |
| 129 | this.data = { ...this.data, ...JSON.parse(readFileSync(file, "utf8")) }; | |
| 130 | } catch (err) { | |
| 131 | console.error(`care: ${file} unreadable (${(err as Error).message}); starting empty`); | |
| 132 | } | |
| 133 | } | |
| 134 | } | |
| 135 | ||
| 136 | private readonly listeners = new Set<() => void>(); | |
| 137 | ||
| 138 | /** Called after every change to the book, whoever made it; returns how to stop listening. */ | |
| 139 | onChange(fn: () => void): () => void { | |
| 140 | this.listeners.add(fn); | |
| 141 | return () => this.listeners.delete(fn); | |
| 142 | } | |
| 143 | ||
| 144 | private save() { | |
| 145 | for (const fn of this.listeners) fn(); | |
| 146 | if (!this.file) return; | |
| 147 | mkdirSync(dirname(this.file), { recursive: true }); | |
| 148 | writeFileSync(`${this.file}.tmp`, JSON.stringify(this.data)); | |
| 149 | renameSync(`${this.file}.tmp`, this.file); | |
| 150 | } | |
| 151 | ||
| 152 | get startedAt(): number { | |
| 153 | return this.data.startedAt; | |
| 154 | } | |
| 155 | /** Oldest first. */ | |
| 156 | entries(): readonly Entry[] { | |
| 157 | return this.data.entries; | |
| 158 | } | |
| 159 | get snoozes(): Readonly<Record<string, number>> { | |
| 160 | return this.data.snoozes; | |
| 161 | } | |
| 162 | get every(): Readonly<Record<string, number>> { | |
| 163 | return this.data.every; | |
| 164 | } | |
| 165 | ||
| 166 | add(input: unknown): Entry { | |
| 167 | if (this.data.entries.length >= MAX_ENTRIES) throw new LogError("the log book is full"); | |
| 168 | const entry = { ...parseEntry(input, this.clock()), id: this.data.nextId++ } as Entry; | |
| 169 | this.data.entries.push(entry); | |
| 170 | this.data.entries.sort((a, b) => a.at - b.at || a.id - b.id); | |
| 171 | this.save(); | |
| 172 | return entry; | |
| 173 | } | |
| 174 | ||
| 175 | update(id: number, input: unknown): Entry { | |
| 176 | const i = this.data.entries.findIndex((e) => e.id === id); | |
| 177 | if (i < 0) throw new LogError("no such entry"); | |
| 178 | const entry = { ...parseEntry(input, this.clock()), id } as Entry; | |
| 179 | this.data.entries[i] = entry; | |
| 180 | this.data.entries.sort((a, b) => a.at - b.at || a.id - b.id); | |
| 181 | this.save(); | |
| 182 | return entry; | |
| 183 | } | |
| 184 | ||
| 185 | remove(id: number): boolean { | |
| 186 | const n = this.data.entries.length; | |
| 187 | this.data.entries = this.data.entries.filter((e) => e.id !== id); | |
| 188 | if (this.data.entries.length === n) return false; | |
| 189 | this.save(); | |
| 190 | return true; | |
| 191 | } | |
| 192 | ||
| 193 | snooze(reminder: string, hours: number) { | |
| 194 | if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(reminder) || !(hours > 0 && hours <= 24 * 14)) throw new LogError("snooze a reminder for up to 14 days"); | |
| 195 | this.data.snoozes[reminder] = this.clock() + hours * 3_600_000; | |
| 196 | this.save(); | |
| 197 | } | |
| 198 | ||
| 199 | /** Edit a reminder's cadence; null puts the profile's back. */ | |
| 200 | setEvery(reminder: string, hours: number | null) { | |
| 201 | if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(reminder)) throw new LogError("no such reminder"); | |
| 202 | if (hours === null) delete this.data.every[reminder]; | |
| 203 | else if (!(hours >= 1 && hours <= 24 * 120)) throw new LogError("every is 1 to 2880 hours"); | |
| 204 | else this.data.every[reminder] = hours; | |
| 205 | this.save(); | |
| 206 | } | |
| 207 | } |
Software/so101/src/care-page.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 1 | /** The grow care page: health strip, reminders, quick-add, charts against the target bands, and the log book as a timeline with stage bands. Every button is a form; the one script only refreshes it live. */ | |
| 2 | ||
| 3 | import { boltingWatch, currentStage, health, LABELS, ago, readings, reminders, snapshot, stageAt, stageHistory, totals, transplantPrompt, type Snapshot } from "./care-rules.ts"; | |
| 4 | import { ACTIONS, PROBLEMS, SYSTEMS, type Entry, type CareLog } from "./care-log.ts"; | |
| 5 | import { MEASURES, type Band, type Measure, type Profile } from "./care-profile.ts"; | |
| 6 | import { renderSignedIn, SIGNED_IN_STYLE, type SignedIn } from "./signed-in.ts"; | |
| 7 | import { esc } from "./story-markdown.ts"; | |
| 8 | ||
| 9 | const DAY = 86_400_000; | |
| 10 | ||
| 11 | /** Without it the page is whole; with it, a change anyone makes (the terminal, another tab) shows at once, unless a field is being typed in. */ | |
| 12 | const LIVE = `if (window.EventSource) new EventSource("/care/events").addEventListener("care", async () => { | |
| 13 | const f = document.activeElement; | |
| 14 | if (f && /^(INPUT|SELECT|TEXTAREA)$/.test(f.tagName)) return; | |
| 15 | const r = await fetch("/care", { headers: { accept: "text/html" } }); | |
| 16 | if (r.ok) document.querySelector("main").innerHTML = new DOMParser().parseFromString(await r.text(), "text/html").querySelector("main").innerHTML; | |
| 17 | });`; | |
| 18 | ||
| 19 | const STYLE = ` | |
| 20 | :root { color-scheme: dark light; --bg: #0b0d10; --panel: #11161d; --fg: #e8eaed; --dim: #9aa4ae; --line: #2a313a; --accent: #f0883e; --on-accent: #1a1206; --link: #79b8ff; --ok: #3fb950; --bad: #f85149; --band: #3fb95033; } | |
| 21 | @media (prefers-color-scheme: light) { :root { --bg: #fbfaf7; --panel: #fff; --fg: #1f2328; --dim: #59636e; --line: #d8dee4; --accent: #bc4c00; --on-accent: #fff; --link: #0969da; --ok: #1a7f37; --bad: #cf222e; --band: #1a7f3733; } } | |
| 22 | body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 ui-sans-serif, system-ui, sans-serif; } | |
| 23 | main { max-width: 60rem; margin: 0 auto; padding: 1rem; } | |
| 24 | h1 { margin: .5rem 0; } h2 { margin: 1.2rem 0 .5rem; font-size: 1.1rem; } | |
| 25 | .top { max-width: 60rem; margin: 0 auto; padding: .5rem 1rem 0; display: flex; justify-content: space-between; gap: 1rem; font-size: .9rem; color: var(--dim); } | |
| 26 | .health { border-left: 6px solid var(--ok); background: var(--panel); padding: .6rem .9rem; border-radius: 6px; } | |
| 27 | .health[data-ok="false"] { border-color: var(--bad); } | |
| 28 | .health p { margin: .1rem 0; } | |
| 29 | .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: .6rem .8rem; margin: .6rem 0; } | |
| 30 | ul.list { list-style: none; margin: 0; padding: 0; } ul.list li { display: flex; flex-wrap: wrap; gap: .4rem .8rem; align-items: center; justify-content: space-between; padding: .35rem 0; border-top: 1px solid var(--line); } ul.list li:first-child { border-top: 0; } | |
| 31 | .late { color: var(--bad); font-weight: 600; } .dim { color: var(--dim); font-size: .9rem; } | |
| 32 | button, select, input { font: inherit; min-height: 44px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); padding: 0 .7rem; box-sizing: border-box; } | |
| 33 | button { background: var(--accent); color: var(--on-accent); border: 0; font-weight: 650; padding: 0 1rem; } | |
| 34 | button.quiet { background: transparent; color: var(--link); border: 1px solid var(--line); } | |
| 35 | form { display: flex; flex-wrap: wrap; gap: .4rem; align-items: center; margin: .3rem 0; } form.inline { display: inline-flex; margin: 0; } | |
| 36 | input[type=number], input[type=text] { width: 8rem; } input.wide { flex: 1; min-width: 12rem; } | |
| 37 | .charts { display: grid; gap: .6rem; grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr)); } | |
| 38 | .chart svg { width: 100%; height: auto; display: block; } .chart h3 { margin: 0; font-size: .95rem; } | |
| 39 | .stage { margin-top: .8rem; padding: .2rem .5rem; background: var(--band); border-radius: 6px; font-weight: 600; } | |
| 40 | .alert { border: 1px solid var(--bad); border-radius: 8px; padding: .6rem .8rem; color: var(--bad); font-weight: 650; } | |
| 41 | a { color: var(--link); } a:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } | |
| 42 | .skip { position: absolute; left: -999px; } .skip:focus { left: .5rem; top: .5rem; background: var(--panel); padding: .5rem; z-index: 1; } | |
| 43 | `; | |
| 44 | ||
| 45 | /** One chart: the readings as a line, the target band as a shaded strip, the last 30 days. */ | |
| 46 | function chart(kind: Measure, snap: Snapshot, band: Band | undefined, now: number): string { | |
| 47 | const { name, unit } = LABELS[kind]; | |
| 48 | const pts = readings(snap.entries, kind).filter((r) => r.at > now - 30 * DAY && r.at <= now); | |
| 49 | const W = 320, H = 120, L = 30, R = 8, T = 8, B = 16; | |
| 50 | if (!pts.length) return `<div class="panel chart"><h3>${esc(name)}</h3><p class="dim">No readings yet${band ? `; typical ${band[0]}–${band[1]}${esc(unit)}` : ""}.</p></div>`; | |
| 51 | const values = pts.map((p) => p.value).concat(band ?? []); | |
| 52 | let lo = Math.min(...values), hi = Math.max(...values); | |
| 53 | const pad = (hi - lo || 1) * 0.15; | |
| 54 | lo -= pad; hi += pad; | |
| 55 | const x = (t: number) => L + ((t - (now - 30 * DAY)) / (30 * DAY)) * (W - L - R); | |
| 56 | const y = (v: number) => T + (1 - (v - lo) / (hi - lo)) * (H - T - B); | |
| 57 | const line = pts.map((p) => `${x(p.at).toFixed(1)},${y(p.value).toFixed(1)}`).join(" "); | |
| 58 | const strip = band ? `<rect x="${L}" y="${y(band[1]).toFixed(1)}" width="${W - L - R}" height="${(y(band[0]) - y(band[1])).toFixed(1)}" fill="var(--band)"/>` : ""; | |
| 59 | const last = pts[pts.length - 1]!; | |
| 60 | const dots = pts.map((p) => `<circle cx="${x(p.at).toFixed(1)}" cy="${y(p.value).toFixed(1)}" r="2.5" fill="var(--accent)"/>`).join(""); | |
| 61 | return `<div class="panel chart"><h3>${esc(name)}: ${last.value}${esc(unit)} <span class="dim">${ago(now - last.at)}${band ? `, typical ${band[0]}–${band[1]}` : ""}</span></h3> | |
| 62 | <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(name)} over the last 30 days${band ? `, typical band ${band[0]} to ${band[1]}` : ""}">${strip} | |
| 63 | <text x="2" y="${T + 8}" font-size="9" fill="var(--dim)">${hi.toFixed(1)}</text><text x="2" y="${H - B}" font-size="9" fill="var(--dim)">${lo.toFixed(1)}</text> | |
| 64 | <polyline points="${line}" fill="none" stroke="var(--accent)" stroke-width="1.5"/>${dots}</svg></div>`; | |
| 65 | } | |
| 66 | ||
| 67 | const when = (at: number) => new Date(at).toISOString().replace("T", " ").slice(0, 16) + " UTC"; | |
| 68 | ||
| 69 | function describe(e: Entry): string { | |
| 70 | switch (e.type) { | |
| 71 | case "measurement": return `${LABELS[e.kind].name} ${e.value}${LABELS[e.kind].unit}${e.source === "sensor" ? " (sensor)" : ""}`; | |
| 72 | case "observation": return e.text; | |
| 73 | case "problem": return `Problem: ${e.what}${e.text ? `. ${e.text}` : ""}`; | |
| 74 | case "action": | |
| 75 | if (e.transplant) return `Transplant: ${e.transplant.system}, ${e.transplant.litres} L, ${e.transplant.sites} sites, pump ${e.transplant.pump ? "yes" : "no"}`; | |
| 76 | if (e.what === "done") return `Done: ${e.ref}`; | |
| 77 | return `${e.what}${e.amount ? ` ${e.amount}${e.what === "harvest" ? " g" : e.what === "nutrients" ? " ml" : ""}` : ""}`; | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | const option = (v: string, label = v) => `<option value="${esc(v)}">${esc(label)}</option>`; | |
| 82 | const post = (action: string, fields: Record<string, string>, label: string, cls = "", name = "") => | |
| 83 | `<form class="inline" method="post" action="${action}">${Object.entries(fields).map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join("")}<button${cls ? ` class="${cls}"` : ""}${name ? ` aria-label="${esc(name)}"` : ""}>${esc(label)}</button></form>`; | |
| 84 | ||
| 85 | export interface CareView { | |
| 86 | profile: Profile; | |
| 87 | log: CareLog; | |
| 88 | now: number; | |
| 89 | /** May write: the owner (or a run on one's own machine). */ | |
| 90 | owner: boolean; | |
| 91 | signedIn: SignedIn | null; | |
| 92 | /** A refused form's message, shown at the top. */ | |
| 93 | error?: string | null; | |
| 94 | } | |
| 95 | ||
| 96 | export function renderCare({ profile, log, now, owner, signedIn, error }: CareView): string { | |
| 97 | const snap = snapshot(log); | |
| 98 | const spans = stageHistory(profile, snap.entries, snap.startedAt); | |
| 99 | const cur = currentStage(spans); | |
| 100 | const h = health(profile, snap, now); | |
| 101 | const due = reminders(profile, snap, now); | |
| 102 | const prompt = transplantPrompt(profile, snap, now); | |
| 103 | const bolt = boltingWatch(profile, snap, now); | |
| 104 | const sum = totals(snap.entries, now); | |
| 105 | const days = Math.floor((now - cur.from) / DAY); | |
| 106 | ||
| 107 | const quick = owner | |
| 108 | ? `<section class="panel" aria-labelledby="quick"><h2 id="quick" style="margin-top:0">Quick add</h2> | |
| 109 | <div style="display:flex;gap:.5rem;flex-wrap:wrap">${post("/care/log", { type: "action", what: "topoff" }, "Topped off")}${post("/care/log", { type: "action", what: "change" }, "Changed water")}${post("/care/log", { type: "action", what: "water" }, "Watered")}</div> | |
| 110 | <form method="post" action="/care/log"><input type="hidden" name="type" value="measurement"><label>Measure <select name="kind" aria-label="What was measured">${MEASURES.map((m) => option(m, LABELS[m].name)).join("")}</select></label><input type="number" name="value" step="any" required aria-label="Value" placeholder="value"><button>Log</button></form> | |
| 111 | <form method="post" action="/care/log"><input type="hidden" name="type" value="action"><select name="what" aria-label="Action">${ACTIONS.filter((a) => a !== "transplant" && a !== "done").map((a) => option(a)).join("")}</select><input type="number" name="amount" step="any" placeholder="ml or g" aria-label="Amount"><button>Log action</button></form> | |
| 112 | <form method="post" action="/care/log"><input type="hidden" name="type" value="observation"><input class="wide" type="text" name="text" required maxlength="1000" placeholder="Observation" aria-label="Observation"><button>Note</button></form> | |
| 113 | <form method="post" action="/care/log"><input type="hidden" name="type" value="problem"><select name="what" aria-label="Problem">${PROBLEMS.map((p) => option(p)).join("")}</select><input class="wide" type="text" name="text" maxlength="1000" placeholder="Detail (optional)" aria-label="Problem detail"><button>Report</button></form> | |
| 114 | ${spans.length === 1 ? `<form method="post" action="/care/log"><input type="hidden" name="type" value="action"><input type="hidden" name="what" value="transplant"><select name="system" aria-label="System type">${SYSTEMS.map((s) => option(s)).join("")}</select><input type="number" name="litres" step="any" required placeholder="litres" aria-label="Reservoir litres"><input type="number" name="sites" required placeholder="sites" aria-label="Sites"><label><input type="checkbox" name="pump" value="true"> pump</label><button>Transplant</button></form>` : ""} | |
| 115 | </section>` | |
| 116 | : ""; | |
| 117 | ||
| 118 | const dueRows = due | |
| 119 | .map((d) => { | |
| 120 | const late = d.overdueMs > 0 && !d.snoozedUntil; | |
| 121 | const state = d.snoozedUntil ? `snoozed until ${when(d.snoozedUntil)}` : late ? `overdue ${Math.max(1, Math.floor(d.overdueMs / 3_600_000))} h` : `due ${when(d.dueAt)}`; | |
| 122 | const acts = owner ? `<span>${post("/care/reminder", { id: d.reminder.id, action: "done" }, "Done")} ${post("/care/reminder", { id: d.reminder.id, action: "snooze", hours: "24" }, "Snooze 1 d", "quiet")}</span>` : ""; | |
| 123 | return `<li data-reminder="${esc(d.reminder.id)}"><span>${esc(d.reminder.label)}<br><span class="${late ? "late" : "dim"}">${esc(state)} · every ${d.everyHours} h</span></span>${acts}</li>`; | |
| 124 | }) | |
| 125 | .join(""); | |
| 126 | ||
| 127 | const kinds: Measure[] = ["ph", "ec", "waterTemp", "airTemp", "lightHours"]; | |
| 128 | const charts = kinds.map((k) => chart(k, snap, cur.stage.bands[k], now)).join(""); | |
| 129 | ||
| 130 | let lastStage = ""; | |
| 131 | const rows = [...snap.entries] | |
| 132 | .reverse() | |
| 133 | .map((e) => { | |
| 134 | const st = stageAt(spans, e.at).name; | |
| 135 | const band = st !== lastStage ? `<li class="stage">${esc(st)}</li>` : ""; | |
| 136 | lastStage = st; | |
| 137 | const del = owner ? post(`/care/log/${e.id}/delete`, {}, "Delete", "quiet") : ""; | |
| 138 | return `${band}<li data-entry="${e.id}" data-type="${e.type}"><span><span class="dim">${when(e.at)} · ${e.type}</span><br>${esc(describe(e))}</span>${del}</li>`; | |
| 139 | }) | |
| 140 | .join(""); | |
| 141 | ||
| 142 | return `<!doctype html> | |
| 143 | <html lang="en"> | |
| 144 | <head> | |
| 145 | <meta charset="utf-8"> | |
| 146 | <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> | |
| 147 | <title>Grow care · ${esc(profile.name)}</title> | |
| 148 | <meta name="description" content="Plant care for the grow box: reminders, a log book and charts against typical ranges."> | |
| 149 | <style>${STYLE}${SIGNED_IN_STYLE}</style> | |
| 150 | </head> | |
| 151 | <body> | |
| 152 | <a class="skip" href="#main">Skip to the care page</a> | |
| 153 | <nav class="top" aria-label="Grow"><span>${renderSignedIn(signedIn, "/care")}</span><span><a href="/">Workshop</a></span></nav> | |
| 154 | <main id="main"> | |
| 155 | ${error ? `<p class="alert" role="alert">${esc(error)}</p>` : ""} | |
| 156 | <h1>${esc(profile.name)} <span class="dim">· ${esc(cur.stage.name)}, day ${days}</span></h1> | |
| 157 | <section class="health" data-ok="${h.ok}" aria-label="Health">${h.lines.map((l) => `<p>${esc(l)}</p>`).join("")}</section> | |
| 158 | ${prompt ? `<p class="panel" data-prompt="transplant">${esc(prompt)}</p>` : ""}${bolt ? `<p class="panel" data-prompt="bolting">${esc(bolt)}</p>` : ""} | |
| 159 | ${quick} | |
| 160 | <h2>Reminders</h2><div class="panel"><ul class="list">${dueRows}</ul></div> | |
| 161 | <h2>Metrics</h2> | |
| 162 | <p class="dim">Typical ranges, not guaranteed. ${esc(profile.note)} Days since the last water change: ${sum.daysSinceChange ?? "none logged"}. Harvest so far: ${sum.harvestGrams} g. Light target ${profile.light.hours} h, warn above ${profile.light.warnAbove} h (bolting).</p> | |
| 163 | <div class="charts">${charts}</div> | |
| 164 | <h2>Log book</h2><div class="panel"><ul class="list">${rows || '<li class="dim">Nothing logged yet.</li>'}</ul></div> | |
| 165 | </main> | |
| 166 | <script>${LIVE}</script> | |
| 167 | </body> | |
| 168 | </html> | |
| 169 | `; | |
| 170 | } |
Software/so101/src/care-profile.ts added +134
| @@ -0,0 +1,134 @@ | ||
| 1 | /** | |
| 2 | * A plant profile is data: a JSON file in src/care-profiles (or the data dir's care-profiles) says the stages a plant goes | |
| 3 | * through, each with its target bands and its routine. Lettuce or basil is another file, not another code path. | |
| 4 | */ | |
| 5 | ||
| 6 | import { existsSync, readdirSync, readFileSync } from "node:fs"; | |
| 7 | import { join } from "node:path"; | |
| 8 | ||
| 9 | export const MEASURES = ["ph", "ec", "waterTemp", "airTemp", "level", "lightHours"] as const; | |
| 10 | export type Measure = (typeof MEASURES)[number]; | |
| 11 | ||
| 12 | export type Band = readonly [number, number]; | |
| 13 | ||
| 14 | export interface Reminder { | |
| 15 | id: string; | |
| 16 | label: string; | |
| 17 | everyHours: number; | |
| 18 | /** Replaces everyHours in a vertical tower, whose small reservoir drifts faster. */ | |
| 19 | tower?: number; | |
| 20 | /** Shown only when the transplant said so: a recirculating pump, or a tower. */ | |
| 21 | needs?: "pump" | "tower"; | |
| 22 | /** Log keys ("action:topoff", "measurement:ph") that count as done, besides "done:<id>". */ | |
| 23 | resets: string[]; | |
| 24 | } | |
| 25 | ||
| 26 | export interface Stage { | |
| 27 | id: string; | |
| 28 | name: string; | |
| 29 | bands: Partial<Record<Measure, Band>>; | |
| 30 | reminders: Reminder[]; | |
| 31 | transplantCheck?: { afterDays: Band; label: string }; | |
| 32 | } | |
| 33 | ||
| 34 | export interface Profile { | |
| 35 | id: string; | |
| 36 | name: string; | |
| 37 | note: string; | |
| 38 | light: { hours: number; warnAbove: number; dli: Band }; | |
| 39 | stages: Stage[]; | |
| 40 | } | |
| 41 | ||
| 42 | export class ProfileError extends Error {} | |
| 43 | ||
| 44 | const id = (v: unknown, what: string): string => { | |
| 45 | if (typeof v !== "string" || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(v)) throw new ProfileError(`${what}: an id is lowercase letters, digits and dashes`); | |
| 46 | return v; | |
| 47 | }; | |
| 48 | const words = (v: unknown, what: string, max = 200): string => { | |
| 49 | if (typeof v !== "string" || !v.trim() || v.length > max || /[\u0000-\u001f\u007f]/.test(v)) throw new ProfileError(`${what} is 1 to ${max} characters`); | |
| 50 | return v.trim(); | |
| 51 | }; | |
| 52 | const num = (v: unknown, what: string): number => { | |
| 53 | if (typeof v !== "number" || !Number.isFinite(v)) throw new ProfileError(`${what} is a number`); | |
| 54 | return v; | |
| 55 | }; | |
| 56 | const band = (v: unknown, what: string): Band => { | |
| 57 | if (!Array.isArray(v) || v.length !== 2) throw new ProfileError(`${what} is [low, high]`); | |
| 58 | const [lo, hi] = [num(v[0], what), num(v[1], what)]; | |
| 59 | if (lo > hi) throw new ProfileError(`${what}: low is above high`); | |
| 60 | return [lo, hi]; | |
| 61 | }; | |
| 62 | const obj = (v: unknown, what: string): Record<string, unknown> => { | |
| 63 | if (!v || typeof v !== "object" || Array.isArray(v)) throw new ProfileError(`${what} is an object`); | |
| 64 | return v as Record<string, unknown>; | |
| 65 | }; | |
| 66 | ||
| 67 | /** Any JSON → a profile; throws a ProfileError saying what is wrong. */ | |
| 68 | export function parseProfile(input: unknown): Profile { | |
| 69 | const p = obj(input, "a profile"); | |
| 70 | const light = obj(p.light, "light"); | |
| 71 | if (!Array.isArray(p.stages) || !p.stages.length || p.stages.length > 6) throw new ProfileError("a profile has 1 to 6 stages"); | |
| 72 | const stages = p.stages.map((raw): Stage => { | |
| 73 | const s = obj(raw, "a stage"); | |
| 74 | const bandsIn = obj(s.bands ?? {}, "bands"); | |
| 75 | const bands: Partial<Record<Measure, Band>> = {}; | |
| 76 | for (const [k, v] of Object.entries(bandsIn)) { | |
| 77 | if (!MEASURES.includes(k as Measure)) throw new ProfileError(`no such measure "${k}"`); | |
| 78 | bands[k as Measure] = band(v, `${k} band`); | |
| 79 | } | |
| 80 | if (!Array.isArray(s.reminders) || s.reminders.length > 20) throw new ProfileError("a stage has up to 20 reminders"); | |
| 81 | const seen = new Set<string>(); | |
| 82 | const reminders = s.reminders.map((rr): Reminder => { | |
| 83 | const r = obj(rr, "a reminder"); | |
| 84 | const rid = id(r.id, "a reminder"); | |
| 85 | if (seen.has(rid)) throw new ProfileError(`two reminders are called "${rid}"`); | |
| 86 | seen.add(rid); | |
| 87 | const hours = (v: unknown) => { | |
| 88 | const n = num(v, "everyHours"); | |
| 89 | if (n < 1 || n > 24 * 120) throw new ProfileError("everyHours is 1 to 2880"); | |
| 90 | return n; | |
| 91 | }; | |
| 92 | if (r.needs !== undefined && r.needs !== "pump" && r.needs !== "tower") throw new ProfileError('needs is "pump" or "tower"'); | |
| 93 | const resets = r.resets ?? []; | |
| 94 | if (!Array.isArray(resets) || !resets.every((k) => typeof k === "string" && /^[a-zA-Z]+:[a-zA-Z-]+$/.test(k))) throw new ProfileError("resets are keys like action:topoff"); | |
| 95 | return { id: rid, label: words(r.label, "a reminder's label"), everyHours: hours(r.everyHours), ...(r.tower !== undefined ? { tower: hours(r.tower) } : {}), ...(r.needs ? { needs: r.needs } : {}), resets: resets as string[] }; | |
| 96 | }); | |
| 97 | const tc = s.transplantCheck === undefined ? undefined : obj(s.transplantCheck, "transplantCheck"); | |
| 98 | return { | |
| 99 | id: id(s.id, "a stage"), | |
| 100 | name: words(s.name, "a stage's name", 60), | |
| 101 | bands, | |
| 102 | reminders, | |
| 103 | ...(tc ? { transplantCheck: { afterDays: band(tc.afterDays, "afterDays"), label: words(tc.label, "the check's label") } } : {}), | |
| 104 | }; | |
| 105 | }); | |
| 106 | if (new Set(stages.map((s) => s.id)).size !== stages.length) throw new ProfileError("two stages share an id"); | |
| 107 | return { | |
| 108 | id: id(p.id, "a profile"), | |
| 109 | name: words(p.name, "a profile's name", 60), | |
| 110 | note: words(p.note ?? "Typical ranges, not guaranteed.", "the note", 400), | |
| 111 | light: { hours: num(light.hours, "light hours"), warnAbove: num(light.warnAbove, "light warnAbove"), dli: band(light.dli, "dli") }, | |
| 112 | stages, | |
| 113 | }; | |
| 114 | } | |
| 115 | ||
| 116 | /** Every *.json in a directory that parses; one that does not is named on stderr and skipped. */ | |
| 117 | export function loadProfiles(...dirs: string[]): Profile[] { | |
| 118 | const out = new Map<string, Profile>(); | |
| 119 | for (const dir of dirs) { | |
| 120 | if (!existsSync(dir)) continue; | |
| 121 | for (const file of readdirSync(dir).filter((f) => f.endsWith(".json")).sort()) { | |
| 122 | try { | |
| 123 | const p = parseProfile(JSON.parse(readFileSync(join(dir, file), "utf8"))); | |
| 124 | out.set(p.id, p); | |
| 125 | } catch (err) { | |
| 126 | console.error(`care: ${join(dir, file)} unusable (${(err as Error).message})`); | |
| 127 | } | |
| 128 | } | |
| 129 | } | |
| 130 | return [...out.values()]; | |
| 131 | } | |
| 132 | ||
| 133 | /** The profiles that ship with the app. */ | |
| 134 | export const BUILT_IN_DIR = new URL("./care-profiles", import.meta.url).pathname; |
Software/so101/src/care-profiles/spinach.json added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | { | |
| 2 | "id": "spinach", | |
| 3 | "name": "Spinach", | |
| 4 | "note": "Typical ranges, not guaranteed: Cornell CEA spinach report, Organic Seed Alliance, Hydrobuilder; the rockwool stage and the timeline are grower consensus.", | |
| 5 | "light": { "hours": 12, "warnAbove": 14, "dli": [12, 17] }, | |
| 6 | "timeline": { "germinateDays": 3, "respaceDay": 9, "babyLeafDays": [14, 16], "fullLeafDays": [30, 45] }, | |
| 7 | "stages": [ | |
| 8 | { | |
| 9 | "id": "seedling", | |
| 10 | "name": "Rockwool seedling", | |
| 11 | "bands": { "ph": [5.5, 6.0], "ec": [0.5, 1.4], "airTemp": [18, 24], "lightHours": [10, 14] }, | |
| 12 | "reminders": [ | |
| 13 | { "id": "moisture", "label": "Check cube moisture (a light cube needs bottom water); vent or remove the dome", "everyHours": 24, "resets": ["action:water"] }, | |
| 14 | { "id": "light", "label": "Light ran", "everyHours": 24 }, | |
| 15 | { "id": "bottom-water", "label": "Bottom-water or refill the tray at this stage's EC and pH, then log it", "everyHours": 60, "resets": ["action:water", "action:topoff"] }, | |
| 16 | { "id": "thin", "label": "Thin to the strongest seedling per cube once true leaves show", "everyHours": 168, "resets": ["action:thin"] } | |
| 17 | ], | |
| 18 | "transplantCheck": { "afterDays": [14, 21], "label": "Roots out of the cube bottom and 2-4 true leaves?" } | |
| 19 | }, | |
| 20 | { | |
| 21 | "id": "hydroponic", | |
| 22 | "name": "Hydroponic", | |
| 23 | "bands": { "ph": [5.5, 6.5], "ec": [1.6, 2.0], "waterTemp": [18, 20], "airTemp": [20, 24], "lightHours": [10, 14] }, | |
| 24 | "reminders": [ | |
| 25 | { "id": "light", "label": "Light ran", "everyHours": 24 }, | |
| 26 | { "id": "level", "label": "Water level; look for wilting", "everyHours": 24, "resets": ["measurement:level", "action:topoff"] }, | |
| 27 | { "id": "pump", "label": "Pump ran? Top emitter clear, every level wet", "everyHours": 24, "needs": "pump", "resets": ["action:pumpcheck"] }, | |
| 28 | { "id": "measure", "label": "Measure pH, EC and water temperature", "everyHours": 60, "tower": 36, "resets": ["measurement:ph", "measurement:ec", "measurement:waterTemp"] }, | |
| 29 | { "id": "topoff", "label": "Top off with plain water", "everyHours": 60, "tower": 24, "resets": ["action:topoff", "action:change"] }, | |
| 30 | { "id": "calibrate", "label": "Calibrate the pH probe", "everyHours": 168 }, | |
| 31 | { "id": "air-stone", "label": "Clean the air stone", "everyHours": 168, "resets": ["action:airstone"] }, | |
| 32 | { "id": "roots", "label": "Check the roots (brown or slimy = Pythium); thin or harvest", "everyHours": 168 }, | |
| 33 | { "id": "tower", "label": "Tower: top emitter not clogged, every level wet, no algae on lit parts", "everyHours": 168, "needs": "tower" }, | |
| 34 | { "id": "change", "label": "Full reservoir change and wipe down", "everyHours": 336, "resets": ["action:change"] } | |
| 35 | ] | |
| 36 | }, | |
| 37 | { | |
| 38 | "id": "harvest", | |
| 39 | "name": "Harvest", | |
| 40 | "bands": { "ph": [5.5, 6.5], "ec": [1.8, 2.3], "waterTemp": [18, 20], "airTemp": [20, 24], "lightHours": [10, 14] }, | |
| 41 | "reminders": [ | |
| 42 | { "id": "light", "label": "Light ran", "everyHours": 24 }, | |
| 43 | { "id": "level", "label": "Water level; look for wilting", "everyHours": 24, "resets": ["measurement:level", "action:topoff"] }, | |
| 44 | { "id": "pump", "label": "Pump ran?", "everyHours": 24, "needs": "pump", "resets": ["action:pumpcheck"] }, | |
| 45 | { "id": "measure", "label": "Measure pH, EC and water temperature", "everyHours": 60, "tower": 36, "resets": ["measurement:ph", "measurement:ec", "measurement:waterTemp"] }, | |
| 46 | { "id": "bolting", "label": "Stalk forming? Look at the side camera (watch when air has been above 24 C)", "everyHours": 48 }, | |
| 47 | { "id": "harvest", "label": "Cut and come again: harvest outer leaves", "everyHours": 168, "resets": ["action:harvest"] }, | |
| 48 | { "id": "change", "label": "Full reservoir change and wipe down", "everyHours": 336, "resets": ["action:change"] } | |
| 49 | ] | |
| 50 | } | |
| 51 | ] | |
| 52 | } |
Software/so101/src/care-routes.ts added +118
| @@ -0,0 +1,118 @@ | ||
| 1 | /** The grow care routes: /care (the page), /care/api (the same as JSON), and the writes, which are the owner's. */ | |
| 2 | ||
| 3 | import type { IncomingMessage, ServerResponse } from "node:http"; | |
| 4 | import { boltingWatch, currentStage, health, reminders, snapshot, stageHistory, totals, transplantPrompt } from "./care-rules.ts"; | |
| 5 | import { LogError, type CareLog } from "./care-log.ts"; | |
| 6 | import { renderCare } from "./care-page.ts"; | |
| 7 | import type { Profile } from "./care-profile.ts"; | |
| 8 | import type { SignedIn } from "./signed-in.ts"; | |
| 9 | ||
| 10 | export interface CareContext { | |
| 11 | profile: Profile; | |
| 12 | log: CareLog; | |
| 13 | /** null when the request may not write; the reader is told who they are for the page. */ | |
| 14 | who: (req: IncomingMessage) => { owner: boolean; signedIn: SignedIn | null; known: boolean }; | |
| 15 | readBody: (req: IncomingMessage, limit?: number) => Promise<Buffer>; | |
| 16 | now?: () => number; | |
| 17 | } | |
| 18 | ||
| 19 | const NUMBERS = new Set(["value", "amount", "litres", "sites", "hours"]); | |
| 20 | ||
| 21 | /** A JSON body, or a form's fields with the numbers made numbers. */ | |
| 22 | function fields(req: IncomingMessage, body: string): Record<string, unknown> { | |
| 23 | if ((req.headers["content-type"] ?? "").includes("json")) { | |
| 24 | const v = JSON.parse(body || "null"); | |
| 25 | if (!v || typeof v !== "object" || Array.isArray(v)) throw new LogError("send an object"); | |
| 26 | return v as Record<string, unknown>; | |
| 27 | } | |
| 28 | const out: Record<string, unknown> = {}; | |
| 29 | for (const [k, v] of new URLSearchParams(body)) out[k] = NUMBERS.has(k) ? (v === "" ? undefined : Number(v)) : k === "pump" ? v === "true" : v; | |
| 30 | return out; | |
| 31 | } | |
| 32 | ||
| 33 | /** True when the path was this module's and has been answered. */ | |
| 34 | export async function handleCare(req: IncomingMessage, res: ServerResponse, pathname: string, ctx: CareContext): Promise<boolean> { | |
| 35 | if (pathname !== "/care" && !pathname.startsWith("/care/")) return false; | |
| 36 | const now = ctx.now?.() ?? Date.now(); | |
| 37 | const me = ctx.who(req); | |
| 38 | const send = (status: number, type: string, body: string, extra: Record<string, string> = {}) => { | |
| 39 | res.writeHead(status, { "content-type": type, "cache-control": "no-store", ...extra }); | |
| 40 | res.end(body); | |
| 41 | }; | |
| 42 | const json = (status: number, body: unknown) => send(status, "application/json", JSON.stringify(body)); | |
| 43 | ||
| 44 | if (req.method === "GET" && pathname === "/care") { | |
| 45 | send(200, "text/html; charset=utf-8", renderCare({ profile: ctx.profile, log: ctx.log, now, owner: me.owner, signedIn: me.signedIn, error: new URL(req.url ?? "/", "http://x").searchParams.get("error")?.slice(0, 200) })); | |
| 46 | return true; | |
| 47 | } | |
| 48 | if (req.method === "GET" && pathname === "/care/events") { | |
| 49 | res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no" }); | |
| 50 | res.write("retry: 5000\n\n"); | |
| 51 | const stop = ctx.log.onChange(() => res.write("event: care\ndata: changed\n\n")); | |
| 52 | const beat = setInterval(() => res.write(": \n\n"), 25_000); | |
| 53 | res.on("close", () => { stop(); clearInterval(beat); }); | |
| 54 | return true; | |
| 55 | } | |
| 56 | if (req.method === "GET" && pathname === "/care/api") { | |
| 57 | const snap = snapshot(ctx.log); | |
| 58 | const spans = stageHistory(ctx.profile, snap.entries, snap.startedAt); | |
| 59 | json(200, { | |
| 60 | profile: ctx.profile.id, | |
| 61 | stage: currentStage(spans).stage.id, | |
| 62 | stages: spans.map((s) => ({ id: s.stage.id, from: s.from })), | |
| 63 | health: health(ctx.profile, snap, now), | |
| 64 | reminders: reminders(ctx.profile, snap, now).map((d) => ({ id: d.reminder.id, label: d.reminder.label, everyHours: d.everyHours, dueAt: d.dueAt, snoozedUntil: d.snoozedUntil })), | |
| 65 | prompts: [transplantPrompt(ctx.profile, snap, now), boltingWatch(ctx.profile, snap, now)].filter(Boolean), | |
| 66 | totals: totals(snap.entries, now), | |
| 67 | entries: snap.entries, | |
| 68 | }); | |
| 69 | return true; | |
| 70 | } | |
| 71 | ||
| 72 | const entry = /^\/care\/log(?:\/(\d+)(\/delete)?)?$/.exec(pathname); | |
| 73 | const reminder = pathname === "/care/reminder"; | |
| 74 | if (!entry && !reminder) { | |
| 75 | json(404, { error: "no such route" }); | |
| 76 | return true; | |
| 77 | } | |
| 78 | if (req.method === "GET") return json(405, { error: "POST here" }), true; | |
| 79 | if (!me.owner) { | |
| 80 | json(me.known ? 403 : 401, { error: "only the owner may change the log book" }); | |
| 81 | return true; | |
| 82 | } | |
| 83 | const form = !(req.headers["content-type"] ?? "").includes("json"); | |
| 84 | try { | |
| 85 | let raw: Buffer; | |
| 86 | try { | |
| 87 | raw = await ctx.readBody(req, 8192); | |
| 88 | } catch { | |
| 89 | json(413, { error: "too long" }); | |
| 90 | return true; | |
| 91 | } | |
| 92 | const input = fields(req, raw.toString("utf8")); | |
| 93 | let result: unknown = { ok: true }; | |
| 94 | const id = entry?.[1] ? Number(entry[1]) : null; | |
| 95 | if (reminder) { | |
| 96 | const rid = String(input.id ?? ""); | |
| 97 | if (input.action === "done") result = ctx.log.add({ type: "action", what: "done", ref: rid }); | |
| 98 | else if (input.action === "snooze") ctx.log.snooze(rid, Number(input.hours ?? 24)); | |
| 99 | else if (input.action === "every") ctx.log.setEvery(rid, input.hours === null ? null : Number(input.hours)); | |
| 100 | else throw new LogError("action is done, snooze or every"); | |
| 101 | } else if (id === null) { | |
| 102 | if (req.method !== "POST") return json(405, { error: "POST adds an entry" }), true; | |
| 103 | result = ctx.log.add(input); | |
| 104 | } else if (entry![2] || req.method === "DELETE") { | |
| 105 | if (!ctx.log.remove(id)) throw new LogError("no such entry"); | |
| 106 | } else if (req.method === "PUT") { | |
| 107 | result = ctx.log.update(id, input); | |
| 108 | } else throw new LogError("PUT edits, DELETE removes"); | |
| 109 | if (form) send(303, "text/plain", "", { location: "/care" }); | |
| 110 | else json(200, result); | |
| 111 | } catch (err) { | |
| 112 | const msg = err instanceof LogError ? err.message : err instanceof SyntaxError ? "send JSON" : null; | |
| 113 | if (msg !== null && form) send(303, "text/plain", "", { location: `/care?error=${encodeURIComponent(msg)}` }); | |
| 114 | else if (msg !== null) json(400, { error: msg }); | |
| 115 | else throw err; | |
| 116 | } | |
| 117 | return true; | |
| 118 | } |
Software/so101/src/care-rules.ts added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | /** | |
| 2 | * What the log and the profile say together: the current stage, the reminders and when each is due, the target-band | |
| 3 | * checks, and the health strip. Everything here is a pure function of (profile, log, now). | |
| 4 | */ | |
| 5 | ||
| 6 | import type { Band, Measure, Profile, Reminder, Stage } from "./care-profile.ts"; | |
| 7 | import { keyOf, type Entry, type CareLog, type Reading, type Transplant } from "./care-log.ts"; | |
| 8 | ||
| 9 | const HOUR = 3_600_000; | |
| 10 | const DAY = 24 * HOUR; | |
| 11 | ||
| 12 | export interface Snapshot { | |
| 13 | entries: readonly Entry[]; | |
| 14 | startedAt: number; | |
| 15 | snoozes: Readonly<Record<string, number>>; | |
| 16 | every: Readonly<Record<string, number>>; | |
| 17 | } | |
| 18 | export const snapshot = (log: CareLog): Snapshot => ({ entries: log.entries(), startedAt: log.startedAt, snoozes: log.snoozes, every: log.every }); | |
| 19 | ||
| 20 | export interface StageSpan { | |
| 21 | stage: Stage; | |
| 22 | from: number; | |
| 23 | } | |
| 24 | ||
| 25 | const transplantOf = (entries: readonly Entry[]): { at: number; t: Transplant } | null => { | |
| 26 | for (const e of entries) if (e.type === "action" && e.what === "transplant" && e.transplant) return { at: e.at, t: e.transplant }; | |
| 27 | return null; | |
| 28 | }; | |
| 29 | ||
| 30 | /** The stages the plant has been through, oldest first: the transplant moves it on and the history stays. */ | |
| 31 | export function stageHistory(profile: Profile, entries: readonly Entry[], startedAt: number): StageSpan[] { | |
| 32 | const [seedling, hydro, harvest] = profile.stages; | |
| 33 | const first = entries.find((e) => e.type === "action" && e.what === "sow")?.at ?? Math.min(startedAt, entries[0]?.at ?? startedAt); | |
| 34 | const spans: StageSpan[] = [{ stage: seedling!, from: first }]; | |
| 35 | const moved = transplantOf(entries); | |
| 36 | if (moved && hydro) { | |
| 37 | spans.push({ stage: hydro, from: moved.at }); | |
| 38 | const cut = entries.find((e) => e.type === "action" && e.what === "harvest" && e.at >= moved.at); | |
| 39 | if (cut && harvest) spans.push({ stage: harvest, from: cut.at }); | |
| 40 | } | |
| 41 | return spans; | |
| 42 | } | |
| 43 | ||
| 44 | export const currentStage = (spans: readonly StageSpan[]): StageSpan => spans[spans.length - 1]!; | |
| 45 | export const stageAt = (spans: readonly StageSpan[], at: number): Stage => (spans.filter((s) => s.from <= at).pop() ?? spans[0]!).stage; | |
| 46 | ||
| 47 | export interface Due { | |
| 48 | reminder: Reminder; | |
| 49 | everyHours: number; | |
| 50 | dueAt: number; | |
| 51 | overdueMs: number; | |
| 52 | snoozedUntil: number | null; | |
| 53 | } | |
| 54 | ||
| 55 | /** Each reminder of the current stage with when it falls due: the cadence after the last matching log entry, or after the stage began. */ | |
| 56 | export function reminders(profile: Profile, snap: Snapshot, now: number): Due[] { | |
| 57 | const spans = stageHistory(profile, snap.entries, snap.startedAt); | |
| 58 | const { stage, from } = currentStage(spans); | |
| 59 | const moved = transplantOf(snap.entries)?.t; | |
| 60 | return stage.reminders | |
| 61 | .filter((r) => !r.needs || (r.needs === "pump" ? moved?.pump : moved?.system === "vertical tower")) | |
| 62 | .map((reminder) => { | |
| 63 | const keys = new Set([`done:${reminder.id}`, ...reminder.resets]); | |
| 64 | let last = from; | |
| 65 | for (const e of snap.entries) if (e.at <= now && e.at >= from && keys.has(keyOf(e) ?? "")) last = Math.max(last, e.at); | |
| 66 | const everyHours = snap.every[reminder.id] ?? (moved?.system === "vertical tower" ? reminder.tower : undefined) ?? reminder.everyHours; | |
| 67 | const dueAt = last + everyHours * HOUR; | |
| 68 | const until = snap.snoozes[reminder.id]; | |
| 69 | return { reminder, everyHours, dueAt, overdueMs: now - dueAt, snoozedUntil: until && until > now ? until : null }; | |
| 70 | }) | |
| 71 | .sort((a, b) => a.dueAt - b.dueAt); | |
| 72 | } | |
| 73 | ||
| 74 | /** Overdue and not snoozed. */ | |
| 75 | export const overdue = (dues: readonly Due[]): Due[] => dues.filter((d) => d.overdueMs > 0 && !d.snoozedUntil); | |
| 76 | ||
| 77 | export type Verdict = "in" | "below" | "above"; | |
| 78 | export const check = (value: number, band: Band): Verdict => (value < band[0] ? "below" : value > band[1] ? "above" : "in"); | |
| 79 | ||
| 80 | /** The readings of one kind, oldest first. */ | |
| 81 | export const readings = (entries: readonly Entry[], kind: Measure): Reading[] => | |
| 82 | entries.flatMap((e) => (e.type === "measurement" && e.kind === kind ? [{ kind, value: e.value, at: e.at, source: e.source }] : [])); | |
| 83 | ||
| 84 | export const LABELS: Record<Measure, { name: string; unit: string }> = { | |
| 85 | ph: { name: "pH", unit: "" }, | |
| 86 | ec: { name: "EC", unit: " mS/cm" }, | |
| 87 | waterTemp: { name: "Water temp", unit: " °C" }, | |
| 88 | airTemp: { name: "Air temp", unit: " °C" }, | |
| 89 | level: { name: "Level", unit: " %" }, | |
| 90 | lightHours: { name: "Light", unit: " h" }, | |
| 91 | }; | |
| 92 | ||
| 93 | export const ago = (ms: number): string => { | |
| 94 | if (ms < HOUR) return "just now"; | |
| 95 | if (ms < DAY) return `${Math.floor(ms / HOUR)} h ago`; | |
| 96 | return `${Math.floor(ms / DAY)} d ago`; | |
| 97 | }; | |
| 98 | const span = (ms: number): string => (ms < DAY ? `${Math.max(1, Math.floor(ms / HOUR))} h` : `${Math.floor(ms / DAY)} d`); | |
| 99 | ||
| 100 | export interface Health { | |
| 101 | ok: boolean; | |
| 102 | /** Green: ["All in band, nothing overdue"]; otherwise what is off. */ | |
| 103 | lines: string[]; | |
| 104 | } | |
| 105 | ||
| 106 | /** The health strip: green when every latest reading is in band and no reminder is overdue; otherwise it names what is off. */ | |
| 107 | export function health(profile: Profile, snap: Snapshot, now: number): Health { | |
| 108 | const { stage } = currentStage(stageHistory(profile, snap.entries, snap.startedAt)); | |
| 109 | const lines: string[] = []; | |
| 110 | for (const [kind, band] of Object.entries(stage.bands) as [Measure, Band][]) { | |
| 111 | const last = readings(snap.entries, kind).filter((r) => r.at <= now).pop(); | |
| 112 | if (!last) continue; | |
| 113 | const v = check(last.value, band); | |
| 114 | if (v === "in") continue; | |
| 115 | const { name, unit } = LABELS[kind]; | |
| 116 | lines.push(`${name} ${last.value}${unit}, ${v} ${v === "above" ? band[1] : band[0]}, measured ${ago(now - last.at)}`); | |
| 117 | } | |
| 118 | for (const d of overdue(reminders(profile, snap, now))) lines.push(`${d.reminder.label.split(/[;(,]/)[0]!.trim()} is ${span(d.overdueMs)} overdue`); | |
| 119 | return lines.length ? { ok: false, lines } : { ok: true, lines: ["All readings in band, nothing overdue"] }; | |
| 120 | } | |
| 121 | ||
| 122 | export interface Totals { | |
| 123 | daysSinceChange: number | null; | |
| 124 | harvestGrams: number; | |
| 125 | } | |
| 126 | export function totals(entries: readonly Entry[], now: number): Totals { | |
| 127 | const change = entries.filter((e) => e.type === "action" && e.what === "change" && e.at <= now).pop(); | |
| 128 | const harvestGrams = entries.reduce((sum, e) => sum + (e.type === "action" && e.what === "harvest" ? (e.amount ?? 0) : 0), 0); | |
| 129 | return { daysSinceChange: change ? Math.floor((now - change.at) / DAY) : null, harvestGrams }; | |
| 130 | } | |
| 131 | ||
| 132 | /** "Ready to transplant?" from the sow date, while still a seedling; the owner confirms by logging the transplant. */ | |
| 133 | export function transplantPrompt(profile: Profile, snap: Snapshot, now: number): string | null { | |
| 134 | const spans = stageHistory(profile, snap.entries, snap.startedAt); | |
| 135 | const cur = currentStage(spans); | |
| 136 | const check = cur.stage.transplantCheck; | |
| 137 | if (!check || spans.length > 1) return null; | |
| 138 | const days = Math.floor((now - cur.from) / DAY); | |
| 139 | return days >= check.afterDays[0] ? `Day ${days} from sowing: ${check.label}` : null; | |
| 140 | } | |
| 141 | ||
| 142 | /** Bolting watch in the harvest stage: air above 24 °C in the last 3 days. */ | |
| 143 | export function boltingWatch(profile: Profile, snap: Snapshot, now: number): string | null { | |
| 144 | if (currentStage(stageHistory(profile, snap.entries, snap.startedAt)).stage.id !== "harvest") return null; | |
| 145 | const hot = readings(snap.entries, "airTemp").some((r) => r.at > now - 3 * DAY && r.value > 24); | |
| 146 | return hot ? "Air was above 24 °C lately: is a stalk forming?" : null; | |
| 147 | } |
Software/so101/src/care-terminal.test.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | import { afterEach, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { CareLog } from "./care-log.ts"; | |
| 6 | import { BUILT_IN_DIR, loadProfiles } from "./care-profile.ts"; | |
| 7 | import { CARE_USAGE, careCommand, careLines } from "./care-terminal.ts"; | |
| 8 | import { sign } from "./identity.ts"; | |
| 9 | import { Lobby } from "./lobby.ts"; | |
| 10 | import { startRelay, type RunningRelay } from "./relay.ts"; | |
| 11 | import { careReader, Door, typed, emptyRoom } from "./terminal.ts"; | |
| 12 | ||
| 13 | const KEY = "k".repeat(64); | |
| 14 | const profile = loadProfiles(BUILT_IN_DIR).find((p) => p.id === "spinach")!; | |
| 15 | const as = (name: string, role: "user" | "admin") => { | |
| 16 | const identity = `id-${name}|${name}|${role}|${Date.now() + 600_000}`; | |
| 17 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 18 | }; | |
| 19 | const terminal = (port: number, name: string | null, role: "user" | "admin" = "user"): Record<string, string> => | |
| 20 | name ? { PORT: String(port), FORGE_APP_IDENTITY_KEY: KEY, FORGE_APP_USER_ID: `id-${name}`, FORGE_APP_USER: name, FORGE_APP_USER_ROLE: role } : { PORT: String(port) }; | |
| 21 | ||
| 22 | let dir = ""; | |
| 23 | let relay: RunningRelay | undefined; | |
| 24 | let lobby: Lobby | undefined; | |
| 25 | afterEach(async () => { | |
| 26 | await relay?.close(); | |
| 27 | lobby?.close(); | |
| 28 | if (dir) rmSync(dir, { recursive: true, force: true }); | |
| 29 | dir = ""; | |
| 30 | relay = lobby = undefined; | |
| 31 | }); | |
| 32 | ||
| 33 | async function start() { | |
| 34 | dir = mkdtempSync(join(tmpdir(), "so101-care-")); | |
| 35 | lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json"), countsFile: join(dir, "visitors.json") }); | |
| 36 | const log = new CareLog(); | |
| 37 | relay = await startRelay({ port: 0, simulation: "http://127.0.0.1:1", lobby, care: { log, profile } }); | |
| 38 | return { log, port: relay.port, base: `http://127.0.0.1:${relay.port}` }; | |
| 39 | } | |
| 40 | ||
| 41 | test("a /care line parses into the ask the page's buttons make", () => { | |
| 42 | expect(typed(emptyRoom(), "/care")).toEqual({ care: { method: "GET", path: "/care/api" } }); | |
| 43 | expect(typed(emptyRoom(), "/care log ph 6.1")).toEqual({ care: { method: "POST", path: "/care/log", body: { type: "measurement", kind: "ph", value: 6.1 } } }); | |
| 44 | expect(typed(emptyRoom(), "/care did harvest 40")).toEqual({ care: { method: "POST", path: "/care/log", body: { type: "action", what: "harvest", amount: 40 } } }); | |
| 45 | expect(typed(emptyRoom(), "/care problem tip burn on the top row")).toEqual({ care: { method: "POST", path: "/care/log", body: { type: "problem", what: "tip burn", text: "on the top row" } } }); | |
| 46 | expect(typed(emptyRoom(), "/care snooze roots 48")).toEqual({ care: { method: "POST", path: "/care/reminder", body: { id: "roots", action: "snooze", hours: 48 } } }); | |
| 47 | expect(typed(emptyRoom(), "/care delete 3")).toMatchObject({ care: { method: "DELETE", path: "/care/log/3" } }); | |
| 48 | for (const bad of ["/care log ph", "/care log salt 1", "/care did transplant", "/care note", "/care delete x", "/care frob"]) expect(typed(emptyRoom(), bad)).toEqual({ print: CARE_USAGE }); | |
| 49 | expect(careCommand([], "")).toEqual({ method: "GET", path: "/care/api" }); | |
| 50 | }); | |
| 51 | ||
| 52 | test("the terminal: a guest reads and is refused writes; the owner writes, and the page and /care/api show it", async () => { | |
| 53 | const { port, base } = await start(); | |
| 54 | const run = async (env: Record<string, string>, line: string) => { | |
| 55 | const printed: string[] = []; | |
| 56 | new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, null, null, null, null, null, null, null, null, null, null, careReader(env)).input(line); | |
| 57 | for (let i = 0; i < 100 && !printed.length; i++) await Bun.sleep(20); | |
| 58 | return printed; | |
| 59 | }; | |
| 60 | const guest = terminal(port, null); | |
| 61 | const plain = terminal(port, "eve"); | |
| 62 | const owner = terminal(port, "trevato", "admin"); | |
| 63 | expect((await run(guest, "/care"))[0]).toContain("Stage: seedling"); | |
| 64 | for (const env of [guest, plain]) { | |
| 65 | expect((await run(env, "/care did topoff"))[0]).toMatch(/^error: only the owner/); | |
| 66 | expect((await run(env, "/care delete 1"))[0]).toMatch(/^error: only the owner/); | |
| 67 | } | |
| 68 | expect((await (await fetch(`${base}/care/api`)).json() as { entries: unknown[] }).entries).toHaveLength(0); | |
| 69 | expect(await run(owner, "/care log ph 7.1")).toEqual(["care saved"]); | |
| 70 | expect(await run(owner, "/care note first true leaves")).toEqual(["care saved"]); | |
| 71 | const api = (await (await fetch(`${base}/care/api`)).json()) as { entries: { id: number }[]; health: { lines: string[] } }; | |
| 72 | expect(api.entries).toHaveLength(2); | |
| 73 | expect(api.health.lines.join()).toContain("pH 7.1, above 6,"); | |
| 74 | expect(await (await fetch(`${base}/care`)).text()).toContain("first true leaves"); | |
| 75 | const read = await run(guest, "/care"); | |
| 76 | expect(read.some((l) => l.includes("ph 7.1"))).toBe(true); | |
| 77 | expect(await run(owner, `/care delete ${api.entries[0]!.id}`)).toEqual(["care saved"]); | |
| 78 | expect((await (await fetch(`${base}/care/api`)).json() as { entries: unknown[] }).entries).toHaveLength(1); | |
| 79 | expect(await run(owner, "/care done light")).toEqual(["care saved"]); | |
| 80 | }); | |
| 81 | ||
| 82 | test("through the relay: a cross-site write is refused, a guest is 401, a plain user 403, an oversize body 413", async () => { | |
| 83 | const { log, base } = await start(); | |
| 84 | const body = JSON.stringify({ type: "observation", text: "hi" }); | |
| 85 | const post = (headers: Record<string, string>, payload = body) => fetch(`${base}/care/log`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: payload }); | |
| 86 | expect((await post({ ...as("trevato", "admin"), "sec-fetch-site": "cross-site" })).status).toBe(403); | |
| 87 | expect((await post({ ...as("trevato", "admin"), origin: "https://evil.example" })).status).toBe(403); | |
| 88 | expect((await post({})).status).toBe(401); | |
| 89 | expect((await post(as("eve", "user"))).status).toBe(403); | |
| 90 | expect(log.entries()).toHaveLength(0); | |
| 91 | expect((await post(as("trevato", "admin"))).status).toBe(200); | |
| 92 | // the cap counts bytes read: an 8193-byte body is refused though it says nothing about its length up front | |
| 93 | const big = JSON.stringify({ type: "observation", text: "x".repeat(8200) }); | |
| 94 | expect((await post(as("trevato", "admin"), big)).status).toBe(413); | |
| 95 | expect(log.entries()).toHaveLength(1); | |
| 96 | expect(careLines({ stage: "seedling", health: { ok: true, lines: [] }, reminders: [], entries: [] })[0]).toContain("healthy"); | |
| 97 | }); |
Software/so101/src/care-terminal.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * The care app at the terminal: /care reads the same /care/api the page does, and its writes are the same POSTs the | |
| 3 | * page's buttons make, so the server (and only it) decides who may. This module only parses a line and words an answer. | |
| 4 | */ | |
| 5 | ||
| 6 | import { ACTIONS, PROBLEMS } from "./care-log.ts"; | |
| 7 | import { MEASURES } from "./care-profile.ts"; | |
| 8 | ||
| 9 | export interface CareAsk { | |
| 10 | method: "GET" | "POST" | "DELETE"; | |
| 11 | path: string; | |
| 12 | body?: Record<string, unknown>; | |
| 13 | } | |
| 14 | ||
| 15 | export const CARE_USAGE = "usage: /care · /care log <ph|ec|waterTemp|airTemp|level|lightHours> <value> · /care did <action> [amount] · /care note <text> · /care problem <bolting|tip burn|root rot|algae|yellowing|leggy> [detail] · /care done <reminder> · /care snooze <reminder> [hours] · /care delete <entry id>"; | |
| 16 | ||
| 17 | const QUICK = ACTIONS.filter((a) => a !== "transplant" && a !== "done"); | |
| 18 | ||
| 19 | /** `/care …` (the words after the verb, and the line after the sub-verb) → what to ask the server, or the usage. */ | |
| 20 | export function careCommand(words: string[], tail: string): CareAsk | { print: string } { | |
| 21 | const usage = { print: CARE_USAGE }; | |
| 22 | const [sub = "", a = "", b = ""] = words; | |
| 23 | const post = (path: string, body: Record<string, unknown>): CareAsk => ({ method: "POST", path, body }); | |
| 24 | const num = (s: string) => (/^-?\d+(\.\d+)?$/.test(s) ? Number(s) : NaN); | |
| 25 | switch (sub.toLowerCase()) { | |
| 26 | case "": | |
| 27 | return { method: "GET", path: "/care/api" }; | |
| 28 | case "log": | |
| 29 | return (MEASURES as readonly string[]).includes(a) && Number.isFinite(num(b)) && words.length === 3 ? post("/care/log", { type: "measurement", kind: a, value: num(b) }) : usage; | |
| 30 | case "did": | |
| 31 | if (!(QUICK as readonly string[]).includes(a) || words.length > 3) return usage; | |
| 32 | return post("/care/log", { type: "action", what: a, ...(b ? { amount: num(b) } : {}) }); | |
| 33 | case "note": | |
| 34 | return tail ? post("/care/log", { type: "observation", text: tail }) : usage; | |
| 35 | case "problem": { | |
| 36 | const kind = PROBLEMS.find((p) => tail === p || tail.startsWith(`${p} `)); | |
| 37 | return kind ? post("/care/log", { type: "problem", what: kind, ...(tail.length > kind.length ? { text: tail.slice(kind.length).trim() } : {}) }) : usage; | |
| 38 | } | |
| 39 | case "done": | |
| 40 | return /^[a-z0-9-]{1,32}$/.test(a) && words.length === 2 ? post("/care/reminder", { id: a, action: "done" }) : usage; | |
| 41 | case "snooze": | |
| 42 | return /^[a-z0-9-]{1,32}$/.test(a) && words.length <= 3 && (!b || Number.isFinite(num(b))) ? post("/care/reminder", { id: a, action: "snooze", hours: b ? num(b) : 24 }) : usage; | |
| 43 | case "delete": | |
| 44 | return /^\d{1,9}$/.test(a) && words.length === 2 ? { method: "DELETE", path: `/care/log/${a}`, body: {} } : usage; | |
| 45 | default: | |
| 46 | return usage; | |
| 47 | } | |
| 48 | } | |
| 49 | ||
| 50 | const day = (at: number) => new Date(at).toISOString().replace("T", " ").slice(0, 16); | |
| 51 | ||
| 52 | /** GET /care/api as lines: the stage, the health strip, what is due, and the latest entries with their ids. */ | |
| 53 | export function careLines(body: unknown, now = Date.now()): string[] { | |
| 54 | const b = (body ?? {}) as { stage?: unknown; health?: { ok?: unknown; lines?: unknown[] }; reminders?: { id?: unknown; label?: unknown; dueAt?: unknown; snoozedUntil?: unknown }[]; prompts?: unknown[]; entries?: Record<string, unknown>[] }; | |
| 55 | const lines = [`Stage: ${String(b.stage ?? "?")} · ${b.health?.ok ? "healthy" : "needs attention"} (typical ranges, not guaranteed)`]; | |
| 56 | for (const l of b.health?.lines ?? []) lines.push(` ${String(l)}`); | |
| 57 | for (const p of b.prompts ?? []) lines.push(` ${String(p)}`); | |
| 58 | lines.push("Reminders:"); | |
| 59 | for (const r of (b.reminders ?? []).slice(0, 8)) { | |
| 60 | const state = r.snoozedUntil ? `snoozed until ${day(Number(r.snoozedUntil))}` : Number(r.dueAt) <= now ? "OVERDUE" : `due ${day(Number(r.dueAt))}`; | |
| 61 | lines.push(` ${String(r.id)}: ${String(r.label)} · ${state}`); | |
| 62 | } | |
| 63 | lines.push("Log book (newest last):"); | |
| 64 | for (const e of (b.entries ?? []).slice(-5)) { | |
| 65 | const what = e.type === "measurement" ? `${e.kind} ${e.value}` : e.type === "action" ? String(e.what) + (e.amount ? ` ${e.amount}` : "") + (e.ref ? ` ${e.ref}` : "") : e.type === "problem" ? `problem ${e.what}${e.text ? `: ${e.text}` : ""}` : String(e.text); | |
| 66 | lines.push(` #${e.id} ${day(Number(e.at))} ${e.type}: ${what}`); | |
| 67 | } | |
| 68 | return lines; | |
| 69 | } |
Software/so101/src/care.test.ts added +252
| @@ -0,0 +1,252 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 3 | import { createServer } from "node:http"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { check, health, reminders, snapshot, stageHistory, totals, transplantPrompt } from "./care-rules.ts"; | |
| 7 | import { CareLog, LogError, parseEntry } from "./care-log.ts"; | |
| 8 | import { BUILT_IN_DIR, loadProfiles, parseProfile, ProfileError } from "./care-profile.ts"; | |
| 9 | import { renderCare } from "./care-page.ts"; | |
| 10 | import { handleCare } from "./care-routes.ts"; | |
| 11 | ||
| 12 | const H = 3_600_000; | |
| 13 | const D = 24 * H; | |
| 14 | const T0 = Date.parse("2026-10-01T08:00:00Z"); | |
| 15 | const spinach = loadProfiles(BUILT_IN_DIR).find((p) => p.id === "spinach")!; | |
| 16 | const TOWER = { type: "action", what: "transplant", system: "vertical tower", litres: 20, sites: 12, pump: true }; | |
| 17 | ||
| 18 | /** A log whose clock the test moves. */ | |
| 19 | function book(file?: string) { | |
| 20 | const clock = { now: T0 }; | |
| 21 | return { clock, log: new CareLog(file, () => clock.now) }; | |
| 22 | } | |
| 23 | const due = (log: CareLog, now: number, id: string) => reminders(spinach, snapshot(log), now).find((d) => d.reminder.id === id); | |
| 24 | ||
| 25 | test("a profile loads from a file, and another file adds another plant", () => { | |
| 26 | const dir = mkdtempSync(join(tmpdir(), "grow-")); | |
| 27 | try { | |
| 28 | const basil = { ...JSON.parse(readFileSync(join(BUILT_IN_DIR, "spinach.json"), "utf8")), id: "basil", name: "Basil" }; | |
| 29 | writeFileSync(join(dir, "basil.json"), JSON.stringify(basil)); | |
| 30 | writeFileSync(join(dir, "broken.json"), "{"); | |
| 31 | const ids = loadProfiles(BUILT_IN_DIR, dir).map((p) => p.id); | |
| 32 | expect(ids).toEqual(["spinach", "basil"]); | |
| 33 | expect(spinach.stages.map((s) => s.id)).toEqual(["seedling", "hydroponic", "harvest"]); | |
| 34 | expect(spinach.stages[1]!.bands.ph).toEqual([5.5, 6.5]); | |
| 35 | expect(spinach.light.hours).toBe(12); | |
| 36 | } finally { | |
| 37 | rmSync(dir, { recursive: true, force: true }); | |
| 38 | } | |
| 39 | }); | |
| 40 | ||
| 41 | test("a profile is validated", () => { | |
| 42 | const ok = JSON.parse(readFileSync(join(BUILT_IN_DIR, "spinach.json"), "utf8")); | |
| 43 | expect(() => parseProfile({ ...ok, stages: [] })).toThrow(ProfileError); | |
| 44 | expect(() => parseProfile({ ...ok, stages: [{ ...ok.stages[0], bands: { ph: [7, 5] } }] })).toThrow(/low is above high/); | |
| 45 | expect(() => parseProfile({ ...ok, stages: [{ ...ok.stages[0], bands: { salt: [1, 2] } }] })).toThrow(/measure/); | |
| 46 | expect(() => parseProfile({ ...ok, id: "Bad Id" })).toThrow(/id/); | |
| 47 | }); | |
| 48 | ||
| 49 | test("entries are typed and validated at the door", () => { | |
| 50 | expect(parseEntry({ type: "measurement", kind: "ph", value: 6.1 }, T0)).toMatchObject({ kind: "ph", value: 6.1, source: "manual", at: T0 }); | |
| 51 | expect(() => parseEntry({ type: "measurement", kind: "ph", value: 71 }, T0)).toThrow(LogError); | |
| 52 | expect(() => parseEntry({ type: "measurement", kind: "salt", value: 1 }, T0)).toThrow(LogError); | |
| 53 | expect(() => parseEntry({ type: "problem", what: "gremlins" }, T0)).toThrow(LogError); | |
| 54 | expect(() => parseEntry({ type: "action", what: "transplant", system: "vertical tower", litres: 0, sites: 4 }, T0)).toThrow(/litres/); | |
| 55 | expect(() => parseEntry({ type: "observation", text: "x", at: T0 + D }, T0)).toThrow(/past/); | |
| 56 | expect(parseEntry({ type: "action", what: "harvest", amount: 40 }, T0)).toMatchObject({ amount: 40 }); | |
| 57 | }); | |
| 58 | ||
| 59 | test("the log book creates, edits, deletes and survives a restart", () => { | |
| 60 | const dir = mkdtempSync(join(tmpdir(), "grow-")); | |
| 61 | try { | |
| 62 | const file = join(dir, "care.json"); | |
| 63 | const { log } = book(file); | |
| 64 | const a = log.add({ type: "observation", text: "first true leaves" }); | |
| 65 | log.update(a.id, { type: "observation", text: "second pair" }); | |
| 66 | const b = log.add({ type: "problem", what: "algae" }); | |
| 67 | expect(log.remove(b.id)).toBe(true); | |
| 68 | expect(log.remove(b.id)).toBe(false); | |
| 69 | expect(new CareLog(file).entries()).toMatchObject([{ id: a.id, text: "second pair" }]); | |
| 70 | } finally { | |
| 71 | rmSync(dir, { recursive: true, force: true }); | |
| 72 | } | |
| 73 | }); | |
| 74 | ||
| 75 | test("seedling reminders fall due on their cadence and the moisture one resets when watering is logged", () => { | |
| 76 | const { clock, log } = book(); | |
| 77 | log.add({ type: "action", what: "sow" }); | |
| 78 | expect(due(log, T0 + 23 * H, "moisture")!.overdueMs).toBeLessThan(0); | |
| 79 | expect(due(log, T0 + 25 * H, "moisture")!.overdueMs).toBe(H); | |
| 80 | clock.now = T0 + 25 * H; | |
| 81 | log.add({ type: "action", what: "water" }); | |
| 82 | expect(due(log, T0 + 26 * H, "moisture")!.dueAt).toBe(T0 + 49 * H); | |
| 83 | expect(due(log, T0 + 26 * H, "bottom-water")!.dueAt).toBe(T0 + 25 * H + 60 * H); | |
| 84 | }); | |
| 85 | ||
| 86 | test("the transplant moves the stage, changes the reminders, and keeps history", () => { | |
| 87 | const { clock, log } = book(); | |
| 88 | log.add({ type: "action", what: "sow" }); | |
| 89 | const seedlingIds = reminders(spinach, snapshot(log), T0).map((d) => d.reminder.id); | |
| 90 | expect(seedlingIds).toContain("moisture"); | |
| 91 | clock.now = T0 + 16 * D; | |
| 92 | log.add(TOWER); | |
| 93 | const snap = snapshot(log); | |
| 94 | const spans = stageHistory(spinach, snap.entries, snap.startedAt); | |
| 95 | expect(spans.map((s) => [s.stage.id, s.from])).toEqual([["seedling", T0], ["hydroponic", T0 + 16 * D]]); | |
| 96 | const ids = reminders(spinach, snap, clock.now).map((d) => d.reminder.id); | |
| 97 | expect(ids).not.toContain("moisture"); | |
| 98 | expect(ids).toContain("pump"); | |
| 99 | expect(ids).toContain("tower"); | |
| 100 | // a small reservoir moves fast: measure and top off sooner in a tower | |
| 101 | expect(due(log, clock.now, "measure")!.everyHours).toBe(36); | |
| 102 | expect(due(log, clock.now, "topoff")!.everyHours).toBe(24); | |
| 103 | }); | |
| 104 | ||
| 105 | test("without a pump there is no pump reminder; a different system keeps the default cadence", () => { | |
| 106 | const { clock, log } = book(); | |
| 107 | clock.now = T0; | |
| 108 | log.add({ ...TOWER, system: "DWC", pump: false }); | |
| 109 | const ids = reminders(spinach, snapshot(log), T0).map((d) => d.reminder.id); | |
| 110 | expect(ids).not.toContain("pump"); | |
| 111 | expect(ids).not.toContain("tower"); | |
| 112 | expect(due(log, T0, "measure")!.everyHours).toBe(60); | |
| 113 | }); | |
| 114 | ||
| 115 | test("topping off resets the top-off reminder; done, snooze and an edited cadence work", () => { | |
| 116 | const { clock, log } = book(); | |
| 117 | log.add(TOWER); | |
| 118 | expect(due(log, T0 + 25 * H, "topoff")!.overdueMs).toBe(H); | |
| 119 | clock.now = T0 + 25 * H; | |
| 120 | log.add({ type: "action", what: "topoff" }); | |
| 121 | expect(due(log, clock.now, "topoff")!.dueAt).toBe(T0 + 49 * H); | |
| 122 | log.add({ type: "action", what: "done", ref: "calibrate" }); | |
| 123 | expect(due(log, clock.now, "calibrate")!.dueAt).toBe(clock.now + 168 * H); | |
| 124 | log.snooze("roots", 48); | |
| 125 | expect(due(log, clock.now + 10 * H, "roots")!.snoozedUntil).toBe(clock.now + 48 * H); | |
| 126 | log.setEvery("roots", 24); | |
| 127 | expect(due(log, clock.now, "roots")!.everyHours).toBe(24); | |
| 128 | log.setEvery("roots", null); | |
| 129 | expect(due(log, clock.now, "roots")!.everyHours).toBe(168); | |
| 130 | // a full change also counts as topping off, and is the two-week one | |
| 131 | log.add({ type: "action", what: "change" }); | |
| 132 | expect(due(log, clock.now, "change")!.dueAt).toBe(clock.now + 336 * H); | |
| 133 | }); | |
| 134 | ||
| 135 | test("band checks", () => { | |
| 136 | expect(check(7.1, [5.5, 6.5])).toBe("above"); | |
| 137 | expect(check(5.0, [5.5, 6.5])).toBe("below"); | |
| 138 | expect(check(6.5, [5.5, 6.5])).toBe("in"); | |
| 139 | }); | |
| 140 | ||
| 141 | test("the health strip is green, or names what is off", () => { | |
| 142 | const { clock, log } = book(); | |
| 143 | log.add(TOWER); | |
| 144 | const keep = (id: string) => log.add({ type: "action", what: "done", ref: id }); | |
| 145 | clock.now = T0 + 2 * H; | |
| 146 | for (const id of ["light", "level", "pump", "measure", "topoff", "calibrate", "air-stone", "roots", "tower", "change"]) keep(id); | |
| 147 | log.add({ type: "measurement", kind: "ph", value: 6.0 }); | |
| 148 | log.add({ type: "measurement", kind: "ec", value: 1.8 }); | |
| 149 | expect(health(spinach, snapshot(log), clock.now)).toEqual({ ok: true, lines: ["All readings in band, nothing overdue"] }); | |
| 150 | clock.now = T0 + 3 * H; | |
| 151 | log.add({ type: "measurement", kind: "ph", value: 7.1 }); | |
| 152 | log.add({ type: "measurement", kind: "airTemp", value: 26 }); | |
| 153 | const h = health(spinach, snapshot(log), T0 + 2 * D + 3 * H); | |
| 154 | expect(h.ok).toBe(false); | |
| 155 | expect(h.lines).toContain("pH 7.1, above 6.5, measured 2 d ago"); | |
| 156 | expect(h.lines).toContain("Air temp 26 °C, above 24, measured 2 d ago"); | |
| 157 | expect(h.lines.some((l) => /overdue/.test(l))).toBe(true); | |
| 158 | }); | |
| 159 | ||
| 160 | test("totals, and the ready-to-transplant prompt from the sow date", () => { | |
| 161 | const { clock, log } = book(); | |
| 162 | log.add({ type: "action", what: "sow" }); | |
| 163 | expect(transplantPrompt(spinach, snapshot(log), T0 + 10 * D)).toBeNull(); | |
| 164 | expect(transplantPrompt(spinach, snapshot(log), T0 + 15 * D)).toMatch(/Day 15.*2-4 true leaves/); | |
| 165 | clock.now = T0 + 16 * D; | |
| 166 | log.add(TOWER); | |
| 167 | expect(transplantPrompt(spinach, snapshot(log), T0 + 20 * D)).toBeNull(); | |
| 168 | clock.now = T0 + 20 * D; | |
| 169 | log.add({ type: "action", what: "change" }); | |
| 170 | log.add({ type: "action", what: "harvest", amount: 40 }); | |
| 171 | log.add({ type: "action", what: "harvest", amount: 25 }); | |
| 172 | expect(totals(log.entries(), T0 + 23 * D)).toEqual({ daysSinceChange: 3, harvestGrams: 65 }); | |
| 173 | expect(stageHistory(spinach, log.entries(), log.startedAt).map((s) => s.stage.id)).toEqual(["seedling", "hydroponic", "harvest"]); | |
| 174 | }); | |
| 175 | ||
| 176 | test("the page shows the strip, reminders, charts with bands and the log; a guest has no buttons", () => { | |
| 177 | const { clock, log } = book(); | |
| 178 | log.add({ type: "observation", text: "<b>hi</b>" }); | |
| 179 | clock.now = T0 + 1 * H; | |
| 180 | log.add({ type: "measurement", kind: "ph", value: 5.8 }); | |
| 181 | const page = (owner: boolean) => renderCare({ profile: spinach, log, now: clock.now, owner, signedIn: null }); | |
| 182 | const html = page(true); | |
| 183 | expect(html).toContain('data-ok="true"'); | |
| 184 | expect(html).toContain("<b>hi</b>"); | |
| 185 | expect(html).not.toContain("<b>hi</b>"); | |
| 186 | expect(html).toContain("Rockwool seedling"); | |
| 187 | expect(html).toContain("<polyline"); | |
| 188 | expect(html).toContain("Typical ranges, not guaranteed"); | |
| 189 | expect(html).toContain("Topped off"); | |
| 190 | expect(page(false)).not.toContain("Topped off"); | |
| 191 | }); | |
| 192 | ||
| 193 | test("the routes: read for anyone, write for the owner, forms redirect", async () => { | |
| 194 | const { log } = book(); | |
| 195 | let owner = true; | |
| 196 | const server = createServer((req, res) => { | |
| 197 | const readBody = (r: typeof req) => new Promise<Buffer>((ok) => { const c: Buffer[] = []; r.on("data", (d) => c.push(d)); r.on("end", () => ok(Buffer.concat(c))); }); | |
| 198 | handleCare(req, res, new URL(req.url!, "http://x").pathname, { profile: spinach, log, readBody, who: () => ({ owner, known: owner, signedIn: null }) }).then((hit) => hit || (res.writeHead(404), res.end())); | |
| 199 | }); | |
| 200 | await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok)); | |
| 201 | const base = `http://127.0.0.1:${(server.address() as { port: number }).port}`; | |
| 202 | try { | |
| 203 | const add = await fetch(`${base}/care/log`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "measurement", kind: "ec", value: 1.7 }) }); | |
| 204 | const { id } = (await add.json()) as { id: number }; | |
| 205 | expect(add.status).toBe(200); | |
| 206 | const bad = await fetch(`${base}/care/log`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "measurement", kind: "ph", value: 99 }) }); | |
| 207 | expect(bad.status).toBe(400); | |
| 208 | const form = await fetch(`${base}/care/log`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "type=action&what=topoff" }); | |
| 209 | expect(form.status).toBe(303); | |
| 210 | expect(form.headers.get("location")).toBe("/care"); | |
| 211 | const done = await fetch(`${base}/care/reminder`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "id=light&action=done" }); | |
| 212 | expect(done.status).toBe(303); | |
| 213 | const api = (await (await fetch(`${base}/care/api`)).json()) as { entries: unknown[]; health: { ok: boolean }; stage: string }; | |
| 214 | expect(api.entries).toHaveLength(3); | |
| 215 | expect(api.stage).toBe("seedling"); | |
| 216 | expect((await fetch(`${base}/care`)).status).toBe(200); | |
| 217 | expect((await fetch(`${base}/care/log/${id}/delete`, { method: "POST", redirect: "manual" })).status).toBe(303); | |
| 218 | owner = false; | |
| 219 | expect((await fetch(`${base}/care/log`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status).toBe(401); | |
| 220 | expect((await fetch(`${base}/care/api`)).status).toBe(200); | |
| 221 | } finally { | |
| 222 | server.close(); | |
| 223 | } | |
| 224 | }); | |
| 225 | ||
| 226 | test("a write publishes 'care changed' to /care/events, and a bad form comes back to the page with the message", async () => { | |
| 227 | const { log } = book(); | |
| 228 | const server = createServer((req, res) => { | |
| 229 | const readBody = (r: typeof req) => new Promise<Buffer>((ok) => { const c: Buffer[] = []; r.on("data", (d) => c.push(d)); r.on("end", () => ok(Buffer.concat(c))); }); | |
| 230 | handleCare(req, res, new URL(req.url!, "http://x").pathname, { profile: spinach, log, readBody, who: () => ({ owner: true, known: true, signedIn: null }) }).then((hit) => hit || (res.writeHead(404), res.end())); | |
| 231 | }); | |
| 232 | await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok)); | |
| 233 | const base = `http://127.0.0.1:${(server.address() as { port: number }).port}`; | |
| 234 | const stream = new AbortController(); | |
| 235 | try { | |
| 236 | const events = await fetch(`${base}/care/events`, { signal: stream.signal }); | |
| 237 | expect(events.headers.get("content-type")).toBe("text/event-stream"); | |
| 238 | const reader = events.body!.getReader(); | |
| 239 | await reader.read(); // retry hint | |
| 240 | await fetch(`${base}/care/log`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "action", what: "topoff" }) }); | |
| 241 | expect(new TextDecoder().decode((await reader.read()).value)).toContain("event: care"); | |
| 242 | const bad = await fetch(`${base}/care/log`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "type=measurement&kind=ph&value=71" }); | |
| 243 | expect(bad.status).toBe(303); | |
| 244 | const to = bad.headers.get("location")!; | |
| 245 | expect(to).toStartWith("/care?error="); | |
| 246 | expect(await (await fetch(`${base}${to}`)).text()).toMatch(/role="alert"/); | |
| 247 | expect(await (await fetch(`${base}/care?error=%3Cb%3E`)).text()).not.toContain("<b>"); | |
| 248 | } finally { | |
| 249 | stream.abort(); | |
| 250 | server.close(); | |
| 251 | } | |
| 252 | }); |
Software/so101/src/relay.ts +13
| @@ -106,6 +106,9 @@ import { readServos } from "./servo-panel.ts"; | ||
| 106 | 106 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 107 | 107 | import { CameraError, CameraHub } from "./cameras.ts"; |
| 108 | 108 | import { ARM_ONLY, StationError, StationHub } from "./stations.ts"; |
| 109 | import { CareLog } from "./care-log.ts"; | |
| 110 | import { BUILT_IN_DIR, loadProfiles, type Profile } from "./care-profile.ts"; | |
| 111 | import { handleCare } from "./care-routes.ts"; | |
| 109 | 112 | import { renderWorkshop, type StationView } from "./workshop-page.ts"; |
| 110 | 113 | import { DAY_MS, GrowStills, KEEP_DAYS } from "./grow-stills.ts"; |
| 111 | 114 | import { canopyByDay, dayNumber, GrowLog, GrowLogError, lightHours } from "./grow-log.ts"; |
| @@ -158,6 +161,8 @@ export interface RelayOptions { | ||
| 158 | 161 | cameras?: CameraHub; |
| 159 | 162 | /** The workshop's stations; by default in memory, the arm alone. */ |
| 160 | 163 | stations?: StationHub; |
| 164 | /** The plant care app's log book and plant profile (src/care-routes.ts); by default in memory, with the built-in spinach profile. */ | |
| 165 | care?: { log: CareLog; profile: Profile }; | |
| 161 | 166 | /** The grow box's stills, log and how often a still is taken (src/grow-stills.ts); without it nothing is taken and the card shows no timelapse. */ |
| 162 | 167 | grow?: { stills: GrowStills; log: GrowLog; everyMs: number }; |
| 163 | 168 | /** A setting that could not be used (shown on /link while simulating). */ |
| @@ -318,6 +323,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 318 | 323 | const edges = new ArmEdges(); |
| 319 | 324 | const metrics = new LiveMetrics(); |
| 320 | 325 | const stations = options.stations ?? new StationHub(undefined, ARM_ONLY); |
| 326 | const care = options.care ?? { log: new CareLog(), profile: loadProfiles(BUILT_IN_DIR).find((p) => p.id === "spinach")! }; | |
| 321 | 327 | const cameras = options.cameras ?? new CameraHub({ feed: { ...options.camera, metrics }, seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] }); |
| 322 | 328 | const leaders = options.leaders ?? new LeaderCalibrations(); |
| 323 | 329 | const videos = new Map<number, VideoFeed>(Object.entries(options.video ?? {}).map(([id, sources]) => [Number(id), new VideoFeed(sources, {}, options.env ?? process.env)])); |
| @@ -1041,6 +1047,13 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 1041 | 1047 | return res.end(STATIONS_PAGE); |
| 1042 | 1048 | } |
| 1043 | 1049 | if (url.pathname === "/admin/stations") return await administerStations(req, res); |
| 1050 | if (/^\/care(?:\/|$)/.test(url.pathname)) { | |
| 1051 | const who = (r: IncomingMessage) => { | |
| 1052 | const person = lobby ? lobby.who(r) : LOCAL_PERSON; | |
| 1053 | return { owner: Boolean(person?.owner), known: Boolean(person), signedIn: lobby && !lobby.local ? lobby.signedIn(r) : null }; | |
| 1054 | }; | |
| 1055 | if (await handleCare(req, res, url.pathname, { ...care, who, readBody })) return; | |
| 1056 | } | |
| 1044 | 1057 | if (reading && url.pathname === "/stations") return json(res, 200, stationViews().map(({ station, present, resting, cameras: c }) => ({ id: station.id, name: station.name, kind: station.kind, present, ...(resting ? { resting } : {}), cameras: c }))); |
| 1045 | 1058 | const cameraAdmin = ADMIN_CAMERA.exec(url.pathname); |
| 1046 | 1059 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1]), cameraAdmin[2] !== undefined); |
Software/so101/src/stations.ts +1 −1
| @@ -38,7 +38,7 @@ const text = (value: unknown, what: string, max: number): string => { | ||
| 38 | 38 | export const ARM_ONLY: readonly Station[] = [{ id: "arm", name: "The arm", kind: "arm", cameras: [1], controls: [{ label: "Drive the arm", href: "/arm" }] }]; |
| 39 | 39 | |
| 40 | 40 | /** What the file holds when there is none: the arm and the grow box (its camera is the second one listed; the owner edits both on /admin/stations/edit). */ |
| 41 | export const WORKSHOP: readonly Station[] = [...ARM_ONLY, { id: "grow", name: "Grow box", kind: "grow", cameras: [2], controls: [] }]; | |
| 41 | export const WORKSHOP: readonly Station[] = [...ARM_ONLY, { id: "grow", name: "Grow box", kind: "grow", cameras: [2], controls: [{ label: "Care", href: "/care" }] }]; | |
| 42 | 42 | |
| 43 | 43 | /** Any JSON → the stations it describes; throws a StationError saying what is wrong. */ |
| 44 | 44 | export function parseStations(input: unknown): Station[] { |
Software/so101/src/terminal.ts +37 −3
| @@ -35,6 +35,7 @@ | ||
| 35 | 35 | * /align [joint] admin: list each joint's reference pose and offset; with a joint, record it at its reference (POST /settings/joint-zero) and say Done or record again |
| 36 | 36 | * /health owner or moderator: each open page's link as it last reported it (GET /admin/health, the page's Admin -> Health) |
| 37 | 37 | * /stations [set <json>] the workshop's stations (GET /stations); the owner replaces them with a JSON list (PUT /admin/stations) |
| 38 | * /care [log|did|note|problem|done|snooze|delete …] the plant care app (GET /care/api); anyone reads, the owner writes (POST /care/log, /care/reminder) | |
| 38 | 39 | * /versions owner or moderator: the app's and the Pi's commits and the last sync (GET /admin/versions) |
| 39 | 40 | * /trace <session> owner or moderator: a kept session's 5 Hz trace, per joint (GET /precision/trace) |
| 40 | 41 | * /data [hour|day|week|all] owner or moderator: the Data view's overview and worst sessions (GET /data, src/data-lines.ts); default day |
| @@ -70,6 +71,7 @@ import type { DeviceName, LightView } from "./light.ts"; | ||
| 70 | 71 | import { readTuning, tuningSentence, type TuningView } from "./tuning-panel.ts"; |
| 71 | 72 | import { JOINTS } from "./sts3215.ts"; |
| 72 | 73 | import { headlineValue, hopLines, NO_HOPS, P95_RULE, readPrecision, sampleSize, sparkline, type PrecisionPanel } from "./precision-panel.ts"; |
| 74 | import { careCommand, careLines, type CareAsk } from "./care-terminal.ts"; | |
| 73 | 75 | import { presenceText } from "./ui/lobby-panel.js"; |
| 74 | 76 | import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js"; |
| 75 | 77 | |
| @@ -179,6 +181,24 @@ export function stationsReader(env: Env, fetcher: typeof fetch = fetch): ReadSta | ||
| 179 | 181 | }; |
| 180 | 182 | } |
| 181 | 183 | |
| 184 | /** What the care app answered to an ask. */ | |
| 185 | export type ReadCare = (ask: CareAsk) => Promise<Seen>; | |
| 186 | ||
| 187 | /** Ask the care routes: a read is open, a write is the owner's, and the server decides which. */ | |
| 188 | export function careReader(env: Env, fetcher: typeof fetch = fetch): ReadCare { | |
| 189 | return async (ask) => { | |
| 190 | try { | |
| 191 | const write = ask.method !== "GET"; | |
| 192 | const r = await fetcher(`${appUrl(env)}${ask.path}`, { method: ask.method, headers: { ...terminalHeaders(env), ...(write ? { "content-type": "application/json" } : {}) }, ...(write ? { body: JSON.stringify(ask.body ?? {}) } : {}), signal: AbortSignal.timeout(5000) }); | |
| 193 | const body = (await r.json().catch(() => null)) as unknown; | |
| 194 | if (!r.ok) return { error: plain((body as { error?: unknown } | null)?.error ?? `status ${r.status}`), lines: [] }; | |
| 195 | return { error: null, lines: write ? ["care saved"] : careLines(body).map(plain) }; | |
| 196 | } catch (err) { | |
| 197 | return { error: plain((err as Error).message), lines: [] }; | |
| 198 | } | |
| 199 | }; | |
| 200 | } | |
| 201 | ||
| 182 | 202 | /** What the grow log answered; with a change, the owner's POST /grow/log. */ |
| 183 | 203 | export type ReadGrowLog = (change?: Record<string, unknown>) => Promise<Seen>; |
| 184 | 204 | |
| @@ -523,7 +543,7 @@ export function whoami(room: Room): string { | ||
| 523 | 543 | /** The terminal holds no session to end: the forge signs who is at the keyboard afresh on every connection. */ |
| 524 | 544 | 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"; |
| 525 | 545 | |
| 526 | 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) /grow log|planted <date>|note <text> · /stations [set <json>] (set: owner) · /machine [off] · /who /whoami · /quit"; | |
| 546 | 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) /grow log|planted <date>|note <text> · /care [log|did|note|problem|done|snooze|delete …] · /stations [set <json>] (set: owner) · /machine [off] · /who /whoami · /quit"; | |
| 527 | 547 | |
| 528 | 548 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 529 | 549 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -679,7 +699,7 @@ function target(room: Room, word: string): string | null { | ||
| 679 | 699 | return ID.test(word) ? word : null; |
| 680 | 700 | } |
| 681 | 701 | |
| 682 | 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 } | { growLog: Record<string, unknown> | null } | { quit: true } | null; | |
| 702 | 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 } | { growLog: Record<string, unknown> | null } | { care: CareAsk } | { quit: true } | null; | |
| 683 | 703 | |
| 684 | 704 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 685 | 705 | export function typed(room: Room, input: string): Typed { |
| @@ -692,6 +712,10 @@ export function typed(room: Room, input: string): Typed { | ||
| 692 | 712 | const set = /^\/stations\s+set\s+(\S[\s\S]*)$/i.exec(line); |
| 693 | 713 | return set ? { stations: set[1]! } : { print: "usage: /stations [set <json list>]" }; |
| 694 | 714 | } |
| 715 | if (/^care$/i.test(verb)) { | |
| 716 | const r = careCommand([arg, ...rest].filter(Boolean), line.replace(/^\/\S+\s+\S+\s*/, "").trim()); | |
| 717 | return "method" in r ? { care: r } : r; | |
| 718 | } | |
| 695 | 719 | if (/^align$/i.test(verb)) { |
| 696 | 720 | if (rest.length || (arg && !REFERENCES.some((r) => r.joint === arg))) return { print: `usage: /align [${REFERENCES.map((r) => r.joint).join("|")}]` }; |
| 697 | 721 | return { align: arg || null }; |
| @@ -839,12 +863,14 @@ export class Door { | ||
| 839 | 863 | private readonly readVersions: ReadVersions | null; |
| 840 | 864 | private readonly readStations: ReadStations | null; |
| 841 | 865 | private readonly readGrowLog: ReadGrowLog | null; |
| 866 | private readonly readCare: ReadCare | null; | |
| 842 | 867 | private readonly readAlign: ReadAlign | null; |
| 843 | 868 | private readonly readData: ReadData | null; |
| 844 | 869 | private readonly readGrow: ReadGrow | null; |
| 845 | 870 | |
| 846 | 871 | /** `post` reaches the app's /stop and /resume, `read` its /admin/health, `readCard` its /precision; without them, the door says it cannot. */ |
| 847 | 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, readGrowLog: ReadGrowLog | null = null) { | |
| 872 | 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, readGrowLog: ReadGrowLog | null = null, readCare: ReadCare | null = null) { | |
| 873 | this.readCare = readCare; | |
| 848 | 874 | this.readGrowLog = readGrowLog; |
| 849 | 875 | this.readGrow = readGrow; |
| 850 | 876 | this.readData = readData; |
| @@ -908,6 +934,7 @@ export class Door { | ||
| 908 | 934 | else if ("versions" in t) void this.versions(); |
| 909 | 935 | else if ("stations" in t) void this.stations(t.stations); |
| 910 | 936 | else if ("growLog" in t) void this.growLog(t.growLog); |
| 937 | else if ("care" in t) void this.care(t.care); | |
| 911 | 938 | else if ("machine" in t) this.watchMachine(t.machine); |
| 912 | 939 | else this.send(t.send); |
| 913 | 940 | return true; |
| @@ -936,6 +963,13 @@ export class Door { | ||
| 936 | 963 | for (const line of r.error ? [`error: ${r.error}`] : r.lines) this.print(line); |
| 937 | 964 | } |
| 938 | 965 | |
| 966 | /** Anyone may read the care page's figures; the server lets only the owner write. */ | |
| 967 | private async care(ask: CareAsk): Promise<void> { | |
| 968 | if (!this.readCare) return this.print("error: the care app is not available here"); | |
| 969 | const r = await this.readCare(ask); | |
| 970 | for (const line of r.error ? [`error: ${r.error}`] : r.lines) this.print(line); | |
| 971 | } | |
| 972 | ||
| 939 | 973 | /** The server decides who may change them; anyone may list. */ |
| 940 | 974 | private async stations(set: string | null): Promise<void> { |
| 941 | 975 | if (!this.readStations) return this.print("error: stations are not available here"); |
Software/so101/src/tty.ts +2 −2
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import { createInterface, type Interface } from "node:readline"; |
| 7 | import { alignReader, cardReader, dataReader, Door, growLogReader, growReader, HELP, liveUrl, poster, reader, servosReader, stationsReader, terminalHeaders, traceReader, tuningReader, versionsReader } from "./terminal.ts"; | |
| 7 | import { alignReader, cardReader, careReader, dataReader, Door, growLogReader, 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), growReader(env), stationsReader(env), growLogReader(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), growLogReader(env), careReader(env)); | |
| 21 | 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); |
| 22 | 22 | try { |
| 23 | 23 | await door.open(() => { |
new above
offline