Compare commits
84 Commits
3f16925fe0
...
eda_dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f63a7063c | |||
| dd2dd53d7e | |||
| 980a3e5178 | |||
| 494c11ddbf | |||
| 726dd9803a | |||
| ce10c741fc | |||
| 78b1c99890 | |||
| d3649669ee | |||
| b69faec547 | |||
| ee0e1ff575 | |||
| ef2c9f9f45 | |||
| c9529ec9d7 | |||
| cb43ad78ca | |||
| bccef3875b | |||
| 69ff224fe7 | |||
| 1c1db5c5d0 | |||
| 91ebdb2bbf | |||
| 8d9fbfa0bf | |||
| 52354d194a | |||
| 4fd5bf852e | |||
| 2c3bdb7f34 | |||
| 301aefc186 | |||
| d893f4e991 | |||
| c6087b990c | |||
| 39fb5fb7c2 | |||
| b6f7ea65a4 | |||
| 6978f9e406 | |||
| 8b1f851add | |||
| 13ba593b69 | |||
| f4dd248e16 | |||
| 580412aa50 | |||
| f5f8865309 | |||
| 44e095cb95 | |||
| 73ada89a13 | |||
| 6eb65361a8 | |||
| c08e232339 | |||
| e842f036e2 | |||
| 005447f938 | |||
| 06d9297e9a | |||
| 965937352d | |||
| ec015911e9 | |||
| c94269379e | |||
| d93089a491 | |||
| 7b29331f52 | |||
| 9332802e5d | |||
| a86af4eb20 | |||
| 2ac26b5825 | |||
| 3f903cdbdd | |||
| ffcf0d3eda | |||
| e3b3a636e2 | |||
| 55c9c33432 | |||
| 82e5833e4e | |||
| 2e98167dba | |||
| a761398301 | |||
| 5d247a5729 | |||
| 30a1180108 | |||
| 354de04a3d | |||
| 32b4d9e92b | |||
| 1167e27b1d | |||
| f4e5c5037b | |||
| fc93db73c2 | |||
| 44f757ee37 | |||
| b00182d95d | |||
| b7efa081ec | |||
| 08351a09bf | |||
| 4593a397dd | |||
| 4d1d245680 | |||
| 5afdcc78ae | |||
| e3de7800e5 | |||
| 73bfc1d9b9 | |||
| f4b806a538 | |||
| fe3b12a60d | |||
| 88f9c53fda | |||
| e8cb057082 | |||
| 4a02e5fed3 | |||
| 552d87d75b | |||
| 7e21cf057e | |||
| 4fd175e0e4 | |||
| 535244209a | |||
| 0845e87ddd | |||
| 2d9bb15d4c | |||
| 29594f8bad | |||
| 4ff31557a8 | |||
| 3e77a4ad7c |
@@ -0,0 +1,10 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.png binary
|
||||||
|
*.ico binary
|
||||||
|
*.pdf binary
|
||||||
|
*.woff2 binary
|
||||||
|
|
||||||
|
# raw sources are kept byte-for-byte as dropped in
|
||||||
|
wiki/raw/** -text
|
||||||
|
*.jpg binary
|
||||||
|
*.bin binary
|
||||||
+8
-2
@@ -24,8 +24,6 @@ dist/
|
|||||||
/dingtian/
|
/dingtian/
|
||||||
/QRCode_sdk*/
|
/QRCode_sdk*/
|
||||||
|
|
||||||
# Graphify knowledge-graph output (dev tool; generated, not committed)
|
|
||||||
graphify-out/
|
|
||||||
parking.sqlite*.bak-*
|
parking.sqlite*.bak-*
|
||||||
questions.txt
|
questions.txt
|
||||||
|
|
||||||
@@ -33,3 +31,11 @@ questions.txt
|
|||||||
task_plan.md
|
task_plan.md
|
||||||
findings.md
|
findings.md
|
||||||
progress.md
|
progress.md
|
||||||
|
|
||||||
|
# local scratch (site snapshots pulled for incident review, never committed)
|
||||||
|
tmp/
|
||||||
|
|
||||||
|
# Firmware PoC (firmware/relay-proxy/README.md): toolchain venv, build output, Wi-Fi secrets
|
||||||
|
firmware/.venv/
|
||||||
|
firmware/**/.pio/
|
||||||
|
firmware/**/include/secrets.h
|
||||||
|
|||||||
@@ -7,9 +7,15 @@
|
|||||||
# TLS later: replace `:80` with the real hostname (e.g. `parksystems.msai.al`), uncomment
|
# TLS later: replace `:80` with the real hostname (e.g. `parksystems.msai.al`), uncomment
|
||||||
# Caddy's :443 in docker-compose.prod.yml, and Caddy auto-provisions HTTPS. For a private
|
# Caddy's :443 in docker-compose.prod.yml, and Caddy auto-provisions HTTPS. For a private
|
||||||
# CA / internal cert, use `tls /path/cert.pem /path/key.pem`.
|
# CA / internal cert, use `tls /path/cert.pem /path/key.pem`.
|
||||||
:80 {
|
#
|
||||||
|
# PORTS ARE ENV-DRIVEN (2026-10-08): HTTP_PORT (listen, default 80) and SERVER_PORT (upstream,
|
||||||
|
# default 3000) come from docker-compose.prod.yml, which takes them from the stack env. A booth
|
||||||
|
# leaves both unset and gets :80 → :3000 exactly as before. A SHARED host (the lab stack moved
|
||||||
|
# onto art-docker-station, whose :80 belongs to another service) sets HTTP_PORT=8080 etc. in the
|
||||||
|
# Komodo stack env — nothing here or in the image changes. See wiki/decisions/container-deployment.md.
|
||||||
|
:{$HTTP_PORT:80} {
|
||||||
encode gzip
|
encode gzip
|
||||||
# Host network (prod): the server runs on the host's net namespace (to reach the booth LAN /
|
# Host network (prod): the server runs on the host's net namespace (to reach the booth LAN /
|
||||||
# device VLAN), so reach it over loopback, not the compose service name `server`.
|
# device VLAN), so reach it over loopback, not the compose service name `server`.
|
||||||
reverse_proxy 127.0.0.1:3000
|
reverse_proxy 127.0.0.1:{$SERVER_PORT:3000}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const basic = "Basic " + Buffer.from(`${REVIEWER.user}:${REVIEWER.pass}`).toStri
|
|||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
dir = await mkdtemp(path.join(tmpdir(), "collector-"));
|
dir = await mkdtemp(path.join(tmpdir(), "collector-"));
|
||||||
app = await buildCollector({ host: "127.0.0.1", port: 0, dataDir: dir, boothTokens: TOKENS, reviewer: REVIEWER }, { dbFile: ":memory:" });
|
app = await buildCollector({ host: "127.0.0.1", port: 0, dataDir: dir, boothTokens: TOKENS, reviewer: REVIEWER, trainerUrl: null }, { dbFile: ":memory:" });
|
||||||
await app.ready();
|
await app.ready();
|
||||||
});
|
});
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
@@ -151,3 +151,46 @@ describe("config", () => {
|
|||||||
expect(() => parseBoothTokens("nocolon")).toThrow(/bad pair/);
|
expect(() => parseBoothTokens("nocolon")).toThrow(/bad pair/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("schema migration", () => {
|
||||||
|
it("opens a database created before the `kind` column and adds the missing columns, so ingest and stats work", async () => {
|
||||||
|
// art-docker-station, 2026-09-16: the volume's DB predated `kind`; CREATE TABLE IF NOT
|
||||||
|
// EXISTS left it alone, and /health, every ingest and the trainer's readiness failed
|
||||||
|
// with "no such column: kind". Replay: a file with the ORIGINAL column set.
|
||||||
|
const { default: Database } = await import("better-sqlite3");
|
||||||
|
const file = path.join(dir, "old.sqlite");
|
||||||
|
const old = new Database(file);
|
||||||
|
old.exec(`CREATE TABLE items (
|
||||||
|
id TEXT PRIMARY KEY, booth TEXT NOT NULL, order_ref TEXT NOT NULL, at TEXT NOT NULL,
|
||||||
|
service TEXT NOT NULL, vision_class TEXT NOT NULL, vision_confidence REAL NOT NULL,
|
||||||
|
image_width INTEGER NOT NULL, image_height INTEGER NOT NULL, plate_blurred INTEGER NOT NULL,
|
||||||
|
image_path TEXT NOT NULL, received_at TEXT NOT NULL, review_label TEXT, reviewed_at TEXT, reviewer TEXT)`);
|
||||||
|
old.prepare(
|
||||||
|
"INSERT INTO items (id, booth, order_ref, at, service, vision_class, vision_confidence, image_width, image_height, plate_blurred, image_path, received_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||||
|
).run("legacy-1", "booth-7", "o-0", "2026-09-01T00:00:00.000Z", "Standard", "suv", 0.8, 100, 100, 1, "crops/legacy-1.jpg", "2026-09-01T00:00:00.000Z");
|
||||||
|
old.close();
|
||||||
|
|
||||||
|
const legacy = await buildCollector({ host: "127.0.0.1", port: 0, dataDir: dir, boothTokens: TOKENS, reviewer: REVIEWER, trainerUrl: null }, { dbFile: file });
|
||||||
|
await legacy.ready();
|
||||||
|
try {
|
||||||
|
const health = await legacy.inject({ method: "GET", url: "/health" });
|
||||||
|
expect(health.statusCode).toBe(200);
|
||||||
|
expect(health.json()).toMatchObject({ ok: true, booths: 1, pending: 1 });
|
||||||
|
|
||||||
|
const { body, type } = multipart({ meta: JSON.stringify(meta({ item: "item-new" })) }, JPEG);
|
||||||
|
const r = await legacy.inject({ method: "POST", url: "/ingest", headers: { authorization: `Bearer ${TOKENS.get("booth-7")!}`, "content-type": type }, payload: body });
|
||||||
|
expect(r.statusCode).toBe(201);
|
||||||
|
|
||||||
|
const stats = await legacy.inject({ method: "GET", url: "/api/stats", headers: { authorization: basic } });
|
||||||
|
expect(stats.statusCode).toBe(200);
|
||||||
|
|
||||||
|
// The legacy row reads back with the defaults the new columns carry.
|
||||||
|
const cols = new Database(file, { readonly: true }).prepare("PRAGMA table_info(items)").all() as { name: string }[];
|
||||||
|
expect(cols.map((c) => c.name)).toEqual(expect.arrayContaining(["kind", "operator_ref", "operator_classes", "vision_category_id", "downgraded"]));
|
||||||
|
const legacyRow = new Database(file, { readonly: true }).prepare("SELECT kind, operator_classes, downgraded FROM items WHERE id = 'legacy-1'").get() as Record<string, unknown>;
|
||||||
|
expect(legacyRow).toEqual({ kind: "wash", operator_classes: "[]", downgraded: 0 });
|
||||||
|
} finally {
|
||||||
|
await legacy.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import { reviewPage } from "./review-page.js";
|
|||||||
// /review + /api/* the reviewer's screen (HTTP Basic, one login)
|
// /review + /api/* the reviewer's screen (HTTP Basic, one login)
|
||||||
// GET /export/labels.csv the training set: reviewed, usable rows (crops sit beside it on
|
// GET /export/labels.csv the training set: reviewed, usable rows (crops sit beside it on
|
||||||
// the volume, so the trainer on this host reads them directly)
|
// the volume, so the trainer on this host reads them directly)
|
||||||
|
// /api/training/* the Training section: a thin proxy to the trainer's job API on
|
||||||
|
// the compose network (never published), behind the reviewer login
|
||||||
// It deliberately has no fleet features and no path back into a booth.
|
// It deliberately has no fleet features and no path back into a booth.
|
||||||
|
|
||||||
/** The package's `meta` part, as the booth sends it (review-outbox.ts). */
|
/** The package's `meta` part, as the booth sends it (review-outbox.ts). */
|
||||||
@@ -230,6 +232,66 @@ export async function buildCollector(cfg: CollectorConfig, opts: { dbFile?: stri
|
|||||||
return reply.type("text/csv; charset=utf-8").header("content-disposition", 'attachment; filename="labels.csv"').send([head, ...lines].join("\n") + "\n");
|
return reply.type("text/csv; charset=utf-8").header("content-disposition", 'attachment; filename="labels.csv"').send([head, ...lines].join("\n") + "\n");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Training (proxy to the trainer's job API) ----------------------------------------
|
||||||
|
// The trainer is a sibling container reading the same volume; it is reachable only on the
|
||||||
|
// compose network, so the reviewer's login here is the only gate. The proxy forwards a
|
||||||
|
// fixed set of paths and passes the trainer's status codes through (409 = a job runs).
|
||||||
|
const trainer = cfg.trainerUrl;
|
||||||
|
async function viaTrainer(reply: FastifyReply, tpath: string, init?: RequestInit): Promise<unknown> {
|
||||||
|
if (!trainer) return reply.code(503).send({ error: "trainer not configured" });
|
||||||
|
let r: Response;
|
||||||
|
try {
|
||||||
|
r = await fetch(trainer + tpath, { ...init, signal: AbortSignal.timeout(15_000) });
|
||||||
|
} catch (err) {
|
||||||
|
return reply.code(502).send({ error: `trainer unreachable: ${(err as Error).message}` });
|
||||||
|
}
|
||||||
|
const ctype = r.headers.get("content-type") ?? "application/json";
|
||||||
|
return reply.code(r.status).type(ctype).send(Buffer.from(await r.arrayBuffer()));
|
||||||
|
}
|
||||||
|
app.get("/api/training/status", { preHandler: requireReviewer }, async (_req, reply) => {
|
||||||
|
if (!trainer) return { configured: false };
|
||||||
|
try {
|
||||||
|
const get = async (p: string) => {
|
||||||
|
const r = await fetch(trainer + p, { signal: AbortSignal.timeout(15_000) });
|
||||||
|
if (!r.ok) {
|
||||||
|
// Surface the trainer's own error text (its handlers answer 500 JSON), so the
|
||||||
|
// reviewer reads "no such column: kind", not just a status code.
|
||||||
|
const detail = await r.text().then((t) => {
|
||||||
|
try {
|
||||||
|
return String((JSON.parse(t) as { error?: unknown }).error ?? t);
|
||||||
|
} catch {
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
}, () => "");
|
||||||
|
throw new Error(`${p} → HTTP ${r.status}${detail ? `: ${detail.slice(0, 300)}` : ""}`);
|
||||||
|
}
|
||||||
|
return r.json() as Promise<Record<string, unknown>>;
|
||||||
|
};
|
||||||
|
const [health, readiness, versions, jobs] = await Promise.all([get("/health"), get("/readiness"), get("/versions"), get("/jobs")]);
|
||||||
|
return { configured: true, reachable: true, health, readiness, versions: versions.versions, jobs: jobs.jobs, current: jobs.current };
|
||||||
|
} catch (err) {
|
||||||
|
return reply.code(200).send({ configured: true, reachable: false, error: (err as Error).message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
app.post<{ Body: Record<string, unknown> }>("/api/training/jobs", { preHandler: requireReviewer }, async (req, reply) => {
|
||||||
|
const b = req.body && typeof req.body === "object" ? req.body : {};
|
||||||
|
const kind = b.kind;
|
||||||
|
if (kind !== "train" && kind !== "evaluate" && kind !== "publish") return reply.code(400).send({ error: "kind must be train, evaluate or publish" });
|
||||||
|
// Only the knobs the UI offers cross over; the trainer validates their values.
|
||||||
|
const allowed = ["kind", "mode", "backbone", "minAccuracy", "minPerClass", "epochs", "version"];
|
||||||
|
const body: Record<string, unknown> = {};
|
||||||
|
for (const k of allowed) if (b[k] !== undefined) body[k] = b[k];
|
||||||
|
return viaTrainer(reply, "/jobs", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||||
|
});
|
||||||
|
app.get<{ Params: { id: string } }>("/api/training/jobs/:id", { preHandler: requireReviewer }, async (req, reply) => {
|
||||||
|
if (!ID_RE.test(req.params.id)) return reply.code(400).send({ error: "bad job id" });
|
||||||
|
return viaTrainer(reply, `/jobs/${encodeURIComponent(req.params.id)}`);
|
||||||
|
});
|
||||||
|
app.get<{ Params: { v: string } }>("/api/training/versions/:v/report", { preHandler: requireReviewer }, async (req, reply) => {
|
||||||
|
if (!ID_RE.test(req.params.v)) return reply.code(400).send({ error: "bad version" });
|
||||||
|
return viaTrainer(reply, `/versions/${encodeURIComponent(req.params.v)}/report`);
|
||||||
|
});
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ export interface CollectorConfig {
|
|||||||
readonly boothTokens: ReadonlyMap<string, string>;
|
readonly boothTokens: ReadonlyMap<string, string>;
|
||||||
/** The single reviewer login; null = review screen and export refuse (503). */
|
/** The single reviewer login; null = review screen and export refuse (503). */
|
||||||
readonly reviewer: { readonly user: string; readonly pass: string } | null;
|
readonly reviewer: { readonly user: string; readonly pass: string } | null;
|
||||||
|
/** The trainer's job API on the compose network (http://trainer:8091); null = the
|
||||||
|
* Training section is hidden and /api/training/* answers 503. */
|
||||||
|
readonly trainerUrl: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** "booth-7:abc,booth-9:def" (commas, whitespace or newlines between pairs). */
|
/** "booth-7:abc,booth-9:def" (commas, whitespace or newlines between pairs). */
|
||||||
@@ -32,5 +35,6 @@ export function configFromEnv(env: NodeJS.ProcessEnv = process.env): CollectorCo
|
|||||||
dataDir: env.COLLECTOR_DATA_DIR ?? "/data",
|
dataDir: env.COLLECTOR_DATA_DIR ?? "/data",
|
||||||
boothTokens: parseBoothTokens(env.COLLECTOR_BOOTH_TOKENS ?? ""),
|
boothTokens: parseBoothTokens(env.COLLECTOR_BOOTH_TOKENS ?? ""),
|
||||||
reviewer: user && pass.length >= 8 ? { user, pass } : null,
|
reviewer: user && pass.length >= 8 ? { user, pass } : null,
|
||||||
|
trainerUrl: (env.COLLECTOR_TRAINER_URL ?? "").trim().replace(/\/+$/, "") || null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,39 @@ export class CollectorDb {
|
|||||||
CREATE INDEX IF NOT EXISTS items_pending ON items (reviewed_at, received_at);
|
CREATE INDEX IF NOT EXISTS items_pending ON items (reviewed_at, received_at);
|
||||||
CREATE INDEX IF NOT EXISTS items_booth ON items (booth, received_at);
|
CREATE INDEX IF NOT EXISTS items_booth ON items (booth, received_at);
|
||||||
`);
|
`);
|
||||||
|
this.#migrate();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Columns added after the first deploy, with the DDL that adds them to an EXISTING
|
||||||
|
* table. `CREATE TABLE IF NOT EXISTS` above only shapes a NEW database; a volume that
|
||||||
|
* was created by an earlier build keeps its old columns, and every query naming a new
|
||||||
|
* one then fails ("no such column: kind" — art-docker-station, 2026-09-16: the
|
||||||
|
* collector's /health, every ingest, and the trainer's readiness all broke on a DB
|
||||||
|
* from before `kind`). Each entry must be addable to a populated table, i.e. nullable
|
||||||
|
* or carrying a DEFAULT. Append here whenever a column joins the CREATE above. */
|
||||||
|
static readonly #ADDED_COLUMNS: ReadonlyArray<readonly [name: string, ddl: string]> = [
|
||||||
|
["kind", "TEXT NOT NULL DEFAULT 'wash'"],
|
||||||
|
["operator_ref", "TEXT NOT NULL DEFAULT ''"],
|
||||||
|
["operator_category_id", "TEXT NOT NULL DEFAULT ''"],
|
||||||
|
["operator_category_name", "TEXT NOT NULL DEFAULT ''"],
|
||||||
|
["operator_classes", "TEXT NOT NULL DEFAULT '[]'"],
|
||||||
|
["vision_category_id", "TEXT"],
|
||||||
|
["downgraded", "INTEGER NOT NULL DEFAULT 0"],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Bring an existing `items` table up to the current column set (idempotent). */
|
||||||
|
#migrate(): void {
|
||||||
|
const present = new Set(
|
||||||
|
(this.#db.prepare("PRAGMA table_info(items)").all() as { name: string }[]).map((c) => c.name),
|
||||||
|
);
|
||||||
|
for (const [name, ddl] of CollectorDb.#ADDED_COLUMNS) {
|
||||||
|
if (!present.has(name)) this.#db.exec(`ALTER TABLE items ADD COLUMN ${name} ${ddl}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The current column names of `items` (for tests and diagnostics). */
|
||||||
|
columns(): string[] {
|
||||||
|
return (this.#db.prepare("PRAGMA table_info(items)").all() as { name: string }[]).map((c) => c.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
close(): void {
|
close(): void {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const cfg = configFromEnv();
|
|||||||
const app = await buildCollector(cfg);
|
const app = await buildCollector(cfg);
|
||||||
if (cfg.boothTokens.size === 0) app.log.warn("COLLECTOR_BOOTH_TOKENS is empty — no booth can ingest");
|
if (cfg.boothTokens.size === 0) app.log.warn("COLLECTOR_BOOTH_TOKENS is empty — no booth can ingest");
|
||||||
if (!cfg.reviewer) app.log.warn("COLLECTOR_REVIEWER_USER/PASS not set — the review screen and export refuse");
|
if (!cfg.reviewer) app.log.warn("COLLECTOR_REVIEWER_USER/PASS not set — the review screen and export refuse");
|
||||||
app.log.info(`collector: ${cfg.boothTokens.size} booth token(s), data in ${cfg.dataDir}`);
|
app.log.info(`collector: ${cfg.boothTokens.size} booth token(s), data in ${cfg.dataDir}, trainer ${cfg.trainerUrl ?? "not configured"}`);
|
||||||
await app.listen({ host: cfg.host, port: cfg.port });
|
await app.listen({ host: cfg.host, port: cfg.port });
|
||||||
|
|
||||||
const stop = async () => {
|
const stop = async () => {
|
||||||
|
|||||||
@@ -35,6 +35,16 @@ export function reviewPage(): string {
|
|||||||
td, th { text-align:left; padding:.2rem .5rem; border-bottom:1px solid #2a2a2a; }
|
td, th { text-align:left; padding:.2rem .5rem; border-bottom:1px solid #2a2a2a; }
|
||||||
th { color:var(--muted); font-weight:normal; font-size:.75rem; text-transform:uppercase; letter-spacing:.06em; }
|
th { color:var(--muted); font-weight:normal; font-size:.75rem; text-transform:uppercase; letter-spacing:.06em; }
|
||||||
kbd { background:#2a2a2a; border:1px solid #444; border-radius:3px; padding:0 .3rem; font-size:.75rem; }
|
kbd { background:#2a2a2a; border:1px solid #444; border-radius:3px; padding:0 .3rem; font-size:.75rem; }
|
||||||
|
h2 { font-size:.8rem; letter-spacing:.08em; text-transform:uppercase; color:var(--amber); margin:0 0 .6rem; }
|
||||||
|
.row { display:flex; flex-wrap:wrap; gap:.6rem; align-items:center; }
|
||||||
|
select, input { background:#2a2a2a; color:var(--text); border:1px solid #444; border-radius:4px; padding:.4rem .5rem; font:inherit; }
|
||||||
|
input[type=number] { width:5rem; }
|
||||||
|
label { color:var(--muted); font-size:.8rem; }
|
||||||
|
pre { background:#0d0d0d; border:1px solid #2a2a2a; border-radius:4px; padding:.6rem; max-height:22rem; overflow:auto; font-size:.75rem; white-space:pre-wrap; margin:.6rem 0 0; }
|
||||||
|
.ok { color:var(--green); }
|
||||||
|
.bad { color:var(--red); }
|
||||||
|
button:disabled { opacity:.45; cursor:not-allowed; }
|
||||||
|
button.small { padding:.25rem .5rem; font-size:.75rem; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -46,6 +56,10 @@ export function reviewPage(): string {
|
|||||||
<section class="card">
|
<section class="card">
|
||||||
<table id="stats"><thead><tr><th>booth</th><th>operator</th><th>reviewed</th><th>agree</th><th>disagree</th><th>unusable</th></tr></thead><tbody></tbody></table>
|
<table id="stats"><thead><tr><th>booth</th><th>operator</th><th>reviewed</th><th>agree</th><th>disagree</th><th>unusable</th></tr></thead><tbody></tbody></table>
|
||||||
</section>
|
</section>
|
||||||
|
<section class="card" id="training" hidden>
|
||||||
|
<h2>Training</h2>
|
||||||
|
<div id="tr-body"></div>
|
||||||
|
</section>
|
||||||
<p class="muted">Keys: <kbd>1</kbd>–<kbd>9</kbd>, <kbd>0</kbd> pick a class in order · <kbd>u</kbd> unusable · <kbd>s</kbd> skip. Skipped items come back after a reload. Your verdict is the training label; the operator's pick is only compared against it.</p>
|
<p class="muted">Keys: <kbd>1</kbd>–<kbd>9</kbd>, <kbd>0</kbd> pick a class in order · <kbd>u</kbd> unusable · <kbd>s</kbd> skip. Skipped items come back after a reload. Your verdict is the training label; the operator's pick is only compared against it.</p>
|
||||||
</main>
|
</main>
|
||||||
<script>
|
<script>
|
||||||
@@ -114,6 +128,106 @@ document.addEventListener('keydown', e => {
|
|||||||
|
|
||||||
next().catch(e => { document.getElementById('item').innerHTML = '<p class="warn">' + esc(e.message) + '</p>'; });
|
next().catch(e => { document.getElementById('item').innerHTML = '<p class="warn">' + esc(e.message) + '</p>'; });
|
||||||
loadStats().catch(() => {});
|
loadStats().catch(() => {});
|
||||||
|
|
||||||
|
// ---- Training: the trainer's job API, proxied by the collector -------------------------
|
||||||
|
// Readiness (labels per class vs the minimum), one job at a time with a live log, the
|
||||||
|
// versions a run produced (written or refused) with Report / Evaluate / Publish. Pinning a
|
||||||
|
// published version into the vision image stays a git commit — that is the deploy control.
|
||||||
|
let trPoll = null;
|
||||||
|
let trShownReport = null;
|
||||||
|
const trDefaults = { mode: 'features', backbone: 'resnet18', minAccuracy: 0.85 };
|
||||||
|
|
||||||
|
function pct(x) { return x == null ? '—' : Math.round(x * 100) + ' %'; }
|
||||||
|
|
||||||
|
async function training() {
|
||||||
|
const box = document.getElementById('training');
|
||||||
|
const el = document.getElementById('tr-body');
|
||||||
|
let s;
|
||||||
|
try { s = await api('/api/training/status'); } catch (e) { box.hidden = false; el.innerHTML = '<p class="warn">' + esc(e.message) + '</p>'; return; }
|
||||||
|
if (!s.configured) { box.hidden = true; return; }
|
||||||
|
box.hidden = false;
|
||||||
|
if (!s.reachable) { el.innerHTML = '<p class="warn">trainer not reachable: ' + esc(s.error || '') + '</p>'; schedule(true); return; }
|
||||||
|
const r = s.readiness, run = r.run || {}, minPer = run.minPerClass || 20;
|
||||||
|
const byClass = (r.labelled && r.labelled.byClass) || {};
|
||||||
|
const classes = Object.keys(byClass);
|
||||||
|
const cur = s.current;
|
||||||
|
const readyLine = r.ready
|
||||||
|
? '<span class="ok">enough labels to train</span> — classes this run: ' + esc((run.classes || []).join(', '))
|
||||||
|
: '<span class="warn">not enough labels yet</span> — a class needs ' + minPer + ' reviewed crops; two classes must clear it';
|
||||||
|
let html = '<p>' + readyLine + ' <span class="muted">(' + (r.labelled ? r.labelled.total : 0) + ' labelled, ' + (r.missingCrops || 0) + ' missing crop files)</span></p>';
|
||||||
|
html += '<table><thead><tr><th>class</th><th>reviewed</th><th>train</th><th>val</th><th></th></tr></thead><tbody>' +
|
||||||
|
(classes.map(c => '<tr><td class="mono">' + esc(c) + '</td><td>' + byClass[c] + '</td><td>' + ((run.train || {})[c] ?? '—') + '</td><td>' + ((run.val || {})[c] ?? '—') + '</td><td class="muted">' + (byClass[c] < minPer ? 'below ' + minPer + ' — dropped' : '') + '</td></tr>').join('') || '<tr><td colspan="5" class="muted">no labels yet — review crops above</td></tr>') +
|
||||||
|
'</tbody></table>';
|
||||||
|
const d = Object.assign({}, trDefaults, r.defaults || {});
|
||||||
|
html += '<div class="row" style="margin-top:.8rem">' +
|
||||||
|
'<label>mode <select id="tr-mode">' + (r.modes || ['features', 'finetune']).map(m => '<option' + (m === d.mode ? ' selected' : '') + '>' + m + '</option>').join('') + '</select></label>' +
|
||||||
|
'<label>backbone <select id="tr-backbone">' + (r.backbones || ['resnet18']).map(b => '<option' + (b === d.backbone ? ' selected' : '') + '>' + b + '</option>').join('') + '</select></label>' +
|
||||||
|
'<label>floor <input id="tr-floor" type="number" min="0" max="1" step="0.01" value="' + d.minAccuracy + '"></label>' +
|
||||||
|
'<button id="tr-train"' + (r.ready && !cur ? '' : ' disabled') + '>Train</button>' +
|
||||||
|
(cur ? '<span class="warn">running: ' + esc(cur.kind) + ' ' + esc(cur.id) + '</span>' : '') +
|
||||||
|
'</div>';
|
||||||
|
const last = cur || (s.jobs && s.jobs[0]);
|
||||||
|
if (last) {
|
||||||
|
const cls = last.status === 'done' ? 'ok' : last.status === 'running' ? 'warn' : 'bad';
|
||||||
|
html += '<p style="margin:.8rem 0 0"><span class="' + cls + '">' + esc(last.status) + '</span> <span class="mono">' + esc(last.kind) + ' ' + esc(last.id) + '</span> <span class="muted">' + esc(last.startedAt || '') + (last.exitCode != null ? ' · exit ' + last.exitCode : '') + '</span> <button class="small" data-job="' + esc(last.id) + '">log</button></p>' +
|
||||||
|
'<pre id="tr-log" hidden></pre>';
|
||||||
|
}
|
||||||
|
const vs = s.versions || [];
|
||||||
|
html += '<h2 style="margin-top:1rem">Versions</h2>';
|
||||||
|
html += vs.length
|
||||||
|
? '<table><thead><tr><th>version</th><th>model</th><th>accuracy</th><th>classes</th><th>mode</th><th></th></tr></thead><tbody>' +
|
||||||
|
vs.map(v => '<tr><td class="mono">' + esc(v.version) + '</td><td>' + (v.written ? '<span class="ok">written</span>' : '<span class="bad">refused</span>') + '</td><td>' + pct(v.accuracy) + (v.floor != null ? ' <span class="muted">/ floor ' + pct(v.floor) + '</span>' : '') + '</td><td class="muted">' + esc((v.classes || []).join(', ')) + '</td><td class="muted">' + esc(v.mode || '') + '</td><td>' +
|
||||||
|
'<button class="small" data-report="' + esc(v.version) + '">report</button> ' +
|
||||||
|
(v.written ? '<button class="small" data-eval="' + esc(v.version) + '"' + (cur ? ' disabled' : '') + '>evaluate</button> <button class="small" data-publish="' + esc(v.version) + '"' + (cur ? ' disabled' : '') + '>publish</button>' : '') +
|
||||||
|
'</td></tr>').join('') + '</tbody></table>'
|
||||||
|
: '<p class="muted">no runs yet</p>';
|
||||||
|
html += '<pre id="tr-report" hidden></pre>';
|
||||||
|
html += '<p class="muted" style="margin:.8rem 0 0">A written model is only a file here. To put it on a booth: publish, then pin the version in <span class="mono">apps/vision/models/bodytype.version</span>, commit, and bump the TAG of the booth.</p>';
|
||||||
|
el.innerHTML = html;
|
||||||
|
|
||||||
|
const trainBtn = document.getElementById('tr-train');
|
||||||
|
if (trainBtn) trainBtn.addEventListener('click', () => startJob({ kind: 'train', mode: document.getElementById('tr-mode').value, backbone: document.getElementById('tr-backbone').value, minAccuracy: Number(document.getElementById('tr-floor').value) }));
|
||||||
|
el.querySelectorAll('button[data-eval]').forEach(b => b.addEventListener('click', () => startJob({ kind: 'evaluate', version: b.dataset.eval })));
|
||||||
|
el.querySelectorAll('button[data-publish]').forEach(b => b.addEventListener('click', () => { if (confirm('Publish ' + b.dataset.publish + ' to the package registry?')) startJob({ kind: 'publish', version: b.dataset.publish }); }));
|
||||||
|
el.querySelectorAll('button[data-job]').forEach(b => b.addEventListener('click', () => showLog(b.dataset.job)));
|
||||||
|
el.querySelectorAll('button[data-report]').forEach(b => b.addEventListener('click', () => showReport(b.dataset.report)));
|
||||||
|
if (cur) showLog(cur.id).catch(() => {});
|
||||||
|
if (trShownReport) showReport(trShownReport).catch(() => {});
|
||||||
|
schedule(!!cur);
|
||||||
|
}
|
||||||
|
|
||||||
|
function schedule(soon) {
|
||||||
|
if (trPoll) clearTimeout(trPoll);
|
||||||
|
trPoll = setTimeout(() => training().catch(() => {}), soon ? 4000 : 60000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startJob(body) {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/training/jobs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||||||
|
if (!r.ok) { const e = await r.json().catch(() => ({})); alert('trainer: ' + (e.error || ('HTTP ' + r.status))); }
|
||||||
|
} catch (e) { alert(e.message); }
|
||||||
|
training().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function showLog(id) {
|
||||||
|
const j = await api('/api/training/jobs/' + encodeURIComponent(id));
|
||||||
|
const pre = document.getElementById('tr-log');
|
||||||
|
if (!pre) return;
|
||||||
|
pre.hidden = false;
|
||||||
|
pre.textContent = j.log || '(no output yet)';
|
||||||
|
pre.scrollTop = pre.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function showReport(v) {
|
||||||
|
const r = await fetch('/api/training/versions/' + encodeURIComponent(v) + '/report');
|
||||||
|
const pre = document.getElementById('tr-report');
|
||||||
|
if (!pre) return;
|
||||||
|
trShownReport = v;
|
||||||
|
pre.hidden = false;
|
||||||
|
pre.textContent = r.ok ? await r.text() : 'no report for ' + v + ' (HTTP ' + r.status + ')';
|
||||||
|
}
|
||||||
|
|
||||||
|
training().catch(() => {});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||||
|
import { mkdtemp, rm } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { buildCollector, type CollectorApp } from "./app.js";
|
||||||
|
|
||||||
|
// The Training section's proxy: reviewer-gated, forwards a fixed set of paths to the
|
||||||
|
// trainer's job API, passes its status codes through, and degrades cleanly when the trainer
|
||||||
|
// is not configured or not reachable. The trainer is faked with a bare node http server.
|
||||||
|
|
||||||
|
const REVIEWER = { user: "julian", pass: "review-pass-123" };
|
||||||
|
const basic = "Basic " + Buffer.from(`${REVIEWER.user}:${REVIEWER.pass}`).toString("base64");
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let fake: Server;
|
||||||
|
let fakeUrl: string;
|
||||||
|
let seen: { method: string; url: string; body: string }[];
|
||||||
|
let app: CollectorApp;
|
||||||
|
|
||||||
|
async function start(trainerUrl: string | null): Promise<void> {
|
||||||
|
app = await buildCollector({ host: "127.0.0.1", port: 0, dataDir: dir, boothTokens: new Map(), reviewer: REVIEWER, trainerUrl }, { dbFile: ":memory:" });
|
||||||
|
await app.ready();
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
dir = await mkdtemp(path.join(tmpdir(), "collector-"));
|
||||||
|
seen = [];
|
||||||
|
fake = createServer((req: IncomingMessage, res: ServerResponse) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", (c) => (body += c));
|
||||||
|
req.on("end", () => {
|
||||||
|
seen.push({ method: req.method ?? "", url: req.url ?? "", body });
|
||||||
|
const json = (code: number, obj: unknown) => {
|
||||||
|
res.writeHead(code, { "content-type": "application/json" });
|
||||||
|
res.end(JSON.stringify(obj));
|
||||||
|
};
|
||||||
|
if (req.url === "/health") return json(200, { ok: true, busy: false });
|
||||||
|
if (req.url === "/readiness") return json(200, { ready: false, labelled: { total: 3 } });
|
||||||
|
if (req.url === "/versions") return json(200, { versions: [{ version: "v1", written: true }] });
|
||||||
|
if (req.url === "/jobs" && req.method === "GET") return json(200, { jobs: [{ id: "j1" }], current: null });
|
||||||
|
if (req.url === "/jobs" && req.method === "POST") return body.includes('"busy"') ? json(409, { error: "a job is already running" }) : json(202, { id: "j2", status: "running" });
|
||||||
|
if (req.url === "/jobs/j1") return json(200, { id: "j1", status: "done", log: "ok" });
|
||||||
|
if (req.url === "/versions/v1/report") {
|
||||||
|
res.writeHead(200, { "content-type": "text/markdown; charset=utf-8" });
|
||||||
|
return res.end("# Body-type classifier v1\n");
|
||||||
|
}
|
||||||
|
return json(404, { error: "not found" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>((r) => fake.listen(0, "127.0.0.1", r));
|
||||||
|
const a = fake.address() as { port: number };
|
||||||
|
fakeUrl = `http://127.0.0.1:${a.port}`;
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await app?.close();
|
||||||
|
await new Promise<void>((r) => fake.close(() => r()));
|
||||||
|
await rm(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("review page script", () => {
|
||||||
|
it("parses as JavaScript (an apostrophe in a template literal once broke the whole page)", async () => {
|
||||||
|
const { reviewPage } = await import("./review-page.js");
|
||||||
|
const html = reviewPage();
|
||||||
|
const script = html.slice(html.indexOf("<script>") + 8, html.lastIndexOf("</script>"));
|
||||||
|
expect(() => new Function(script)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("training proxy", () => {
|
||||||
|
it("is hidden when no trainer is configured", async () => {
|
||||||
|
await start(null);
|
||||||
|
const s = await app.inject({ method: "GET", url: "/api/training/status", headers: { authorization: basic } });
|
||||||
|
expect(s.json()).toEqual({ configured: false });
|
||||||
|
const j = await app.inject({ method: "POST", url: "/api/training/jobs", headers: { authorization: basic }, payload: { kind: "train" } });
|
||||||
|
expect(j.statusCode).toBe(503);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aggregates status and forwards jobs and reports behind the reviewer login", async () => {
|
||||||
|
await start(fakeUrl);
|
||||||
|
expect((await app.inject({ method: "GET", url: "/api/training/status" })).statusCode).toBe(401);
|
||||||
|
const s = await app.inject({ method: "GET", url: "/api/training/status", headers: { authorization: basic } });
|
||||||
|
expect(s.statusCode).toBe(200);
|
||||||
|
const body = s.json();
|
||||||
|
expect(body.configured).toBe(true);
|
||||||
|
expect(body.reachable).toBe(true);
|
||||||
|
expect(body.readiness.labelled.total).toBe(3);
|
||||||
|
expect(body.versions[0].version).toBe("v1");
|
||||||
|
expect(body.jobs[0].id).toBe("j1");
|
||||||
|
|
||||||
|
const j = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/training/jobs",
|
||||||
|
headers: { authorization: basic },
|
||||||
|
payload: { kind: "train", mode: "features", minAccuracy: 0.9, secret: "nope", version: "v2" },
|
||||||
|
});
|
||||||
|
expect(j.statusCode).toBe(202);
|
||||||
|
expect(j.json().id).toBe("j2");
|
||||||
|
const posted = seen.find((r) => r.method === "POST")!;
|
||||||
|
expect(JSON.parse(posted.body)).toEqual({ kind: "train", mode: "features", minAccuracy: 0.9, version: "v2" }); // unknown keys dropped
|
||||||
|
|
||||||
|
const busy = await app.inject({ method: "POST", url: "/api/training/jobs", headers: { authorization: basic }, payload: { kind: "evaluate", version: "busy" } });
|
||||||
|
expect(busy.statusCode).toBe(409); // the trainer's answer passes through
|
||||||
|
|
||||||
|
const bad = await app.inject({ method: "POST", url: "/api/training/jobs", headers: { authorization: basic }, payload: { kind: "rm-rf" } });
|
||||||
|
expect(bad.statusCode).toBe(400);
|
||||||
|
|
||||||
|
const one = await app.inject({ method: "GET", url: "/api/training/jobs/j1", headers: { authorization: basic } });
|
||||||
|
expect(one.json().status).toBe("done");
|
||||||
|
expect((await app.inject({ method: "GET", url: "/api/training/jobs/..%2Fx", headers: { authorization: basic } })).statusCode).toBe(400);
|
||||||
|
|
||||||
|
const rep = await app.inject({ method: "GET", url: "/api/training/versions/v1/report", headers: { authorization: basic } });
|
||||||
|
expect(rep.statusCode).toBe(200);
|
||||||
|
expect(rep.headers["content-type"]).toContain("text/markdown");
|
||||||
|
expect(rep.body).toContain("# Body-type classifier v1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports an unreachable trainer without failing the page", async () => {
|
||||||
|
await start("http://127.0.0.1:9"); // nothing listens on the discard port
|
||||||
|
const s = await app.inject({ method: "GET", url: "/api/training/status", headers: { authorization: basic } });
|
||||||
|
expect(s.statusCode).toBe(200);
|
||||||
|
expect(s.json().reachable).toBe(false);
|
||||||
|
const j = await app.inject({ method: "POST", url: "/api/training/jobs", headers: { authorization: basic }, payload: { kind: "train" } });
|
||||||
|
expect(j.statusCode).toBe(502);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Parking System",
|
"productName": "Parking System",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"identifier": "com.parking.desktop",
|
"identifier": "com.parking.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"devUrl": "http://localhost:5173",
|
"devUrl": "http://localhost:5173",
|
||||||
|
|||||||
@@ -76,7 +76,10 @@ WS_ALLOWED_ORIGINS=http://localhost:5173,tauri://localhost,http://tauri.localhos
|
|||||||
# camera's vehicle detection, admits them through the gated SubscriptionFlow. Opt-in per
|
# camera's vehicle detection, admits them through the gated SubscriptionFlow. Opt-in per
|
||||||
# camera (the camera's config.anpr checkbox in Setup); the camera must be BOUND to a relay.
|
# camera (the camera's config.anpr checkbox in Setup); the camera must be BOUND to a relay.
|
||||||
# VISION_ENTRY_MIN_CONFIDENCE=0.85 # stricter floor for a BARRIER-driving read (near-miss → falls back to card/QR)
|
# VISION_ENTRY_MIN_CONFIDENCE=0.85 # stricter floor for a BARRIER-driving read (near-miss → falls back to card/QR)
|
||||||
# ANPR_DEBOUNCE_MS=12000 # same plate/camera within this window = ONE presentation (camera re-fires ~1Hz)
|
# ANPR_DEBOUNCE_MS=12000 # same PLATE on the same camera within this window = ONE presentation (never per camera)
|
||||||
|
# ANPR_POLL_MS=0 # MIN spacing between frame pulls while a car is in the zone; 0 = back-to-back (~3 fps/camera)
|
||||||
|
# ANPR_POLL_WINDOW_MS=8000 # keep reading this long after the camera's LAST vehicle push (0 = one frame per push)
|
||||||
|
# ANPR_POLL_MAX_MS=30000 # hard cap on one loop from its start, however busy the lane
|
||||||
|
|
||||||
# Venue modules --------------------------------------------------------------
|
# Venue modules --------------------------------------------------------------
|
||||||
# Comma-separated ids of the modules this site is ENTITLED to (a vendor/deployment
|
# Comma-separated ids of the modules this site is ENTITLED to (a vendor/deployment
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db } from "@parking/db";
|
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db } from "@parking/db";
|
||||||
import { createTestDb } from "@parking/db/testing";
|
import { createTestDb } from "@parking/db/testing";
|
||||||
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
|
import { deviceEvents, type DeviceReadEvent, type VehicleReadEvent } from "./device-events.js";
|
||||||
import { silentLogger } from "./test-helpers.js";
|
import { silentLogger } from "./test-helpers.js";
|
||||||
import type { VisionClient, VisionResult } from "./vision-client.js";
|
import type { VisionClient, VisionResult, VisionVehicle } from "./vision-client.js";
|
||||||
import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js";
|
import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js";
|
||||||
|
|
||||||
// The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a
|
// The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a
|
||||||
@@ -14,7 +14,12 @@ import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js
|
|||||||
|
|
||||||
// Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub
|
// Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub
|
||||||
// (no registry, no network). The factory returns a fresh shot each call.
|
// (no registry, no network). The factory returns a fresh shot each call.
|
||||||
const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg" }));
|
const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg", capturedAt: new Date().toISOString() }));
|
||||||
|
// The pass sample's box normalisation (needs a real JPEG header in prod) — stubbed so a
|
||||||
|
// test can hand the bridge a vehicle box, or none.
|
||||||
|
const { normalizedBoxes } = vi.hoisted(() => ({
|
||||||
|
normalizedBoxes: vi.fn(async (): Promise<{ vehicleBox: unknown; plateBox: unknown }> => ({ vehicleBox: null, plateBox: null })),
|
||||||
|
}));
|
||||||
// The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in
|
// The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in
|
||||||
// snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this
|
// snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this
|
||||||
// suite stays focused on the bridge's own match/debounce/emit logic.
|
// suite stays focused on the bridge's own match/debounce/emit logic.
|
||||||
@@ -22,6 +27,9 @@ vi.mock("./snapshot.js", () => ({
|
|||||||
buildCamera: () => ({ captureSnapshot }),
|
buildCamera: () => ({ captureSnapshot }),
|
||||||
captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) =>
|
captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) =>
|
||||||
camera.captureSnapshot(ctx as never),
|
camera.captureSnapshot(ctx as never),
|
||||||
|
// Storage re-encode is sharp's business (snapshot.test.ts); here the bytes pass through.
|
||||||
|
encodeForStorage: async (shot: { bytes: Buffer; contentType: string }) => ({ bytes: shot.bytes, contentType: shot.contentType }),
|
||||||
|
normalizedBoxes,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Import AFTER the mock is registered.
|
// Import AFTER the mock is registered.
|
||||||
@@ -31,11 +39,14 @@ let db: Db;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
({ db } = createTestDb());
|
({ db } = createTestDb());
|
||||||
captureSnapshot.mockClear();
|
captureSnapshot.mockClear();
|
||||||
|
normalizedBoxes.mockReset();
|
||||||
|
normalizedBoxes.mockResolvedValue({ vehicleBox: null, plateBox: null });
|
||||||
delete process.env.VISION_ENTRY_MIN_CONFIDENCE;
|
delete process.env.VISION_ENTRY_MIN_CONFIDENCE;
|
||||||
delete process.env.ANPR_DEBOUNCE_MS;
|
delete process.env.ANPR_DEBOUNCE_MS;
|
||||||
// Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate
|
// Read-every-frame loop: keep the window tiny so a loop ends in a few ticks instead of the
|
||||||
// case gives up in ~one tick instead of the 8s production window (tests stay fast). Each
|
// 8s production window (tests stay fast); the 1ms floor keeps a mocked loop from spinning
|
||||||
// bridge reads these in its constructor, so set them before `new AnprBridge`.
|
// thousands of frames. Each bridge reads these in its constructor, so set them before
|
||||||
|
// `new AnprBridge`.
|
||||||
process.env.ANPR_POLL_MS = "1";
|
process.env.ANPR_POLL_MS = "1";
|
||||||
process.env.ANPR_POLL_WINDOW_MS = "5";
|
process.env.ANPR_POLL_WINDOW_MS = "5";
|
||||||
});
|
});
|
||||||
@@ -74,17 +85,18 @@ function seedCamera(opts: { anpr?: boolean; anprAutoTrigger?: boolean } = {}): s
|
|||||||
return camId;
|
return camId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null). */
|
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null), and
|
||||||
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number } = {}): VisionClient {
|
* optionally a vehicle (body type + box) the way the vehicle stage reports it. */
|
||||||
|
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number; vehicle?: VisionVehicle } = {}): VisionClient {
|
||||||
const enabled = opts.enabled ?? true;
|
const enabled = opts.enabled ?? true;
|
||||||
const result: VisionResult | null =
|
const result: VisionResult | null =
|
||||||
opts.plate == null
|
opts.plate == null && opts.vehicle == null
|
||||||
? null
|
? null
|
||||||
: {
|
: {
|
||||||
plate: { text: opts.plate, confidence: opts.confidence ?? 0.99 },
|
plate: opts.plate == null ? null : { text: opts.plate, confidence: opts.confidence ?? 0.99 },
|
||||||
plates: [],
|
plates: [],
|
||||||
lowConfidence: false,
|
lowConfidence: false,
|
||||||
vehicle: null,
|
vehicle: opts.vehicle ?? null,
|
||||||
modelVersion: "test",
|
modelVersion: "test",
|
||||||
tookMs: 1,
|
tookMs: 1,
|
||||||
};
|
};
|
||||||
@@ -96,19 +108,35 @@ function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: numb
|
|||||||
|
|
||||||
/** A fake SubscriptionFlow: only `match()` is called by the bridge. */
|
/** A fake SubscriptionFlow: only `match()` is called by the bridge. */
|
||||||
function fakeSubFlow(
|
function fakeSubFlow(
|
||||||
match: SubscriptionMatch | null,
|
// A fixed answer, or a matcher by plate (several subscribers in one loop).
|
||||||
|
match: SubscriptionMatch | null | ((plate: string) => SubscriptionMatch | null),
|
||||||
// openOccurrenceCount: a constant, or a sequence consumed per call (to simulate a
|
// openOccurrenceCount: a constant, or a sequence consumed per call (to simulate a
|
||||||
// credential closing an occurrence mid-poll → count changes).
|
// credential closing an occurrence mid-poll → count changes).
|
||||||
openCounts: number | number[] = 1,
|
openCounts: number | number[] = 1,
|
||||||
): SubscriptionFlow {
|
): SubscriptionFlow {
|
||||||
const seq = Array.isArray(openCounts) ? [...openCounts] : null;
|
const seq = Array.isArray(openCounts) ? [...openCounts] : null;
|
||||||
return {
|
return {
|
||||||
match: vi.fn(() => match),
|
match: vi.fn((e: DeviceReadEvent) => (typeof match === "function" ? match(e.value) : match)),
|
||||||
openOccurrenceCount: vi.fn(() => (seq ? (seq.length > 1 ? seq.shift()! : seq[0]) : (openCounts as number))),
|
openOccurrenceCount: vi.fn(() => (seq ? (seq.length > 1 ? seq.shift()! : seq[0]) : (openCounts as number))),
|
||||||
} as unknown as SubscriptionFlow;
|
} as unknown as SubscriptionFlow;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SUB_MATCH: SubscriptionMatch = { subscriptionId: "sub-1", carKey: "AA111BB", via: "plate" };
|
const SUB_MATCH: SubscriptionMatch = { subscriptionId: "sub-1", carKey: "AA111BB", via: "plate" };
|
||||||
|
const SUB_MATCH_2: SubscriptionMatch = { subscriptionId: "sub-2", carKey: "CC333DD", via: "plate" };
|
||||||
|
|
||||||
|
/** A VisionClient whose analyze() walks a sequence of (plate, confidence) frames, holding the
|
||||||
|
* last one — the way a car's read evolves as it approaches and settles, or as one car gives
|
||||||
|
* way to the next. `vehicle` (optional) rides every frame. */
|
||||||
|
function sequenceVision(frames: { plate: string; confidence: number }[], vehicle: VisionVehicle | null = null): VisionClient {
|
||||||
|
let i = 0;
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
analyze: vi.fn(async () => {
|
||||||
|
const f = frames[Math.min(i++, frames.length - 1)]!;
|
||||||
|
return { plate: { text: f.plate, confidence: f.confidence }, plates: [], lowConfidence: false, vehicle, modelVersion: "test", tookMs: 1 };
|
||||||
|
}),
|
||||||
|
} as unknown as VisionClient;
|
||||||
|
}
|
||||||
|
|
||||||
/** Capture read events emitted during `fn` (async). */
|
/** Capture read events emitted during `fn` (async). */
|
||||||
async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]> {
|
async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]> {
|
||||||
@@ -122,6 +150,79 @@ async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]>
|
|||||||
return got;
|
return got;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Capture vehicle-read (pass sample) events during `fn`, waiting for the bridge's
|
||||||
|
* fire-and-forget recording to land. */
|
||||||
|
async function captureVehicleReads(fn: () => Promise<void>, expectCount: number): Promise<VehicleReadEvent[]> {
|
||||||
|
const got: VehicleReadEvent[] = [];
|
||||||
|
const off = deviceEvents.onVehicleRead((e) => got.push(e));
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
if (expectCount > 0) await vi.waitFor(() => expect(got).toHaveLength(expectCount));
|
||||||
|
else await new Promise((r) => setTimeout(r, 20));
|
||||||
|
} finally {
|
||||||
|
off();
|
||||||
|
}
|
||||||
|
return got;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("AnprBridge pass sample — every detected car, ticket or not", () => {
|
||||||
|
const VEHICLE: VisionVehicle = { bodyType: "car", confidence: 0.91, bbox: { x1: 10, y1: 10, x2: 200, y2: 120 } };
|
||||||
|
const BOX = { x1: 0.1, y1: 0.1, x2: 0.5, y2: 0.6 };
|
||||||
|
|
||||||
|
it("stores the frame + emits a vehicle read with NO plate at all (barriers up: no ticket, no session)", async () => {
|
||||||
|
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
const bridge = new AnprBridge(db, fakeVision({ vehicle: VEHICLE }), fakeSubFlow(null), silentLogger());
|
||||||
|
|
||||||
|
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 1);
|
||||||
|
const read = got[0]!;
|
||||||
|
expect(read).toMatchObject({ direction: "entry", deviceId: cam, read: { bodyType: "car", confidence: 0.91, box: BOX, plateBox: null } });
|
||||||
|
expect(read.identity).toBe(`pass:${read.read.snapshotId}`);
|
||||||
|
const row = db.select().from(snapshots).where(eq(snapshots.id, read.read.snapshotId!)).get();
|
||||||
|
expect(row).toMatchObject({ direction: "entry", deviceId: cam, identity: read.identity, contentType: "image/jpeg" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is ONE sample per car even when the loop polls several frames, and rides along a subscriber emit", async () => {
|
||||||
|
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: { x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 } });
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
const bridge = new AnprBridge(db, fakeVision({ plate: "AA111BB", confidence: 0.97, vehicle: VEHICLE }), fakeSubFlow(SUB_MATCH), silentLogger());
|
||||||
|
|
||||||
|
let reads: DeviceReadEvent[] = [];
|
||||||
|
const got = await captureVehicleReads(async () => {
|
||||||
|
reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
||||||
|
}, 1);
|
||||||
|
expect(reads).toHaveLength(1); // the subscriber's plate read still goes out
|
||||||
|
expect(got[0]!.read.plateBox).toEqual({ x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 }); // for the crop's blur
|
||||||
|
expect(db.select().from(snapshots).all()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("samples EACH plated car of a loop once — two cars back to back → two samples", async () => {
|
||||||
|
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
// Car A (3 frames) then car B, both framed; a non-subscriber lot (match null) — the
|
||||||
|
// sample is about the reviewer's stream, not about admission.
|
||||||
|
const vision = sequenceVision(
|
||||||
|
[{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 }, { plate: "CC333DD", confidence: 0.96 }],
|
||||||
|
VEHICLE,
|
||||||
|
);
|
||||||
|
process.env.ANPR_POLL_WINDOW_MS = "200";
|
||||||
|
const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger());
|
||||||
|
|
||||||
|
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 2);
|
||||||
|
expect(got).toHaveLength(2);
|
||||||
|
expect(db.select().from(snapshots).all()).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records nothing without a vehicle box (nothing to crop) — a bare class is not a sample", async () => {
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
const bridge = new AnprBridge(db, fakeVision({ vehicle: { bodyType: "car", confidence: 0.9 } }), fakeSubFlow(null), silentLogger());
|
||||||
|
|
||||||
|
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 0);
|
||||||
|
expect(got).toEqual([]);
|
||||||
|
expect(db.select().from(snapshots).all()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("AnprBridge", () => {
|
describe("AnprBridge", () => {
|
||||||
it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => {
|
it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => {
|
||||||
const cam = seedCamera({ anpr: false });
|
const cam = seedCamera({ anpr: false });
|
||||||
@@ -184,9 +285,10 @@ describe("AnprBridge", () => {
|
|||||||
})),
|
})),
|
||||||
} as unknown as VisionClient;
|
} as unknown as VisionClient;
|
||||||
// Generous window so all 3 escalation attempts run deterministically under suite load
|
// Generous window so all 3 escalation attempts run deterministically under suite load
|
||||||
// (the global beforeEach sets a tiny 5ms window for the give-up cases).
|
// (the global beforeEach sets a tiny 5ms window for the give-up cases). The loop keeps
|
||||||
|
// reading until the window ends — the same plate must still be emitted exactly once.
|
||||||
process.env.ANPR_POLL_MS = "1";
|
process.env.ANPR_POLL_MS = "1";
|
||||||
process.env.ANPR_POLL_WINDOW_MS = "2000";
|
process.env.ANPR_POLL_WINDOW_MS = "150";
|
||||||
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
|
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
|
||||||
|
|
||||||
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
||||||
@@ -232,18 +334,40 @@ describe("AnprBridge", () => {
|
|||||||
expect(reads[0]).toMatchObject({ value: "AA111BB" });
|
expect(reads[0]).toMatchObject({ value: "AA111BB" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("ABORTS if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
|
it("does NOT emit if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
|
||||||
// The car's plate is read (identity known) but stays below the floor; meanwhile the
|
// The car's plate is read (identity known) while still below the floor; meanwhile the
|
||||||
// subscriber scans their card → openOccurrenceCount drops. The bridge must abort and NOT
|
// subscriber scans their card → openOccurrenceCount drops. When the plate finally reads
|
||||||
// emit (which would exit the NEXT open occurrence — a phantom double-exit, esp. fleet).
|
// confidently the bridge must NOT emit (it would exit the NEXT open occurrence — a
|
||||||
|
// phantom double-exit, esp. fleet).
|
||||||
const cam = seedCamera({ anpr: true });
|
const cam = seedCamera({ anpr: true });
|
||||||
const vision = fakeVision({ plate: "AA111BB", confidence: 0.5 }); // never clears the floor
|
const vision = sequenceVision([{ plate: "AA111BB", confidence: 0.5 }, { plate: "AA111BB", confidence: 0.97 }]);
|
||||||
// openOccurrenceCount: 1 at baseline, then 0 (the card exit closed it) on the next check.
|
// openOccurrenceCount: 1 at first sighting, then 0 (the card exit closed it) at settle time.
|
||||||
const sub = fakeSubFlow(SUB_MATCH, [1, 0]);
|
const sub = fakeSubFlow(SUB_MATCH, [1, 0]);
|
||||||
|
process.env.ANPR_POLL_WINDOW_MS = "200";
|
||||||
const bridge = new AnprBridge(db, vision, sub, silentLogger());
|
const bridge = new AnprBridge(db, vision, sub, silentLogger());
|
||||||
|
|
||||||
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
||||||
expect(reads).toEqual([]); // aborted — the credential already handled it
|
expect(reads).toEqual([]); // declined — the credential already handled it
|
||||||
|
expect(vision.analyze).toHaveBeenCalledTimes; // (the loop itself kept going)
|
||||||
|
});
|
||||||
|
|
||||||
|
it("KEEPS READING after a confident plate: a second car in the same loop is emitted too", async () => {
|
||||||
|
// Car A reads confidently on frames 1-3, then car B pulls into the zone (frames 4+).
|
||||||
|
// Before 2026-10-11 the loop broke on A's first read and the camera-level debounce then
|
||||||
|
// dropped every push for 12s — B was invisible. Now A is settled once and the loop goes
|
||||||
|
// on; B is read by the same loop. Each plate exactly once, however many frames repeat.
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
const vision = sequenceVision([
|
||||||
|
{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 },
|
||||||
|
{ plate: "CC333DD", confidence: 0.96 },
|
||||||
|
]);
|
||||||
|
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
|
||||||
|
process.env.ANPR_POLL_WINDOW_MS = "200";
|
||||||
|
const bridge = new AnprBridge(db, vision, sub, silentLogger());
|
||||||
|
|
||||||
|
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
|
||||||
|
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
|
||||||
|
expect(captureSnapshot.mock.calls.length).toBeGreaterThan(4); // it did not stop at A
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does NOT emit for a plate matching no subscription — records an advisory anpr-skip", async () => {
|
it("does NOT emit for a plate matching no subscription — records an advisory anpr-skip", async () => {
|
||||||
@@ -275,17 +399,34 @@ describe("AnprBridge", () => {
|
|||||||
expect(skips).toHaveLength(1);
|
expect(skips).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("debounces: two vehicle events within the window analyze/emit at most once", async () => {
|
it("debounces PER PLATE: the same car re-detected within the window is emitted once", async () => {
|
||||||
const cam = seedCamera({ anpr: true });
|
const cam = seedCamera({ anpr: true });
|
||||||
const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 });
|
const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 });
|
||||||
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
|
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
|
||||||
|
|
||||||
const reads = await captureReads(async () => {
|
const reads = await captureReads(async () => {
|
||||||
await bridge.onVehicleDetected(cam);
|
await bridge.onVehicleDetected(cam);
|
||||||
await bridge.onVehicleDetected(cam); // within the 12s window → suppressed
|
await bridge.onVehicleDetected(cam); // a second loop — the same plate within 12s → suppressed
|
||||||
});
|
});
|
||||||
expect(reads).toHaveLength(1);
|
expect(reads).toHaveLength(1);
|
||||||
expect(captureSnapshot).toHaveBeenCalledTimes(1); // 2nd was gated before the snapshot
|
expect(captureSnapshot.mock.calls.length).toBeGreaterThanOrEqual(2); // the 2nd loop DID look
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is NOT blind after a read: a different car detected right after is emitted", async () => {
|
||||||
|
// The old camera-level debounce dropped every push for 12s after a success. A car behind
|
||||||
|
// the first, arriving after the first loop ended, must get its own loop and its own read.
|
||||||
|
const cam = seedCamera({ anpr: true });
|
||||||
|
const frames = [{ plate: "AA111BB", confidence: 0.97 }];
|
||||||
|
const vision = sequenceVision(frames);
|
||||||
|
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
|
||||||
|
const bridge = new AnprBridge(db, vision, sub, silentLogger());
|
||||||
|
|
||||||
|
const reads = await captureReads(async () => {
|
||||||
|
await bridge.onVehicleDetected(cam); // car A
|
||||||
|
frames[0] = { plate: "CC333DD", confidence: 0.96 }; // car B now in the zone
|
||||||
|
await bridge.onVehicleDetected(cam); // its push starts a new loop
|
||||||
|
});
|
||||||
|
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("is a no-op (no throw) when vision is disabled or reads nothing", async () => {
|
it("is a no-op (no throw) when vision is disabled or reads nothing", async () => {
|
||||||
|
|||||||
+191
-118
@@ -1,21 +1,31 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db, type DeviceRow } from "@parking/db";
|
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db, type DeviceRow } from "@parking/db";
|
||||||
|
import type { Snapshot } from "@parking/devices";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
|
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
|
||||||
import { directionOf, type FlowDirection } from "./device-resolve.js";
|
import { directionOf, type FlowDirection } from "./device-resolve.js";
|
||||||
import { buildCamera } from "./snapshot.js";
|
import { buildCamera, encodeForStorage, normalizedBoxes } from "./snapshot.js";
|
||||||
import type { SubscriptionFlow } from "./subscription-flow.js";
|
import type { SubscriptionFlow } from "./subscription-flow.js";
|
||||||
import type { VisionClient } from "./vision-client.js";
|
import type { VisionClient, VisionResult } from "./vision-client.js";
|
||||||
|
|
||||||
// The ANPR "bridge": a subscriber's plate, read from the lane camera, admits them through
|
// The ANPR "bridge": a subscriber's plate, read from the lane camera, admits them through
|
||||||
// the SAME gated SubscriptionFlow a QR/card scan uses. It is the one missing wire between
|
// the SAME gated SubscriptionFlow a QR/card scan uses. It is the one missing wire between
|
||||||
// the camera's vehicle PUSH (hikvision-alarm.ts) and the read bus — NOT a new service.
|
// the camera's vehicle PUSH (hikvision-alarm.ts) and the read bus — NOT a new service.
|
||||||
//
|
//
|
||||||
// On a `vehicle`/`active` event from an OPT-IN camera (config.anpr === true), the bridge:
|
// On a `vehicle`/`active` event from an OPT-IN camera (config.anpr === true), the bridge runs
|
||||||
// pull a fresh snapshot → vision.analyze → entry confidence floor → debounce → MATCH the
|
// ONE poll loop per camera: while the camera keeps pushing (a car is moving in the zone) it
|
||||||
// plate to a subscription → emit a DeviceReadEvent{kind:"plate"} ONLY if it matched.
|
// pulls fresh frames back-to-back → vision.analyze → entry confidence floor → MATCH the plate
|
||||||
// The existing onRead → ReadDispatcher then re-matches and runs the gated SubscriptionFlow
|
// to a subscription → emit a DeviceReadEvent{kind:"plate"} ONLY if it matched — once per
|
||||||
// (active / window / blocklist / car-count), which signs the entry/exit and opens the relay.
|
// plate per loop, and once per plate per ANPR_DEBOUNCE_MS across loops. The existing onRead →
|
||||||
|
// ReadDispatcher then re-matches and runs the gated SubscriptionFlow (active / window /
|
||||||
|
// blocklist / car-count), which signs the entry/exit and opens the relay.
|
||||||
|
//
|
||||||
|
// The loop does NOT stop at the first confident plate (2026-10-11). The camera fires an
|
||||||
|
// independent push on every motion (~1.2 s apart while a car moves — park-2, 2780 pushes, all
|
||||||
|
// activePostCount=1, never `inactive`), so a second car tailgating the first keeps the loop
|
||||||
|
// alive and is read by the same loop. Before, the loop broke on the first read and a 12 s
|
||||||
|
// CAMERA-level debounce then dropped every push — 40 of 57 plate-driven opens at park-2 had
|
||||||
|
// a push land in that blind window. The debounce is per PLATE now.
|
||||||
//
|
//
|
||||||
// INVARIANTS (see wiki/concepts/lane-presence-and-anpr-entry.md §2, append-only-event-chain.md):
|
// INVARIANTS (see wiki/concepts/lane-presence-and-anpr-entry.md §2, append-only-event-chain.md):
|
||||||
// - Advisory, never sole authority: the bridge only emitRead()s — the signed decision +
|
// - Advisory, never sole authority: the bridge only emitRead()s — the signed decision +
|
||||||
@@ -25,7 +35,8 @@ import type { VisionClient } from "./vision-client.js";
|
|||||||
// transient plate-as-ticket exit flow.
|
// transient plate-as-ticket exit flow.
|
||||||
// - Fail-soft + fire-and-forget: any snapshot/vision error degrades to the card/QR path;
|
// - Fail-soft + fire-and-forget: any snapshot/vision error degrades to the card/QR path;
|
||||||
// never throws into the push handler, never awaited on the camera's 200 response.
|
// never throws into the push handler, never awaited on the camera's 200 response.
|
||||||
// - Opt-in per camera, and debounced (the camera re-fires ~1Hz while a car sits).
|
// - Opt-in per camera, and debounced PER PLATE (the same car reads confidently on every
|
||||||
|
// frame once it is framed; one presentation = one read).
|
||||||
|
|
||||||
/** Camera config flag opting it into the ANPR bridge (same flag advisory ANPR uses). */
|
/** Camera config flag opting it into the ANPR bridge (same flag advisory ANPR uses). */
|
||||||
interface CameraConfig {
|
interface CameraConfig {
|
||||||
@@ -45,22 +56,26 @@ function entryMinConfidence(): number {
|
|||||||
return Number.isFinite(raw) && raw > 0 ? raw : 0.85;
|
return Number.isFinite(raw) && raw > 0 ? raw : 0.85;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Same plate/camera within this window = ONE credential presentation. The camera re-fires
|
/** Same plate on the same camera within this window = ONE credential presentation. A framed
|
||||||
* ~1Hz while a car is present; emitting every second would drive repeat entries (a fleet
|
* car reads confidently on every frame, and a car that stops and re-starts in the zone
|
||||||
* sub opens a 2nd occurrence) or exit spam. Required for correctness, not CPU. */
|
* starts a new loop; emitting each time would drive repeat entries (a fleet sub opens a 2nd
|
||||||
|
* occurrence) or exit spam. Keyed by PLATE, never by camera — a camera-level stamp made the
|
||||||
|
* lane blind to the next car for the whole window. Required for correctness, not CPU. */
|
||||||
function debounceMs(): number {
|
function debounceMs(): number {
|
||||||
const raw = Number(process.env.ANPR_DEBOUNCE_MS ?? 12_000);
|
const raw = Number(process.env.ANPR_DEBOUNCE_MS ?? 12_000);
|
||||||
return Number.isFinite(raw) && raw > 0 ? raw : 12_000;
|
return Number.isFinite(raw) && raw > 0 ? raw : 12_000;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A single alarm fires the INSTANT motion starts — the car is still approaching, so the
|
/** A single alarm fires the INSTANT motion starts — the car is still approaching, so the
|
||||||
* first frame often has a small/blurry/absent plate (a low-confidence misread). But the car
|
* first frame often has a small/blurry/absent plate (a low-confidence misread). The readable
|
||||||
* then STOPS at the barrier (waiting for it to open) — the same stationary, well-framed
|
* moments (stopped at the barrier; a gap in headlight glare) are short, so the loop pulls
|
||||||
* moment the manual test reads at ~100%. So instead of one shot, we POLL fresh frames and
|
* frames BACK-TO-BACK: a pull is ~0.1 s and an analyze ~0.25 s on the booth (park-2,
|
||||||
* re-run ANPR until one clears the confidence floor, or the window elapses. Poll interval: */
|
* 2026-10-11), i.e. ~3 frames/s per camera, serial, which the camera's single-threaded
|
||||||
|
* picture endpoint takes without a 503. This is the MINIMUM spacing between two pulls
|
||||||
|
* (ms); 0 = as fast as the camera + recognizer go. Raise it to throttle a weak host. */
|
||||||
function pollMs(): number {
|
function pollMs(): number {
|
||||||
const raw = Number(process.env.ANPR_POLL_MS ?? 1000);
|
const raw = Number(process.env.ANPR_POLL_MS ?? 0);
|
||||||
return Number.isFinite(raw) && raw > 0 ? raw : 1000;
|
return Number.isFinite(raw) && raw >= 0 ? raw : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How long to keep polling AFTER THE LAST vehicle push before giving up. SLIDING: each new
|
/** How long to keep polling AFTER THE LAST vehicle push before giving up. SLIDING: each new
|
||||||
@@ -69,7 +84,7 @@ function pollMs(): number {
|
|||||||
* barrier (the loop tracks "whoever is here now", not the car that started it). */
|
* barrier (the loop tracks "whoever is here now", not the car that started it). */
|
||||||
function pollWindowMs(): number {
|
function pollWindowMs(): number {
|
||||||
const raw = Number(process.env.ANPR_POLL_WINDOW_MS ?? 8000);
|
const raw = Number(process.env.ANPR_POLL_WINDOW_MS ?? 8000);
|
||||||
return Number.isFinite(raw) && raw > 0 ? raw : 8000;
|
return Number.isFinite(raw) && raw >= 0 ? raw : 8000; // 0 = one frame per push
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Hard ceiling on a single loop from its START, so a continuously-busy lane (pushes never
|
/** Hard ceiling on a single loop from its START, so a continuously-busy lane (pushes never
|
||||||
@@ -97,11 +112,12 @@ export class AnprBridge {
|
|||||||
readonly #pollMs: number;
|
readonly #pollMs: number;
|
||||||
readonly #pollWindowMs: number;
|
readonly #pollWindowMs: number;
|
||||||
readonly #pollMaxMs: number;
|
readonly #pollMaxMs: number;
|
||||||
/** Last-fire timestamps, keyed by deviceId (camera-level, pre-snapshot) AND by
|
/** Last emit timestamps keyed by `deviceId:plate`, gated against #debounceMs. Nothing is
|
||||||
* `deviceId:plate` (post-match) — both gated against #debounceMs. */
|
* keyed by camera: the lane must never go blind to the NEXT car. Pruned on stamp. */
|
||||||
readonly #lastFire = new Map<string, number>();
|
readonly #lastFire = new Map<string, number>();
|
||||||
/** Cameras with a poll loop already in flight — a re-fired alarm (the camera pushes ~1Hz
|
/** Cameras with a poll loop already in flight — a re-fired alarm (the camera pushes on
|
||||||
* while the car sits) must NOT start a second concurrent loop on the same camera. */
|
* every motion while a car moves) must NOT start a second concurrent loop on the same
|
||||||
|
* camera: its picture endpoint is single-threaded (a parallel GET gets HTTP 503). */
|
||||||
readonly #polling = new Set<string>();
|
readonly #polling = new Set<string>();
|
||||||
/** Per-camera SLIDING deadline for the running poll loop. A push that joins a running loop
|
/** Per-camera SLIDING deadline for the running poll loop. A push that joins a running loop
|
||||||
* bumps this forward (lastPush + window, capped at start + max), so the loop keeps pulling
|
* bumps this forward (lastPush + window, capped at start + max), so the loop keeps pulling
|
||||||
@@ -143,13 +159,9 @@ export class AnprBridge {
|
|||||||
// car that just entered. Absent ⇒ true (back-compat: existing anpr cameras still trigger).
|
// car that just entered. Absent ⇒ true (back-compat: existing anpr cameras still trigger).
|
||||||
if (cfg.anprAutoTrigger === false) return;
|
if (cfg.anprAutoTrigger === false) return;
|
||||||
|
|
||||||
// Post-success debounce: once we've emitted a read for this camera, ignore the
|
|
||||||
// ~1Hz re-fires for #debounceMs (set on success below). A fresh alarm AFTER the
|
|
||||||
// window is a new presentation and may start a new poll loop.
|
|
||||||
if (this.#debounced(deviceId)) return;
|
|
||||||
// One poll loop per camera. A push that arrives while a loop runs JOINs it — and
|
// One poll loop per camera. A push that arrives while a loop runs JOINs it — and
|
||||||
// SLIDES the deadline forward (a different car arriving mid-loop keeps the loop alive
|
// SLIDES the deadline forward (a different car arriving mid-loop keeps the loop alive
|
||||||
// so it tracks whoever's at the barrier now, instead of giving up on the early car).
|
// so it reads whoever is at the barrier now; the loop never stops on the first plate).
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (this.#polling.has(deviceId)) {
|
if (this.#polling.has(deviceId)) {
|
||||||
const cur = this.#pollDeadline.get(deviceId) ?? now;
|
const cur = this.#pollDeadline.get(deviceId) ?? now;
|
||||||
@@ -172,134 +184,195 @@ export class AnprBridge {
|
|||||||
// the gated flow infers the verb from the camera's bound relay direction).
|
// the gated flow infers the verb from the camera's bound relay direction).
|
||||||
const direction: FlowDirection = directionOf(this.#db, row) === "exit" ? "exit" : "entry";
|
const direction: FlowDirection = directionOf(this.#db, row) === "exit" ? "exit" : "entry";
|
||||||
|
|
||||||
// POLL-UNTIL-CONFIDENT. The alarm fires as the car APPROACHES (small/blurry/absent
|
// READ-EVERY-FRAME. The alarm fires as the car APPROACHES (small/blurry/absent plate →
|
||||||
// plate → low-confidence misread, e.g. '111'@0.20). But the car then STOPS at the
|
// low-confidence misread, e.g. '111'@0.20); the readable moments come later and may be
|
||||||
// barrier — the stationary, well-framed moment the manual test reads at ~100%. So we
|
// short (stopped at the barrier; a gap in glare). So we pull FRESH frames back-to-back
|
||||||
// pull a FRESH frame every #pollMs and re-run ANPR until one clears the floor, or the
|
// (#pollMs is only a floor) and re-run ANPR for as long as the camera keeps pushing —
|
||||||
// #pollWindowMs window elapses (car drove off / non-subscriber). NB: a fresh pull each
|
// the sliding deadline — or until the hard cap. Every confident plate is SETTLED once
|
||||||
// tick — NOT captureSnapshotShared, whose TTL would re-serve the same bad frame.
|
// per loop (emitted, skipped, or declined); the loop goes on afterwards so a second car
|
||||||
// While polling, watch whether THIS subscriber transacts by another credential
|
// behind the first is read by the same loop. NB: a fresh pull each tick — NOT
|
||||||
// (card/QR at the reader). If their open-occurrence count drops mid-poll, the
|
// captureSnapshotShared, whose TTL would re-serve the same bad frame.
|
||||||
// subscriber already exited/entered — the bridge must NOT also emit (it would act on
|
//
|
||||||
// the NEXT open occurrence: a phantom double-exit, worst for a fleet sub). We learn the
|
// Credential race: a subscriber may scan their card/QR at the reader while we are still
|
||||||
// subscription as soon as a frame reads the bound plate (identity needs no confidence),
|
// reading them. We learn a subscription as soon as a frame reads its plate (identity
|
||||||
// snapshot the count, then keep polling for a CONFIDENT read; abort if the count moved.
|
// needs no confidence) and remember their open-occurrence count; if it has moved by the
|
||||||
let result: Awaited<ReturnType<VisionClient["analyze"]>> = null;
|
// time the plate reads confidently, they already transacted and we do NOT emit (it would
|
||||||
let watchedSubId: string | null = null;
|
// act on the NEXT open occurrence: a phantom double-exit, worst for a fleet sub).
|
||||||
let baselineOpen = 0;
|
|
||||||
// Hard ceiling for THIS loop (start + max); the sliding deadline (bumped by joining
|
|
||||||
// pushes) is read from #pollDeadline each tick but never allowed past this cap.
|
|
||||||
const hardCap = Date.now() + this.#pollMaxMs;
|
const hardCap = Date.now() + this.#pollMaxMs;
|
||||||
let attempts = 0;
|
let attempts = 0;
|
||||||
|
/** Plates settled in THIS loop — a framed car reads confidently on every frame. */
|
||||||
|
const handled = new Set<string>();
|
||||||
|
/** Below-floor plate texts already logged at info (repeats go to debug). */
|
||||||
|
const weakLogged = new Set<string>();
|
||||||
|
/** Subscriptions sighted this loop → open-occurrence count at first sighting. */
|
||||||
|
const sighted = new Map<string, number>();
|
||||||
|
let emitted = 0;
|
||||||
|
// The best-framed vehicle PER CONFIDENT PLATE (highest body-type confidence with a
|
||||||
|
// box), plus one "" bucket for frames with no confident plate: PASS samples, one per
|
||||||
|
// car the loop could tell apart, whatever happens to the plate.
|
||||||
|
const best = new Map<string, { shot: Snapshot; r: VisionResult }>();
|
||||||
try {
|
try {
|
||||||
// DO-while: a detection always analyzes AT LEAST ONE frame, however loaded the
|
// DO-while: a detection always analyzes AT LEAST ONE frame, however loaded the
|
||||||
// host — a plain while could zero-iterate if the window elapsed between setting
|
// host — a plain while could zero-iterate if the window elapsed between setting
|
||||||
// the deadline and reaching the loop (seen as a CI flake with the tests' 5ms
|
// the deadline and reaching the loop (seen as a CI flake with the tests' 5ms
|
||||||
// window; on a busy booth it would silently drop a real car's detection). Exit
|
// window; on a busy booth it would silently drop a real car's detection).
|
||||||
// is via the breaks below (confident read, or next tick would pass the deadline).
|
|
||||||
do {
|
do {
|
||||||
attempts++;
|
attempts++;
|
||||||
|
const tick = Date.now();
|
||||||
const shot = await camera.captureSnapshot({ direction });
|
const shot = await camera.captureSnapshot({ direction });
|
||||||
const r = await this.#vision.analyze(shot.bytes, shot.contentType);
|
const r = await this.#vision.analyze(shot.bytes, shot.contentType);
|
||||||
|
const plate = r?.plate?.text.trim().toUpperCase() ?? "";
|
||||||
|
const confident = plate !== "" && r!.plate!.confidence >= this.#entryMinConfidence;
|
||||||
|
|
||||||
// Identify the subscriber from ANY readable plate (even below the barrier floor),
|
if (r?.vehicle?.bbox) {
|
||||||
|
const key = confident ? plate : "";
|
||||||
|
const cur = best.get(key);
|
||||||
|
if (!cur || r.vehicle.confidence > cur.r.vehicle!.confidence) best.set(key, { shot, r });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identify the subscriber from ANY readable plate (even below the barrier floor)
|
||||||
// and baseline their open count once — so we can detect a credential beating us.
|
// and baseline their open count once — so we can detect a credential beating us.
|
||||||
if (r?.plate?.text) {
|
if (plate) {
|
||||||
const m0 = this.#subscription.match({ ...baseRead(row, deviceId), value: r.plate.text.trim().toUpperCase() });
|
const m0 = this.#subscription.match({ ...baseRead(row, deviceId), value: plate });
|
||||||
if (m0 && watchedSubId == null) {
|
if (m0 && !sighted.has(m0.subscriptionId)) {
|
||||||
watchedSubId = m0.subscriptionId;
|
sighted.set(m0.subscriptionId, this.#subscription.openOccurrenceCount(m0.subscriptionId));
|
||||||
baselineOpen = this.#subscription.openOccurrenceCount(watchedSubId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A credential (card/QR) closed/opened an occurrence for this subscriber mid-poll →
|
|
||||||
// they already transacted; stop polling and do NOT emit.
|
if (confident && !handled.has(plate)) {
|
||||||
if (watchedSubId && this.#subscription.openOccurrenceCount(watchedSubId) !== baselineOpen) {
|
handled.add(plate);
|
||||||
this.#logger.info(
|
if (this.#settle(row, deviceId, plate, r!.plate!.confidence, sighted)) emitted++;
|
||||||
`anpr-bridge: subscriber ${watchedSubId} transacted by another credential mid-poll — aborting ANPR`,
|
} else if (plate && !confident && !handled.has(plate)) {
|
||||||
);
|
const line =
|
||||||
return;
|
`anpr-bridge: '${plate}' (${r!.plate!.confidence.toFixed(3)}) below floor ` +
|
||||||
|
`${this.#entryMinConfidence} — re-pulling (attempt ${attempts})`;
|
||||||
|
if (weakLogged.has(plate)) this.#logger.debug(line);
|
||||||
|
else {
|
||||||
|
weakLogged.add(plate);
|
||||||
|
this.#logger.info(line);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (r?.plate && r.plate.confidence >= this.#entryMinConfidence) {
|
// Stop once the (possibly slid) deadline or the cap has passed; else pace to #pollMs.
|
||||||
result = r;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (r?.plate) {
|
|
||||||
this.#logger.info(
|
|
||||||
`anpr-bridge: '${r.plate.text}' (${r.plate.confidence.toFixed(3)}) below floor ` +
|
|
||||||
`${this.#entryMinConfidence} — re-pulling (attempt ${attempts})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Stop if the next tick would land past the (possibly slid) deadline or the cap.
|
|
||||||
const effDeadline = Math.min(this.#pollDeadline.get(deviceId) ?? 0, hardCap);
|
const effDeadline = Math.min(this.#pollDeadline.get(deviceId) ?? 0, hardCap);
|
||||||
if (Date.now() + this.#pollMs >= effDeadline) break;
|
const left = effDeadline - Date.now();
|
||||||
await sleep(this.#pollMs);
|
if (left <= 0) break;
|
||||||
|
const wait = this.#pollMs - (Date.now() - tick);
|
||||||
|
if (wait > 0) await sleep(Math.min(wait, left));
|
||||||
} while (true);
|
} while (true);
|
||||||
} finally {
|
} finally {
|
||||||
this.#polling.delete(deviceId);
|
this.#polling.delete(deviceId);
|
||||||
this.#pollDeadline.delete(deviceId);
|
this.#pollDeadline.delete(deviceId);
|
||||||
|
// One pass sample per plated car. The plateless bucket only when NO car got a plate
|
||||||
|
// (otherwise it is mostly the plated cars' approach frames — not another car).
|
||||||
|
for (const [key, b] of best) {
|
||||||
|
if (key !== "" || best.size === 1) void this.#recordPass(deviceId, direction, b);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!result || !result.plate) {
|
if (handled.size === 0) {
|
||||||
this.#logger.info(
|
this.#logger.info(
|
||||||
`anpr-bridge: no confident plate from ${deviceId} after ${attempts} attempt(s) ` +
|
`anpr-bridge: no confident plate from ${deviceId} after ${attempts} frame(s) ` +
|
||||||
`in ${this.#pollWindowMs}ms — gave up`,
|
`in ${Date.now() - now}ms — gave up`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.#logger.info(
|
||||||
|
`anpr-bridge: ${deviceId} loop done — ${attempts} frame(s) in ${Date.now() - now}ms, ` +
|
||||||
|
`${handled.size} plate(s), ${emitted} emitted`,
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const plate = result.plate.text.trim().toUpperCase();
|
|
||||||
if (!plate) return;
|
|
||||||
|
|
||||||
const e: DeviceReadEvent = {
|
|
||||||
driverId: row.driverId,
|
|
||||||
deviceId,
|
|
||||||
value: plate,
|
|
||||||
kind: "plate",
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
// MATCH BEFORE EMIT — subscriber-only. A non-subscriber plate records advisory
|
|
||||||
// telemetry and stops; it must NEVER reach the transient plate-as-ticket exit flow.
|
|
||||||
const match = this.#subscription.match(e);
|
|
||||||
if (!match) {
|
|
||||||
this.#recordSkip(deviceId, plate, result.plate.confidence);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Final guard against the credential-mid-poll race: if the subscriber transacted between
|
|
||||||
// our baseline and now (e.g. a card scan in the last tick), don't double-act.
|
|
||||||
if (watchedSubId === match.subscriptionId && this.#subscription.openOccurrenceCount(match.subscriptionId) !== baselineOpen) {
|
|
||||||
this.#logger.info(`anpr-bridge: ${match.subscriptionId} already transacted — skipping ANPR emit`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Plate-level debounce — belt-and-suspenders against a gap that slips the
|
|
||||||
// camera-level gate re-emitting the SAME plate.
|
|
||||||
const plateKey = `${deviceId}:${plate}`;
|
|
||||||
if (this.#debounced(plateKey)) return;
|
|
||||||
this.#stamp(plateKey);
|
|
||||||
// Camera-level debounce stamp — now that we've emitted, suppress the camera's ~1Hz
|
|
||||||
// re-fires (and any new poll loop) for #debounceMs.
|
|
||||||
this.#stamp(deviceId);
|
|
||||||
|
|
||||||
this.#logger.info(
|
|
||||||
`anpr-bridge: subscriber plate '${plate}' (${result.plate.confidence.toFixed(3)}) → read bus`,
|
|
||||||
);
|
|
||||||
deviceEvents.emitRead(e); // → onRead → ReadDispatcher → gated SubscriptionFlow
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Fail-soft: an ANPR failure degrades to the subscriber's card/QR, never strands the lane.
|
// Fail-soft: an ANPR failure degrades to the subscriber's card/QR, never strands the lane.
|
||||||
this.#logger.warn(`anpr-bridge failed (${deviceId}): ${(err as Error).message}`);
|
this.#logger.warn(`anpr-bridge failed (${deviceId}): ${(err as Error).message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settle ONE confident plate: match it to a subscriber (MATCH BEFORE EMIT — a non-subscriber
|
||||||
|
* plate records advisory telemetry and stops; it must NEVER reach the transient
|
||||||
|
* plate-as-ticket exit flow), decline if that subscriber already transacted by another
|
||||||
|
* credential during this loop, debounce per plate, then emit. Returns true if emitted.
|
||||||
|
*/
|
||||||
|
#settle(
|
||||||
|
row: { driverId: string },
|
||||||
|
deviceId: string,
|
||||||
|
plate: string,
|
||||||
|
confidence: number,
|
||||||
|
sighted: ReadonlyMap<string, number>,
|
||||||
|
): boolean {
|
||||||
|
const e: DeviceReadEvent = { ...baseRead(row, deviceId), value: plate };
|
||||||
|
const match = this.#subscription.match(e);
|
||||||
|
if (!match) {
|
||||||
|
this.#recordSkip(deviceId, plate, confidence);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const base = sighted.get(match.subscriptionId);
|
||||||
|
if (base != null && this.#subscription.openOccurrenceCount(match.subscriptionId) !== base) {
|
||||||
|
this.#logger.info(
|
||||||
|
`anpr-bridge: subscriber ${match.subscriptionId} transacted by another credential mid-poll — not emitting '${plate}'`,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Per-PLATE debounce across loops: the same car re-starting in the zone within the window
|
||||||
|
// is still the same presentation. Never per camera — the next car must not be blind.
|
||||||
|
const plateKey = `${deviceId}:${plate}`;
|
||||||
|
if (this.#debounced(plateKey)) {
|
||||||
|
this.#logger.debug(`anpr-bridge: '${plate}' read again within ${this.#debounceMs}ms — debounced`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
this.#stamp(plateKey);
|
||||||
|
this.#logger.info(`anpr-bridge: subscriber plate '${plate}' (${confidence.toFixed(3)}) → read bus`);
|
||||||
|
deviceEvents.emitRead(e); // → onRead → ReadDispatcher → gated SubscriptionFlow
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
#debounced(key: string): boolean {
|
#debounced(key: string): boolean {
|
||||||
const last = this.#lastFire.get(key);
|
const last = this.#lastFire.get(key);
|
||||||
return last != null && Date.now() - last < this.#debounceMs;
|
return last != null && Date.now() - last < this.#debounceMs;
|
||||||
}
|
}
|
||||||
|
|
||||||
#stamp(key: string): void {
|
#stamp(key: string): void {
|
||||||
this.#lastFire.set(key, Date.now());
|
const now = Date.now();
|
||||||
|
this.#lastFire.set(key, now);
|
||||||
|
// One key per plate ever seen would grow forever on a busy lane; drop expired stamps.
|
||||||
|
if (this.#lastFire.size > 256) {
|
||||||
|
for (const [k, t] of this.#lastFire) if (now - t >= this.#debounceMs) this.#lastFire.delete(k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** EVERY car the camera flagged becomes one stored frame + one vehicle read on the bus —
|
||||||
|
* plate or no plate, ticket or no ticket. The read is what the Car Wash module samples
|
||||||
|
* for the reviewer (wiki/concepts/vision-review-outbox.md §entry stream); until this,
|
||||||
|
* only session-tied reads were sampled, so a lot with its barriers up (nobody takes a
|
||||||
|
* ticket) sent nothing however many cars the camera saw. One sample per car the loop
|
||||||
|
* could tell apart (per confident plate; one for a plateless loop), from its best-framed
|
||||||
|
* frame. Fire-and-forget: never on the ANPR path, a failure is a log line. Identity
|
||||||
|
* `pass:<snapshotId>` — no session to tie it to. */
|
||||||
|
async #recordPass(deviceId: string, direction: FlowDirection, best: { shot: Snapshot; r: VisionResult }): Promise<void> {
|
||||||
|
try {
|
||||||
|
const vehicle = best.r.vehicle;
|
||||||
|
if (!vehicle) return;
|
||||||
|
const { vehicleBox, plateBox } = await normalizedBoxes(best.shot.bytes, best.r);
|
||||||
|
if (!vehicleBox) return;
|
||||||
|
const stored = await encodeForStorage(best.shot, this.#logger);
|
||||||
|
const id = randomUUID();
|
||||||
|
const identity = `pass:${id}`;
|
||||||
|
this.#db
|
||||||
|
.insert(snapshots)
|
||||||
|
.values({ id, direction, deviceId, identity, contentType: stored.contentType, bytes: stored.bytes, capturedAt: best.shot.capturedAt })
|
||||||
|
.run();
|
||||||
|
// plateBox whenever the detector saw a plate, confident or not: it is what the
|
||||||
|
// review crop blurs — privacy, not identity.
|
||||||
|
deviceEvents.emitVehicleRead({
|
||||||
|
identity,
|
||||||
|
direction,
|
||||||
|
deviceId,
|
||||||
|
read: { bodyType: vehicle.bodyType, confidence: vehicle.confidence, snapshotId: id, box: vehicleBox, plateBox },
|
||||||
|
});
|
||||||
|
this.#logger.debug(`anpr-bridge: pass sample ${id} '${vehicle.bodyType}' (${vehicle.confidence.toFixed(3)}) from ${deviceId}`);
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.warn(`anpr-bridge: pass sample failed for ${deviceId}: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Advisory telemetry: a plate was read at the lane but matched no subscription. Not a
|
/** Advisory telemetry: a plate was read at the lane but matched no subscription. Not a
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { CameraActivity } from "./camera-activity.js";
|
||||||
|
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
|
||||||
|
|
||||||
|
// Per-camera activity drives the booth tiles' snapshot→live switch: one "active" edge
|
||||||
|
// per run of pushes, re-armed by each push, one "idle" edge TTL after the last push.
|
||||||
|
|
||||||
|
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() } as unknown as FastifyBaseLogger;
|
||||||
|
let seen: CameraActivityEvent[];
|
||||||
|
let off: () => void;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
seen = [];
|
||||||
|
off = deviceEvents.onCameraActivity((e) => seen.push(e));
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
off();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("CameraActivity", () => {
|
||||||
|
it("emits active once, re-arms on each push, idles after the TTL", () => {
|
||||||
|
const a = new CameraActivity(logger, 30_000);
|
||||||
|
a.vehicleDetected("cam1");
|
||||||
|
vi.advanceTimersByTime(20_000);
|
||||||
|
a.vehicleDetected("cam1"); // re-arm
|
||||||
|
expect(seen).toEqual([{ deviceId: "cam1", active: true }]);
|
||||||
|
expect(a.snapshot()).toEqual(["cam1"]);
|
||||||
|
vi.advanceTimersByTime(29_000);
|
||||||
|
expect(seen).toHaveLength(1);
|
||||||
|
vi.advanceTimersByTime(1_000);
|
||||||
|
expect(seen).toEqual([
|
||||||
|
{ deviceId: "cam1", active: true },
|
||||||
|
{ deviceId: "cam1", active: false },
|
||||||
|
]);
|
||||||
|
expect(a.snapshot()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tracks cameras independently", () => {
|
||||||
|
const a = new CameraActivity(logger, 1_000);
|
||||||
|
a.vehicleDetected("entry");
|
||||||
|
vi.advanceTimersByTime(600);
|
||||||
|
a.vehicleDetected("exit");
|
||||||
|
vi.advanceTimersByTime(400);
|
||||||
|
expect(a.snapshot()).toEqual(["exit"]);
|
||||||
|
a.stop();
|
||||||
|
vi.advanceTimersByTime(5_000);
|
||||||
|
expect(seen.filter((e) => !e.active)).toEqual([{ deviceId: "entry", active: false }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
|
||||||
|
import { busyTtlMs } from "./lane-status.js";
|
||||||
|
|
||||||
|
// Per-CAMERA "a vehicle is in view" state, for the booth camera tiles: a tile shows the
|
||||||
|
// camera's latest snapshot and switches to live video while its camera is active. Same
|
||||||
|
// signal and TTL as LaneStatus (vehicle `active` pushes, no leave event, 30 s after the
|
||||||
|
// last push) but keyed by camera, not lane: on a shared lane (park-lab: an entry and an
|
||||||
|
// exit camera on one physical lane) only the camera that saw the car goes live.
|
||||||
|
// ADVISORY ONLY — it gates nothing. See wiki/decisions/camera-live-view.md.
|
||||||
|
|
||||||
|
export type { CameraActivityEvent };
|
||||||
|
|
||||||
|
export class CameraActivity {
|
||||||
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
readonly #ttlMs: number;
|
||||||
|
readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||||
|
|
||||||
|
constructor(logger: FastifyBaseLogger, ttlMs = busyTtlMs()) {
|
||||||
|
this.#logger = logger;
|
||||||
|
this.#ttlMs = ttlMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Camera ids currently active (for the WS hello). */
|
||||||
|
snapshot(): string[] {
|
||||||
|
return [...this.#timers.keys()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A vehicle push from `deviceId`: mark it active and (re)arm its clear. */
|
||||||
|
vehicleDetected(deviceId: string): void {
|
||||||
|
const existing = this.#timers.get(deviceId);
|
||||||
|
if (existing) clearTimeout(existing);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this.#timers.delete(deviceId);
|
||||||
|
this.#logger.debug(`camera-activity: ${deviceId} -> idle`);
|
||||||
|
deviceEvents.emitCameraActivity({ deviceId, active: false });
|
||||||
|
}, this.#ttlMs);
|
||||||
|
timer.unref?.();
|
||||||
|
this.#timers.set(deviceId, timer);
|
||||||
|
if (!existing) {
|
||||||
|
this.#logger.debug(`camera-activity: ${deviceId} -> active`);
|
||||||
|
deviceEvents.emitCameraActivity({ deviceId, active: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
for (const t of this.#timers.values()) clearTimeout(t);
|
||||||
|
this.#timers.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices";
|
||||||
|
import { CameraLiveHub, type LiveStatus, type LiveViewer } from "./camera-live.js";
|
||||||
|
|
||||||
|
// The hub's contract: one upstream per camera however many viewers, latest-frame-only
|
||||||
|
// delivery (a busy viewer misses frames, never queues them), teardown after the last
|
||||||
|
// viewer leaves (with a linger), reconnect with backoff while viewers remain, and a
|
||||||
|
// non-retryable failure (codec) reported as "unavailable".
|
||||||
|
|
||||||
|
const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as unknown as FastifyBaseLogger;
|
||||||
|
|
||||||
|
class FakeSource implements LiveVideoSource {
|
||||||
|
frameCbs: Array<(f: Buffer) => void> = [];
|
||||||
|
endCbs: Array<(e?: Error) => void> = [];
|
||||||
|
stopped = false;
|
||||||
|
constructor(private readonly fail?: Error) {}
|
||||||
|
async start() {
|
||||||
|
if (this.fail) {
|
||||||
|
queueMicrotask(() => this.end(this.fail));
|
||||||
|
throw this.fail;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stop() {
|
||||||
|
this.stopped = true;
|
||||||
|
this.end();
|
||||||
|
}
|
||||||
|
onFrame(cb: (f: Buffer) => void) {
|
||||||
|
this.frameCbs.push(cb);
|
||||||
|
}
|
||||||
|
onEnd(cb: (e?: Error) => void) {
|
||||||
|
this.endCbs.push(cb);
|
||||||
|
}
|
||||||
|
frame(b = Buffer.from([0xff, 0xd8])) {
|
||||||
|
for (const cb of this.frameCbs) cb(b);
|
||||||
|
}
|
||||||
|
end(err?: Error) {
|
||||||
|
for (const cb of this.endCbs.splice(0)) cb(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function viewer(busy = false) {
|
||||||
|
const frames: Buffer[] = [];
|
||||||
|
const statuses: LiveStatus[] = [];
|
||||||
|
const v: LiveViewer & { frames: Buffer[]; statuses: LiveStatus[]; isBusy: boolean } = {
|
||||||
|
frames,
|
||||||
|
statuses,
|
||||||
|
isBusy: busy,
|
||||||
|
sendFrame: (f) => frames.push(f),
|
||||||
|
sendStatus: (s) => statuses.push(s),
|
||||||
|
busy: () => v.isBusy,
|
||||||
|
};
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sources: FakeSource[];
|
||||||
|
let nextFail: Error | undefined;
|
||||||
|
const device: LiveStreamDevice = {
|
||||||
|
openLiveStream: () => {
|
||||||
|
const s = new FakeSource(nextFail);
|
||||||
|
sources.push(s);
|
||||||
|
return s;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
sources = [];
|
||||||
|
nextFail = undefined;
|
||||||
|
});
|
||||||
|
afterEach(() => vi.useRealTimers());
|
||||||
|
|
||||||
|
describe("CameraLiveHub", () => {
|
||||||
|
it("shares one upstream between viewers and tears it down after the last leaves", async () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000, maxFps: 1000 });
|
||||||
|
const a = viewer();
|
||||||
|
const b = viewer();
|
||||||
|
const offA = hub.subscribe("cam1", a);
|
||||||
|
const offB = hub.subscribe("cam1", b);
|
||||||
|
expect(sources).toHaveLength(1);
|
||||||
|
sources[0]!.frame();
|
||||||
|
expect(a.frames).toHaveLength(1);
|
||||||
|
expect(b.frames).toHaveLength(1);
|
||||||
|
expect(a.statuses.at(-1)).toEqual({ state: "live" });
|
||||||
|
|
||||||
|
offA();
|
||||||
|
offB();
|
||||||
|
expect(sources[0]!.stopped).toBe(false); // lingering
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(sources[0]!.stopped).toBe(true);
|
||||||
|
expect(hub.upstreamCount).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a viewer returning within the linger reuses the session", () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000 });
|
||||||
|
const off = hub.subscribe("cam1", viewer());
|
||||||
|
off();
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
hub.subscribe("cam1", viewer());
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
expect(sources).toHaveLength(1);
|
||||||
|
expect(sources[0]!.stopped).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips frames for a busy viewer and caps the frame rate", () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger, { maxFps: 10 });
|
||||||
|
const slow = viewer(true);
|
||||||
|
const fast = viewer();
|
||||||
|
hub.subscribe("cam1", slow);
|
||||||
|
hub.subscribe("cam1", fast);
|
||||||
|
for (let i = 0; i < 5; i++) sources[0]!.frame(); // same instant: only the first passes the cap
|
||||||
|
expect(fast.frames).toHaveLength(1);
|
||||||
|
expect(slow.frames).toHaveLength(0);
|
||||||
|
vi.advanceTimersByTime(100);
|
||||||
|
slow.isBusy = false;
|
||||||
|
sources[0]!.frame();
|
||||||
|
expect(fast.frames).toHaveLength(2);
|
||||||
|
expect(slow.frames).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends every frame when no cap is set (the default)", () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger);
|
||||||
|
const v = viewer();
|
||||||
|
hub.subscribe("cam1", v);
|
||||||
|
for (let i = 0; i < 5; i++) sources[0]!.frame(); // same instant: all pass
|
||||||
|
expect(v.frames).toHaveLength(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reconnects with backoff while viewers remain", async () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger);
|
||||||
|
const v = viewer();
|
||||||
|
hub.subscribe("cam1", v);
|
||||||
|
sources[0]!.end(new Error("RTSP connection closed"));
|
||||||
|
expect(v.statuses.at(-1)).toEqual({ state: "retrying", reason: "RTSP connection closed" });
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(sources).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a non-retryable failure as unavailable", async () => {
|
||||||
|
const hub = new CameraLiveHub(() => device, logger, { unavailableRetryMs: 60_000 });
|
||||||
|
nextFail = Object.assign(new Error("camera stream is H264, not MJPEG"), { retryable: false });
|
||||||
|
const v = viewer();
|
||||||
|
hub.subscribe("cam1", v);
|
||||||
|
await vi.advanceTimersByTimeAsync(0);
|
||||||
|
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "camera stream is H264, not MJPEG" });
|
||||||
|
vi.advanceTimersByTime(59_000);
|
||||||
|
expect(sources).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a camera without live support is unavailable and opens nothing", () => {
|
||||||
|
const hub = new CameraLiveHub(() => "live view not supported by this camera driver", logger);
|
||||||
|
const v = viewer();
|
||||||
|
hub.subscribe("cam1", v);
|
||||||
|
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "live view not supported by this camera driver" });
|
||||||
|
expect(hub.upstreamCount).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices";
|
||||||
|
|
||||||
|
// Live camera video for the booth's camera tiles. ONE upstream session per camera,
|
||||||
|
// shared by every viewer (booth tab, desktop shell) and torn down a few seconds after
|
||||||
|
// the last viewer leaves — never one camera session per tab (a camera has few stream
|
||||||
|
// slots, and the ANPR loop pulls stills from the same unit).
|
||||||
|
//
|
||||||
|
// Frames are complete JPEGs (the driver reassembles RTP/JPEG; nothing is decoded here).
|
||||||
|
// Delivery is LATEST-FRAME-ONLY: a viewer whose socket still holds unsent bytes simply
|
||||||
|
// misses frames, so a slow client can never grow server memory. No frame-rate cap by
|
||||||
|
// default — viewers get the camera's own rate (measured: a cap only dropped frames and
|
||||||
|
// added ~40 ms); CAMERA_LIVE_MAX_FPS sets one if a client ever needs it. Advisory viewing only: nothing here touches
|
||||||
|
// the ledger, a gate or a barrier. See wiki/decisions/camera-live-view.md.
|
||||||
|
|
||||||
|
export type LiveStatus =
|
||||||
|
| { state: "connecting" }
|
||||||
|
| { state: "live" }
|
||||||
|
| { state: "retrying"; reason: string }
|
||||||
|
| { state: "unavailable"; reason: string };
|
||||||
|
|
||||||
|
export interface LiveViewer {
|
||||||
|
sendFrame(jpeg: Buffer): void;
|
||||||
|
sendStatus(status: LiveStatus): void;
|
||||||
|
/** True while this viewer's transport still has unsent bytes: skip the frame. */
|
||||||
|
busy(): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve a camera id to its live-stream capability, or a reason it has none. */
|
||||||
|
export type LiveResolver = (deviceId: string) => LiveStreamDevice | string;
|
||||||
|
|
||||||
|
export interface CameraLiveOptions {
|
||||||
|
/** Keep the upstream this long after the last viewer leaves (re-render churn). */
|
||||||
|
lingerMs?: number;
|
||||||
|
/** Per-viewer frame cap; 0 / unset = none (the camera's own rate, 12.5–20 fps). */
|
||||||
|
maxFps?: number;
|
||||||
|
/** Backoff ceiling for reconnects while viewers are present. */
|
||||||
|
maxRetryMs?: number;
|
||||||
|
/** Retry delay after a non-retryable failure (codec/driver), in case it is fixed. */
|
||||||
|
unavailableRetryMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Upstream {
|
||||||
|
readonly deviceId: string;
|
||||||
|
readonly viewers: Map<LiveViewer, { lastSent: number }>;
|
||||||
|
source: LiveVideoSource | null;
|
||||||
|
status: LiveStatus;
|
||||||
|
attempt: number;
|
||||||
|
linger: ReturnType<typeof setTimeout> | null;
|
||||||
|
retry: ReturnType<typeof setTimeout> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Optional per-viewer cap from CAMERA_LIVE_MAX_FPS; 0 (the default) means no cap. */
|
||||||
|
export function liveMaxFps(): number {
|
||||||
|
const raw = Number(process.env.CAMERA_LIVE_MAX_FPS ?? 0);
|
||||||
|
return Number.isFinite(raw) && raw > 0 ? raw : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CameraLiveHub {
|
||||||
|
readonly #resolve: LiveResolver;
|
||||||
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
readonly #lingerMs: number;
|
||||||
|
readonly #minFrameGapMs: number;
|
||||||
|
readonly #maxRetryMs: number;
|
||||||
|
readonly #unavailableRetryMs: number;
|
||||||
|
readonly #upstreams = new Map<string, Upstream>();
|
||||||
|
|
||||||
|
constructor(resolve: LiveResolver, logger: FastifyBaseLogger, opts: CameraLiveOptions = {}) {
|
||||||
|
this.#resolve = resolve;
|
||||||
|
this.#logger = logger;
|
||||||
|
this.#lingerMs = opts.lingerMs ?? 5000;
|
||||||
|
const fps = opts.maxFps ?? liveMaxFps();
|
||||||
|
this.#minFrameGapMs = fps > 0 ? 1000 / fps : 0;
|
||||||
|
this.#maxRetryMs = opts.maxRetryMs ?? 30_000;
|
||||||
|
this.#unavailableRetryMs = opts.unavailableRetryMs ?? 60_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number of open upstream sessions (diagnostic / tests). */
|
||||||
|
get upstreamCount(): number {
|
||||||
|
return [...this.#upstreams.values()].filter((u) => u.source !== null).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribe(deviceId: string, viewer: LiveViewer): () => void {
|
||||||
|
let up = this.#upstreams.get(deviceId);
|
||||||
|
if (!up) {
|
||||||
|
up = { deviceId, viewers: new Map(), source: null, status: { state: "connecting" }, attempt: 0, linger: null, retry: null };
|
||||||
|
this.#upstreams.set(deviceId, up);
|
||||||
|
}
|
||||||
|
if (up.linger) {
|
||||||
|
clearTimeout(up.linger);
|
||||||
|
up.linger = null;
|
||||||
|
}
|
||||||
|
if (!up.source && !up.retry) {
|
||||||
|
up.status = { state: "connecting" };
|
||||||
|
this.#start(up); // may settle the status at once (e.g. "unavailable")
|
||||||
|
}
|
||||||
|
// Added after the start so the newcomer gets the CURRENT status exactly once.
|
||||||
|
up.viewers.set(viewer, { lastSent: 0 });
|
||||||
|
viewer.sendStatus(up.status);
|
||||||
|
|
||||||
|
const u = up;
|
||||||
|
let done = false;
|
||||||
|
return () => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
u.viewers.delete(viewer);
|
||||||
|
if (u.viewers.size === 0 && !u.linger) {
|
||||||
|
u.linger = setTimeout(() => this.#teardown(u), this.#lingerMs);
|
||||||
|
u.linger.unref?.();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
stopAll(): void {
|
||||||
|
for (const up of [...this.#upstreams.values()]) this.#teardown(up);
|
||||||
|
}
|
||||||
|
|
||||||
|
#start(up: Upstream): void {
|
||||||
|
const dev = this.#resolve(up.deviceId);
|
||||||
|
if (typeof dev === "string") {
|
||||||
|
this.#setStatus(up, { state: "unavailable", reason: dev });
|
||||||
|
return; // not a live-capable camera: nothing to retry
|
||||||
|
}
|
||||||
|
let source: LiveVideoSource;
|
||||||
|
try {
|
||||||
|
source = dev.openLiveStream();
|
||||||
|
} catch (err) {
|
||||||
|
// A driver that cannot even build a session (bad config): report it; the next
|
||||||
|
// subscribe tries again.
|
||||||
|
this.#setStatus(up, { state: "unavailable", reason: (err as Error).message });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
up.source = source;
|
||||||
|
let gotFrame = false;
|
||||||
|
source.onFrame((jpeg) => {
|
||||||
|
if (up.source !== source) return;
|
||||||
|
if (!gotFrame) {
|
||||||
|
gotFrame = true;
|
||||||
|
up.attempt = 0;
|
||||||
|
this.#setStatus(up, { state: "live" });
|
||||||
|
}
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [viewer, st] of up.viewers) {
|
||||||
|
if (now - st.lastSent < this.#minFrameGapMs || viewer.busy()) continue;
|
||||||
|
st.lastSent = now;
|
||||||
|
try {
|
||||||
|
viewer.sendFrame(jpeg);
|
||||||
|
} catch {
|
||||||
|
/* a broken viewer is removed by its own close handler */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
source.onEnd((err) => this.#onEnded(up, source, err));
|
||||||
|
source.start().catch(() => undefined); // failures arrive through onEnd
|
||||||
|
}
|
||||||
|
|
||||||
|
#onEnded(up: Upstream, source: LiveVideoSource | null, err?: Error): void {
|
||||||
|
if (source && up.source !== source) return; // a stale session
|
||||||
|
up.source = null;
|
||||||
|
if (up.viewers.size === 0 || !this.#upstreams.has(up.deviceId)) return;
|
||||||
|
const reason = err?.message ?? "stream ended";
|
||||||
|
const retryable = (err as { retryable?: boolean } | undefined)?.retryable !== false;
|
||||||
|
let delay: number;
|
||||||
|
if (retryable) {
|
||||||
|
delay = Math.min(this.#maxRetryMs, 1000 * 2 ** up.attempt);
|
||||||
|
up.attempt++;
|
||||||
|
this.#setStatus(up, { state: "retrying", reason });
|
||||||
|
} else {
|
||||||
|
delay = this.#unavailableRetryMs;
|
||||||
|
this.#setStatus(up, { state: "unavailable", reason });
|
||||||
|
}
|
||||||
|
// Once, not per retry: a camera that is down for hours must not flood the log.
|
||||||
|
if (up.attempt <= 1) this.#logger.warn(`camera-live ${up.deviceId}: ${reason}`);
|
||||||
|
up.retry = setTimeout(() => {
|
||||||
|
up.retry = null;
|
||||||
|
if (up.viewers.size > 0 && !up.source) this.#start(up);
|
||||||
|
}, delay);
|
||||||
|
up.retry.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
#setStatus(up: Upstream, status: LiveStatus): void {
|
||||||
|
up.status = status;
|
||||||
|
for (const viewer of up.viewers.keys()) {
|
||||||
|
try {
|
||||||
|
viewer.sendStatus(status);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#teardown(up: Upstream): void {
|
||||||
|
if (up.linger) clearTimeout(up.linger);
|
||||||
|
if (up.retry) clearTimeout(up.retry);
|
||||||
|
up.linger = null;
|
||||||
|
up.retry = null;
|
||||||
|
const source = up.source;
|
||||||
|
up.source = null;
|
||||||
|
this.#upstreams.delete(up.deviceId);
|
||||||
|
source?.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -89,6 +89,13 @@ export interface DeviceStatusEvent {
|
|||||||
* gate (it never blocks a ticket or opens a barrier). "busy" is set by a vehicle
|
* gate (it never blocks a ticket or opens a barrier). "busy" is set by a vehicle
|
||||||
* `active` event; it auto-clears to "free" after a timeout (this camera class sends
|
* `active` event; it auto-clears to "free" after a timeout (this camera class sends
|
||||||
* no leave/`inactive` signal — see wiki/entities/lpr-camera.md). */
|
* no leave/`inactive` signal — see wiki/entities/lpr-camera.md). */
|
||||||
|
/** A camera started/stopped seeing a vehicle (per camera, TTL-cleared). Drives the
|
||||||
|
* booth camera tiles' snapshot→live switch. Advisory only. See camera-activity.ts. */
|
||||||
|
export interface CameraActivityEvent {
|
||||||
|
readonly deviceId: string;
|
||||||
|
readonly active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface LaneStatusEvent {
|
export interface LaneStatusEvent {
|
||||||
readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity)
|
readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity)
|
||||||
readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity)
|
readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity)
|
||||||
@@ -114,6 +121,9 @@ export interface PlateRecognizedEvent {
|
|||||||
export interface VehicleReadEvent {
|
export interface VehicleReadEvent {
|
||||||
readonly identity: string;
|
readonly identity: string;
|
||||||
readonly direction: "entry" | "exit";
|
readonly direction: "entry" | "exit";
|
||||||
|
/** The camera that took the frame, so a listener can tell "same car, two reads seconds
|
||||||
|
* apart" (the bridge's pass sample + the ticket entry's read) from two cars. */
|
||||||
|
readonly deviceId?: string;
|
||||||
readonly read: VehicleRead;
|
readonly read: VehicleRead;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +200,15 @@ class DeviceEventBus extends EventEmitter {
|
|||||||
return () => this.off("lane-status", cb);
|
return () => this.off("lane-status", cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Emitted when a camera's vehicle activity flips (camera-activity.ts). Advisory. */
|
||||||
|
emitCameraActivity(event: CameraActivityEvent): void {
|
||||||
|
this.emit("camera-activity", event);
|
||||||
|
}
|
||||||
|
onCameraActivity(cb: (event: CameraActivityEvent) => void): () => void {
|
||||||
|
this.on("camera-activity", cb);
|
||||||
|
return () => this.off("camera-activity", cb);
|
||||||
|
}
|
||||||
|
|
||||||
/** Emitted whenever a lane's RADAR presence CHANGES (a presence input shorted/cleared
|
/** Emitted whenever a lane's RADAR presence CHANGES (a presence input shorted/cleared
|
||||||
* at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */
|
* at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */
|
||||||
emitLanePresence(event: LanePresenceEvent): void {
|
emitLanePresence(event: LanePresenceEvent): void {
|
||||||
|
|||||||
@@ -27,8 +27,10 @@ const POLL_MS = Number(process.env.DEVICE_POLL_MS ?? 8000);
|
|||||||
// Camera clock sync (Hikvision loses its clock on power cuts — reboots at the 1970
|
// Camera clock sync (Hikvision loses its clock on power cuts — reboots at the 1970
|
||||||
// epoch until a human logs into its web UI). The monitor re-syncs from the HOST
|
// epoch until a human logs into its web UI). The monitor re-syncs from the HOST
|
||||||
// clock (the site's offline time authority) at the offline→ready edge — exactly the
|
// clock (the site's offline time authority) at the offline→ready edge — exactly the
|
||||||
// power-restored moment — plus a daily backstop; drift under the threshold is left
|
// power-restored moment — plus a daily backstop, plus the moment the site's UTC offset
|
||||||
// alone. See wiki/entities/lpr-camera.md (clock sync).
|
// changes (a DST switch: the camera's zone is a FIXED offset the host rewrites, see
|
||||||
|
// HikvisionCamera.syncClock); drift under the threshold is left alone. See
|
||||||
|
// wiki/entities/lpr-camera.md (clock sync).
|
||||||
const CLOCK_SYNC_BACKSTOP_MS = 24 * 60 * 60 * 1000;
|
const CLOCK_SYNC_BACKSTOP_MS = 24 * 60 * 60 * 1000;
|
||||||
const CLOCK_MAX_DRIFT_SEC = 60;
|
const CLOCK_MAX_DRIFT_SEC = 60;
|
||||||
|
|
||||||
@@ -201,18 +203,26 @@ export class DeviceMonitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Camera clock re-sync at the power-restored edge (prev offline/unknown →
|
// Camera clock re-sync at the power-restored edge (prev offline/unknown →
|
||||||
// ready) + a daily backstop. Stamped BEFORE the async attempt so a failing
|
// ready) + a daily backstop + the site's UTC-offset edge (DST switch). Stamped
|
||||||
// camera is retried at backstop cadence, never every poll.
|
// BEFORE the async attempt so a failing camera is retried at backstop cadence,
|
||||||
|
// never every poll.
|
||||||
if (row.category === "camera" && next.state === "ready" && device && isClockSyncable(device)) {
|
if (row.category === "camera" && next.state === "ready" && device && isClockSyncable(device)) {
|
||||||
const prev = this.#latest.get(row.id);
|
const prev = this.#latest.get(row.id);
|
||||||
const cameBack = !prev || prev.state === "offline";
|
const cameBack = !prev || prev.state === "offline";
|
||||||
const last = this.#clockSyncedAt.get(row.id) ?? 0;
|
const last = this.#clockSyncedAt.get(row.id) ?? 0;
|
||||||
if (cameBack || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
|
const nowIso = localIsoWithOffset(siteTz(this.#db));
|
||||||
|
const offset = nowIso.slice(-6);
|
||||||
|
const offsetChanged = this.#clockSyncedOffset.get(row.id) !== offset;
|
||||||
|
if (cameBack || offsetChanged || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
|
||||||
this.#clockSyncedAt.set(row.id, Date.now());
|
this.#clockSyncedAt.set(row.id, Date.now());
|
||||||
|
this.#clockSyncedOffset.set(row.id, offset);
|
||||||
const cam = device;
|
const cam = device;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const r = await cam.syncClock(localIsoWithOffset(siteTz(this.#db)), CLOCK_MAX_DRIFT_SEC);
|
const r = await cam.syncClock(nowIso, CLOCK_MAX_DRIFT_SEC);
|
||||||
|
if (r.zoneChanged) {
|
||||||
|
this.#log.warn(`device-monitor: camera ${row.id} time zone set to ${r.timeZone ?? "?"} (site offset ${offset})`);
|
||||||
|
}
|
||||||
if (r.synced) {
|
if (r.synced) {
|
||||||
// A large jump is the 1970 power-cut signature — warn (persisted) so
|
// A large jump is the 1970 power-cut signature — warn (persisted) so
|
||||||
// the reboot stays visible; a small correction is routine info.
|
// the reboot stays visible; a small correction is routine info.
|
||||||
@@ -249,6 +259,8 @@ export class DeviceMonitor {
|
|||||||
|
|
||||||
/** Per-camera timestamp of the last clock-sync ATTEMPT (backstop pacing). */
|
/** Per-camera timestamp of the last clock-sync ATTEMPT (backstop pacing). */
|
||||||
readonly #clockSyncedAt = new Map<string, number>();
|
readonly #clockSyncedAt = new Map<string, number>();
|
||||||
|
/** Per-camera site UTC offset ("+02:00") at the last attempt — a change (DST) re-syncs. */
|
||||||
|
readonly #clockSyncedOffset = new Map<string, string>();
|
||||||
|
|
||||||
/** Cache + emit a status, but only when it CHANGED (state or detail). */
|
/** Cache + emit a status, but only when it CHANGED (state or detail). */
|
||||||
#publish(id: string, next: DeviceStatusEvent): void {
|
#publish(id: string, next: DeviceStatusEvent): void {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from "@parking/devices";
|
} from "@parking/devices";
|
||||||
import { DEFAULT_VEHICLE_CATEGORY, reasonPayload } from "@parking/shared";
|
import { DEFAULT_VEHICLE_CATEGORY, reasonPayload } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { pulseBarrier } from "./relay-pulse.js";
|
||||||
import type { DeviceInputEvent, LaneStatusEvent } from "./device-events.js";
|
import type { DeviceInputEvent, LaneStatusEvent } from "./device-events.js";
|
||||||
import { getOccupancy } from "./occupancy.js";
|
import { getOccupancy } from "./occupancy.js";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
@@ -386,7 +387,12 @@ export class EntryFlow {
|
|||||||
const access = this.#buildAccess(resolved.controller);
|
const access = this.#buildAccess(resolved.controller);
|
||||||
let opened = false;
|
let opened = false;
|
||||||
if (access) {
|
if (access) {
|
||||||
await access.pulseOpen(resolved.relay);
|
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||||
|
direction: "entry",
|
||||||
|
identity: ticketId,
|
||||||
|
source: opts.source,
|
||||||
|
...(opts.operator ? { operator: opts.operator } : {}),
|
||||||
|
});
|
||||||
opened = true;
|
opened = true;
|
||||||
} else this.#logger.warn(`entry signed for ${ticketId} but the entry relay won't build`);
|
} else this.#logger.warn(`entry signed for ${ticketId} but the entry relay won't build`);
|
||||||
|
|
||||||
|
|||||||
@@ -111,6 +111,44 @@ describe("exitForBooth — valid exit signs the vehicle_exit", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("forgiven exit (wiki/decisions/forgiven-exit.md)", () => {
|
||||||
|
function payments(identity: string) {
|
||||||
|
return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all().filter((r) => r.type === "payment");
|
||||||
|
}
|
||||||
|
|
||||||
|
it("ticketed car: $0 payment carrying the forgone fee, then the exit is signed with the forgiven reason", async () => {
|
||||||
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 });
|
||||||
|
await enter("T1", minutesAgo(90)); // 2 increments → 20000 owed
|
||||||
|
const f = await pay.forgive("T1", { operator: "owner", note: "regular customer, printer jammed" });
|
||||||
|
expect(f).toMatchObject({ ok: true, forgoneMinor: 20000 });
|
||||||
|
const p = payments("T1");
|
||||||
|
expect(p).toHaveLength(1);
|
||||||
|
expect(p[0]!.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" });
|
||||||
|
expect((p[0]!.payload as { reason: string }).reason).toContain("regular customer, printer jammed");
|
||||||
|
|
||||||
|
// Even with a 0-minute walk-back grace, the forgiven re-open goes through.
|
||||||
|
const r = await exit.reopenBarrier("T1", "owner", { forgiven: { note: "regular customer, printer jammed", forgoneMinor: 20000, currency: "ALL" } });
|
||||||
|
expect(r.ok).toBe(true);
|
||||||
|
expect(exitsSigned("T1")).toHaveLength(1);
|
||||||
|
expect(exitsSigned("T1")[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven" });
|
||||||
|
expect(anomalies("manual exit by owner")).toHaveLength(1);
|
||||||
|
expect(anomalies("manual exit by owner")[0]!.payload).toMatchObject({ forgiven: true, forgoneMinor: 20000, operator: "owner" });
|
||||||
|
// The plain unpaid re-open path is still refused for the NEXT unpaid car.
|
||||||
|
await enter("T2", minutesAgo(90));
|
||||||
|
expect((await exit.reopenBarrier("T2", "owner")).ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no session: a signed anomaly under a fresh forgiven:<id> ref, no exit, no payment", async () => {
|
||||||
|
const r = await exit.forgiveExitNoSession("owner", "came in while the barriers were up");
|
||||||
|
expect(r.ok).toBe(true);
|
||||||
|
const a = anomalies("no ticket / no session");
|
||||||
|
expect(a).toHaveLength(1);
|
||||||
|
expect(a[0]!.identity).toMatch(/^forgiven:/);
|
||||||
|
expect(a[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", forgiven: true, operator: "owner" });
|
||||||
|
expect(db.select().from(ledgerEvents).all().filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("reopenBarrier — no unpaid re-open", () => {
|
describe("reopenBarrier — no unpaid re-open", () => {
|
||||||
it("refuses to re-open an unpaid transient session", async () => {
|
it("refuses to re-open an unpaid transient session", async () => {
|
||||||
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
||||||
|
|||||||
+112
-25
@@ -1,5 +1,7 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db";
|
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db";
|
||||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||||
|
import { pulseBarrier } from "./relay-pulse.js";
|
||||||
import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js";
|
import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js";
|
||||||
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||||
import { snapshotAsync } from "./snapshot.js";
|
import { snapshotAsync } from "./snapshot.js";
|
||||||
@@ -63,6 +65,14 @@ export type BoothReopenResult =
|
|||||||
| { ok: false; reason: string }
|
| { ok: false; reason: string }
|
||||||
| { ok: true; opened: boolean; reason?: string };
|
| { ok: true; opened: boolean; reason?: string };
|
||||||
|
|
||||||
|
/** A forgiven exit's audit facts (wiki/decisions/forgiven-exit.md): the operator's
|
||||||
|
* mandatory free-text note and the fee the $0 payment just waived. */
|
||||||
|
export interface ForgivenExit {
|
||||||
|
readonly note: string;
|
||||||
|
readonly forgoneMinor: number;
|
||||||
|
readonly currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** Minimum ANPR confidence for a plate to participate in swap reconciliation, both for the
|
/** Minimum ANPR confidence for a plate to participate in swap reconciliation, both for the
|
||||||
* exiting read and the matched open session's entry read. Below this, the read is advisory-
|
* exiting read and the matched open session's entry read. Below this, the read is advisory-
|
||||||
* only and never triggers a swap warning (a fuzzy read must not block a legit car). */
|
* only and never triggers a swap warning (a fuzzy read must not block a legit car). */
|
||||||
@@ -201,7 +211,12 @@ export class ExitFlow {
|
|||||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await access.pulseOpen(resolved.relay);
|
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||||
|
direction: "exit",
|
||||||
|
identity: id,
|
||||||
|
source: "booth",
|
||||||
|
...(opts?.operator ? { operator: opts.operator } : {}),
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.#openFailedAnomaly(id, `pulseOpen failed: ${(err as Error).message}`);
|
await this.#openFailedAnomaly(id, `pulseOpen failed: ${(err as Error).message}`);
|
||||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||||
@@ -234,9 +249,10 @@ export class ExitFlow {
|
|||||||
* second exit (that would double-count occupancy): anomaly only, as before.
|
* second exit (that would double-count occupancy): anomaly only, as before.
|
||||||
* See wiki/concepts/booth-exit-flow.md.
|
* See wiki/concepts/booth-exit-flow.md.
|
||||||
*/
|
*/
|
||||||
async reopenBarrier(identity: string, operator?: string): Promise<BoothReopenResult> {
|
async reopenBarrier(identity: string, operator?: string, opts?: { forgiven?: ForgivenExit }): Promise<BoothReopenResult> {
|
||||||
const id = identity.trim();
|
const id = identity.trim();
|
||||||
if (!id) return { ok: false, reason: "ticket id required" };
|
if (!id) return { ok: false, reason: "ticket id required" };
|
||||||
|
const forgiven = opts?.forgiven ?? null;
|
||||||
|
|
||||||
const view = this.#sessionFor(id);
|
const view = this.#sessionFor(id);
|
||||||
if (!view) return { ok: false, reason: "no session for ticket" };
|
if (!view) return { ok: false, reason: "no session for ticket" };
|
||||||
@@ -251,7 +267,10 @@ export class ExitFlow {
|
|||||||
const paid = view.paidAt != null;
|
const paid = view.paidAt != null;
|
||||||
const withinGrace =
|
const withinGrace =
|
||||||
paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
||||||
if (!view.subscription && (!paid || !withinGrace)) {
|
// FORGIVEN exit (barrier:create): the $0 payment carrying the forgone fee was just
|
||||||
|
// signed by PayStation.forgive(); the walk-back check is moot (and a 0-minute grace
|
||||||
|
// tariff must not refuse it). The audit lives on the anomaly + exit below.
|
||||||
|
if (!forgiven && !view.subscription && (!paid || !withinGrace)) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
reason: paid ? "walk-back grace expired — take a top-up payment first" : "session not paid — no barrier open without payment",
|
reason: paid ? "walk-back grace expired — take a top-up payment first" : "session not paid — no barrier open without payment",
|
||||||
@@ -269,9 +288,10 @@ export class ExitFlow {
|
|||||||
type: "anomaly",
|
type: "anomaly",
|
||||||
identity: id,
|
identity: id,
|
||||||
payload: {
|
payload: {
|
||||||
...reasonPayload("exit.manualOpen"),
|
...(forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : reasonPayload("exit.manualOpen")),
|
||||||
source: "booth",
|
source: "booth",
|
||||||
barrierReopen: true,
|
barrierReopen: true,
|
||||||
|
...(forgiven ? { forgiven: true, forgoneMinor: forgiven.forgoneMinor, currency: forgiven.currency } : {}),
|
||||||
...(operator ? { operator } : {}),
|
...(operator ? { operator } : {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -280,34 +300,92 @@ export class ExitFlow {
|
|||||||
// session leaves the active list + occupancy settles. Skip when already exited
|
// session leaves the active list + occupancy settles. Skip when already exited
|
||||||
// (no double-count). Recorded as a human-intervention exit for the audit trail.
|
// (no double-count). Recorded as a human-intervention exit for the audit trail.
|
||||||
if (view.open) {
|
if (view.open) {
|
||||||
await this.#signExit(id, "manual");
|
await this.#signExit(id, "manual", forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : undefined);
|
||||||
this.#closeSessionCache(id);
|
this.#closeSessionCache(id);
|
||||||
this.#fireExitSnapshot(id);
|
this.#fireExitSnapshot(id);
|
||||||
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
|
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!resolved) {
|
const r = await this.#pulseExit(resolved, id, operator, `barrier re-open for ${id}`);
|
||||||
this.#logger.warn(`barrier re-open for ${id}: no exit relay configured`);
|
if (r.opened) {
|
||||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
|
if (forgiven) this.#logger.warn(`FORGIVEN exit barrier open for ${id} by ${operator ?? "?"}: ${forgiven.note}`);
|
||||||
|
else this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
|
||||||
}
|
}
|
||||||
const access = this.#buildAccess(resolved.controller);
|
return r;
|
||||||
if (!access) {
|
|
||||||
this.#logger.warn(`barrier re-open for ${id}: exit controller would not build`);
|
|
||||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await access.pulseOpen(resolved.relay);
|
|
||||||
} catch (err) {
|
|
||||||
this.#logger.error(`barrier re-open pulseOpen failed (${id}): ${(err as Error).message}`);
|
|
||||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
|
||||||
}
|
|
||||||
this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
|
|
||||||
return { ok: true, opened: true };
|
|
||||||
} finally {
|
} finally {
|
||||||
this.#inFlight.delete(key);
|
this.#inFlight.delete(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FORGIVEN exit for a car with NO ticket / no session (it came in while the barriers
|
||||||
|
* were up, lost everything, …). Nothing to forgive and nothing to close: a signed,
|
||||||
|
* attributed anomaly with the exit snapshot as evidence, then the pulse. The anomaly's
|
||||||
|
* identity is a fresh `forgiven:<id>` ref so the live feed can show its snapshot.
|
||||||
|
* See wiki/decisions/forgiven-exit.md.
|
||||||
|
*/
|
||||||
|
async forgiveExitNoSession(operator: string, note: string): Promise<BoothReopenResult> {
|
||||||
|
const key = "forgive:nosession";
|
||||||
|
if (this.#inFlight.has(key)) return { ok: false, reason: "a forgiven open is already in progress" };
|
||||||
|
this.#inFlight.add(key);
|
||||||
|
try {
|
||||||
|
const ref = `forgiven:${randomUUID()}`;
|
||||||
|
const resolved = firstRelayByDirection(this.#db, "exit");
|
||||||
|
await this.#log.append({
|
||||||
|
type: "anomaly",
|
||||||
|
identity: ref,
|
||||||
|
payload: {
|
||||||
|
...reasonPayload("exit.forgiven.noSession", { operator, note: note || "(no reason given)" }),
|
||||||
|
source: "booth",
|
||||||
|
barrierReopen: true,
|
||||||
|
forgiven: true,
|
||||||
|
operator,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.#fireExitSnapshot(ref);
|
||||||
|
const r = await this.#pulseExit(resolved, ref, operator, `forgiven open (no session) ${ref}`);
|
||||||
|
if (r.opened) this.#logger.warn(`FORGIVEN exit barrier open with no session by ${operator}: ${note}`);
|
||||||
|
return r;
|
||||||
|
} finally {
|
||||||
|
this.#inFlight.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drive the exit relay for a human-intervention open; the exit/anomaly is already
|
||||||
|
* signed, so every failure is `ok: true, opened: false` + the reason to open by hand. */
|
||||||
|
async #pulseExit(
|
||||||
|
resolved: ResolvedRelay | null,
|
||||||
|
identity: string,
|
||||||
|
operator: string | undefined,
|
||||||
|
label: string,
|
||||||
|
): Promise<Extract<BoothReopenResult, { ok: true }>> {
|
||||||
|
if (!resolved) {
|
||||||
|
this.#logger.warn(`${label}: no exit relay configured`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
|
||||||
|
}
|
||||||
|
const access = this.#buildAccess(resolved.controller);
|
||||||
|
if (!access) {
|
||||||
|
this.#logger.warn(`${label}: exit controller would not build`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||||
|
direction: "exit",
|
||||||
|
identity,
|
||||||
|
source: "booth",
|
||||||
|
...(operator ? { operator } : {}),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`${label}: pulseOpen failed: ${(err as Error).message}`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||||
|
}
|
||||||
|
return { ok: true, opened: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
#forgivenParams(operator: string | undefined, f: ForgivenExit): Record<string, string | number> {
|
||||||
|
return { operator: operator ?? "?", forgone: (f.forgoneMinor / 100).toFixed(2), currency: f.currency, note: f.note || "(no reason given)" };
|
||||||
|
}
|
||||||
|
|
||||||
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
|
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
|
||||||
* read dispatcher from the reader's binding, which has ruled out a subscription match). */
|
* read dispatcher from the reader's binding, which has ruled out a subscription match). */
|
||||||
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||||
@@ -411,8 +489,13 @@ export class ExitFlow {
|
|||||||
await this.#signExit(e.value, e.kind === "plate" ? "lpr" : "ticket");
|
await this.#signExit(e.value, e.kind === "plate" ? "lpr" : "ticket");
|
||||||
|
|
||||||
const access = this.#buildAccess(resolved.controller);
|
const access = this.#buildAccess(resolved.controller);
|
||||||
if (access) await access.pulseOpen(resolved.relay);
|
if (access) {
|
||||||
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||||
|
direction: "exit",
|
||||||
|
identity: e.value,
|
||||||
|
source: e.kind === "plate" ? "lpr" : "ticket",
|
||||||
|
});
|
||||||
|
} else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
||||||
|
|
||||||
this.#fireExitSnapshot(e.value);
|
this.#fireExitSnapshot(e.value);
|
||||||
this.#closeSessionCache(e.value);
|
this.#closeSessionCache(e.value);
|
||||||
@@ -422,7 +505,11 @@ export class ExitFlow {
|
|||||||
/** Append the signed vehicle_exit. `source`: "ticket" (booth/reader), "lpr" (plate),
|
/** Append the signed vehicle_exit. `source`: "ticket" (booth/reader), "lpr" (plate),
|
||||||
* or "manual" (a human-intervention barrier re-open that closes an open session —
|
* or "manual" (a human-intervention barrier re-open that closes an open session —
|
||||||
* see reopenBarrier). */
|
* see reopenBarrier). */
|
||||||
async #signExit(identity: string, source: "ticket" | "lpr" | "manual" = "ticket"): Promise<void> {
|
async #signExit(
|
||||||
|
identity: string,
|
||||||
|
source: "ticket" | "lpr" | "manual" = "ticket",
|
||||||
|
reason?: ReturnType<typeof reasonPayload>,
|
||||||
|
): Promise<void> {
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "vehicle_exit",
|
type: "vehicle_exit",
|
||||||
direction: "exit",
|
direction: "exit",
|
||||||
@@ -430,7 +517,7 @@ export class ExitFlow {
|
|||||||
identity,
|
identity,
|
||||||
payload: {
|
payload: {
|
||||||
sessionRef: identity,
|
sessionRef: identity,
|
||||||
...(source === "manual" ? reasonPayload("exit.manualOpen") : {}),
|
...(reason ?? (source === "manual" ? reasonPayload("exit.manualOpen") : {})),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export const carwashModule: ServerModule = {
|
|||||||
// training material (the gate view, no order attached). The core announces the read;
|
// training material (the gate view, no order attached). The core announces the read;
|
||||||
// the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set.
|
// the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set.
|
||||||
const offVehicleRead = deviceEvents.onVehicleRead((e) => {
|
const offVehicleRead = deviceEvents.onVehicleRead((e) => {
|
||||||
if (e.direction === "entry" && outbox.sampleEntry()) void outbox.enqueueEntry(e.read);
|
if (e.direction === "entry" && outbox.sampleEntry(e.deviceId)) void outbox.enqueueEntry(e.read);
|
||||||
});
|
});
|
||||||
app.addHook("onClose", async () => offVehicleRead());
|
app.addHook("onClose", async () => offVehicleRead());
|
||||||
app.addHook("onClose", async () => outbox.stop());
|
app.addHook("onClose", async () => outbox.stop());
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import type { FastifyInstance } from "fastify";
|
|||||||
import { deviceEvents as deviceEventBus } from "../../device-events.js";
|
import { deviceEvents as deviceEventBus } from "../../device-events.js";
|
||||||
import { buildServer } from "../../server.js";
|
import { buildServer } from "../../server.js";
|
||||||
import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js";
|
import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js";
|
||||||
import { EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
|
import { ENTRY_DEDUP_MS, EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
|
||||||
|
|
||||||
// The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred
|
// The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred
|
||||||
// vehicle crop + the operator's choice, queued off the intake path, drained one-way with
|
// vehicle crop + the operator's choice, queued off the intake path, drained one-way with
|
||||||
@@ -165,6 +165,20 @@ describe("queue + drain", () => {
|
|||||||
const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn);
|
const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn);
|
||||||
expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]);
|
expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]);
|
||||||
expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off
|
expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off
|
||||||
|
// Per-camera dedup: the bridge's pass sample and the ticket entry's read, seconds
|
||||||
|
// apart from the same camera, are ONE car — the second is skipped and not counted.
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const every = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 1 }, fetchFn);
|
||||||
|
expect(every.sampleEntry("cam-a")).toBe(true);
|
||||||
|
expect(every.sampleEntry("cam-a")).toBe(false);
|
||||||
|
expect(every.sampleEntry("cam-b")).toBe(true); // another camera = another car
|
||||||
|
vi.advanceTimersByTime(ENTRY_DEDUP_MS + 1);
|
||||||
|
expect(every.sampleEntry("cam-a")).toBe(true);
|
||||||
|
expect(every.sampleEntry()).toBe(true); // camera unknown → no dedup
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
expect(await sampler.enqueueEntry(read)).toBe(true);
|
expect(await sampler.enqueueEntry(read)).toBe(true);
|
||||||
const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!;
|
const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!;
|
||||||
expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } });
|
expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } });
|
||||||
|
|||||||
@@ -63,6 +63,9 @@ const CROP_MARGIN = 0.08;
|
|||||||
/** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks
|
/** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks
|
||||||
* should not resurface a fortnight of crops in one burst. */
|
* should not resurface a fortnight of crops in one burst. */
|
||||||
export const EXPIRE_DAYS = 14;
|
export const EXPIRE_DAYS = 14;
|
||||||
|
/** Two entry reads from the same camera closer than this are one car (the ANPR bridge's
|
||||||
|
* per-detection pass sample, then the ticket entry's session-tied read ~seconds later). */
|
||||||
|
export const ENTRY_DEDUP_MS = 30_000;
|
||||||
/** Backoff: 1 min · 2^attempts, capped. */
|
/** Backoff: 1 min · 2^attempts, capped. */
|
||||||
const BACKOFF_BASE_MS = 60_000;
|
const BACKOFF_BASE_MS = 60_000;
|
||||||
const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000;
|
const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000;
|
||||||
@@ -166,6 +169,9 @@ export class ReviewOutbox {
|
|||||||
#timer: NodeJS.Timeout | null = null;
|
#timer: NodeJS.Timeout | null = null;
|
||||||
#draining = false;
|
#draining = false;
|
||||||
#entrySeen = 0;
|
#entrySeen = 0;
|
||||||
|
/** Last entry sample per camera: the bridge's pass sample and the ticket entry's read are
|
||||||
|
* the SAME car seconds apart — one goes, the other is skipped (and not counted). */
|
||||||
|
readonly #lastEntryByDevice = new Map<string, number>();
|
||||||
|
|
||||||
constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) {
|
constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
@@ -202,9 +208,15 @@ export class ReviewOutbox {
|
|||||||
|
|
||||||
/** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted
|
/** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted
|
||||||
* in-process, so "1 in 5" is exactly that across a booth's day. */
|
* in-process, so "1 in 5" is exactly that across a booth's day. */
|
||||||
sampleEntry(): boolean {
|
sampleEntry(deviceId?: string): boolean {
|
||||||
const n = this.#cfg?.entrySample ?? 0;
|
const n = this.#cfg?.entrySample ?? 0;
|
||||||
if (n <= 0) return false;
|
if (n <= 0) return false;
|
||||||
|
if (deviceId) {
|
||||||
|
const now = Date.now();
|
||||||
|
const last = this.#lastEntryByDevice.get(deviceId);
|
||||||
|
if (last != null && now - last < ENTRY_DEDUP_MS) return false;
|
||||||
|
this.#lastEntryByDevice.set(deviceId, now);
|
||||||
|
}
|
||||||
this.#entrySeen += 1;
|
this.#entrySeen += 1;
|
||||||
return this.#entrySeen % n === 0;
|
return this.#entrySeen % n === 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,24 @@ async function enter(identity: string, enteredAt: string, payload?: Record<strin
|
|||||||
await log.append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: enteredAt, payload: payload ?? null });
|
await log.append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: enteredAt, payload: payload ?? null });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe("PayStation.forgive (forgiven exit)", () => {
|
||||||
|
it("signs a $0 payment with the quoted fee as forgoneMinor and marks the session paid", async () => {
|
||||||
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
|
||||||
|
await enter("T1", minutesAgo(90));
|
||||||
|
const r = await pay.forgive("T1", { operator: "owner", note: "lost ticket, known customer" });
|
||||||
|
expect(r).toEqual({ ok: true, forgoneMinor: 20000, currency: expect.any(String) });
|
||||||
|
const ev = db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, "T1")).all().find((e) => e.type === "payment")!;
|
||||||
|
expect(ev.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" });
|
||||||
|
expect((ev.payload as { tender?: string }).tender).toBeUndefined(); // nothing was tendered
|
||||||
|
expect(pay.lookup("T1").paidAt).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws like quote() for an unknown ticket", async () => {
|
||||||
|
seedTariff(db);
|
||||||
|
await expect(pay.forgive("nope", { operator: "owner", note: "x" })).rejects.toThrow(NoOpenSessionError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("PayStation.quote", () => {
|
describe("PayStation.quote", () => {
|
||||||
it("throws NoOpenSessionError for an unknown ticket", () => {
|
it("throws NoOpenSessionError for an unknown ticket", () => {
|
||||||
seedTariff(db);
|
seedTariff(db);
|
||||||
@@ -134,4 +152,25 @@ describe("PayStation.activeSessions", () => {
|
|||||||
expect(list.map((s) => s.identity)).toEqual(["NEW", "OLD"]);
|
expect(list.map((s) => s.identity)).toEqual(["NEW", "OLD"]);
|
||||||
expect(list.every((s) => s.open)).toBe(true);
|
expect(list.every((s) => s.open)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The list prices each open transient from ONE whole-ledger scan (no per-row ledger
|
||||||
|
// reads — those froze park-2's server, 2026-10-24). The amounts must match the
|
||||||
|
// single-session quote() exactly, including after a payment (overstay repricing) and
|
||||||
|
// for a subscription (never quoted).
|
||||||
|
it("prices every row identically to quote() without per-session ledger reads", async () => {
|
||||||
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 });
|
||||||
|
await enter("UNPAID", minutesAgo(150));
|
||||||
|
await enter("PAID", minutesAgo(300));
|
||||||
|
await pay.pay("PAID", "cash"); // grace 0 → paid-but-open ⇒ overstay, re-priced from now
|
||||||
|
await enter("SUB", minutesAgo(10), { permit: true, permitId: "sub-1" });
|
||||||
|
|
||||||
|
const list = pay.activeSessions();
|
||||||
|
const by = new Map(list.map((s) => [s.identity, s]));
|
||||||
|
expect(by.get("UNPAID")!.amountMinor).toBe(pay.quote("UNPAID").amountMinor);
|
||||||
|
expect(by.get("UNPAID")!.currency).toBe(pay.quote("UNPAID").currency);
|
||||||
|
expect(by.get("PAID")!.overstay).toBe(true);
|
||||||
|
expect(by.get("PAID")!.amountMinor).toBe(pay.quote("PAID").amountMinor);
|
||||||
|
expect(by.get("SUB")!.subscription).toBe(true);
|
||||||
|
expect(by.get("SUB")!.amountMinor).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+104
-21
@@ -1,10 +1,16 @@
|
|||||||
import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db";
|
import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||||
import { BOOTH_TILL, priceSession, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared";
|
import { BOOTH_TILL, priceSession, reasonPayload, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||||
import { windowOwedBetween } from "./subscription-window.js";
|
import { windowOwedBetween } from "./subscription-window.js";
|
||||||
import { liveValidations } from "./validations.js";
|
import { liveValidationsFromRows } from "./validations.js";
|
||||||
|
|
||||||
|
/** A `ledger_events` row as the pricing fold reads it. */
|
||||||
|
type LedgerRow = typeof ledgerEvents.$inferSelect;
|
||||||
|
/** Resolves the tariff version in force at an instant. Built once per request so a list
|
||||||
|
* view does not re-read the tariff tables for every row. */
|
||||||
|
type TariffResolver = (at: string) => typeof tariffVersions.$inferSelect | null;
|
||||||
|
|
||||||
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
||||||
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
||||||
@@ -200,12 +206,23 @@ export class PayStation {
|
|||||||
* 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period
|
* 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period
|
||||||
* reflects the reality and re-accrues the fee. No side effect. */
|
* reflects the reality and re-accrues the fee. No side effect. */
|
||||||
quote(identity: string): Quote {
|
quote(identity: string): Quote {
|
||||||
const entry = this.#openEntry(identity);
|
return this.#quoteFromRows(identity, this.#identityRows(identity), this.#tariffResolver());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `quote` over the identity's ledger rows the caller already holds (oldest first) and
|
||||||
|
* a prebuilt tariff resolver. The single-session `quote()` wraps this with one
|
||||||
|
* identity-scoped read; `activeSessions()` feeds it per-identity groups of ONE whole-
|
||||||
|
* ledger scan. Both paths MUST price identically — pinned by pay-station.test.ts.
|
||||||
|
* Why: the list view used to call `quote()` per open unpaid row, each doing 3–4
|
||||||
|
* ledger scans; with ~660 such rows at park-2 the synchronous handler ran ~2 s and
|
||||||
|
* froze the event loop — relay replies then "timed out" (2026-10-24). */
|
||||||
|
#quoteFromRows(identity: string, rows: readonly LedgerRow[], tariffFor: TariffResolver): Quote {
|
||||||
|
const entry = PayStation.#openEntryFromRows(rows);
|
||||||
if (!entry) throw new NoOpenSessionError(identity);
|
if (!entry) throw new NoOpenSessionError(identity);
|
||||||
|
|
||||||
// The tariff in force is keyed to ENTRY (the version frozen for this session), even
|
// The tariff in force is keyed to ENTRY (the version frozen for this session), even
|
||||||
// for an overstay period — the customer keeps the rate card they entered under.
|
// for an overstay period — the customer keeps the rate card they entered under.
|
||||||
const tv = this.#tariffVersionFor(entry.occurredAt);
|
const tv = tariffFor(entry.occurredAt);
|
||||||
if (!tv) throw new NoTariffError();
|
if (!tv) throw new NoTariffError();
|
||||||
const structure = tv.structure as unknown as TariffStructure;
|
const structure = tv.structure as unknown as TariffStructure;
|
||||||
|
|
||||||
@@ -220,8 +237,8 @@ export class PayStation {
|
|||||||
// Merchant validations: fold the LIVE ones (applied, unvoided, not consumed by a
|
// Merchant validations: fold the LIVE ones (applied, unvoided, not consumed by a
|
||||||
// prior payment) so the quote is NET — the payment then stamps their ids as
|
// prior payment) so the quote is NET — the payment then stamps their ids as
|
||||||
// consumed. See wiki/concepts/validation-discounts.md.
|
// consumed. See wiki/concepts/validation-discounts.md.
|
||||||
const last = this.#lastPayment(identity);
|
const last = PayStation.#lastPaymentFromRows(rows);
|
||||||
const validations = liveValidations(this.#db, identity);
|
const validations = liveValidationsFromRows(rows);
|
||||||
const p = priceSession(
|
const p = priceSession(
|
||||||
entry.occurredAt,
|
entry.occurredAt,
|
||||||
new Date().toISOString(),
|
new Date().toISOString(),
|
||||||
@@ -254,12 +271,17 @@ export class PayStation {
|
|||||||
/** The latest signed `payment` for this session (time + the grace window it granted),
|
/** The latest signed `payment` for this session (time + the grace window it granted),
|
||||||
* or null if never paid. Folds the append-only ledger. */
|
* or null if never paid. Folds the append-only ledger. */
|
||||||
#lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null {
|
#lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null {
|
||||||
const rows = this.#db
|
return PayStation.#lastPaymentFromRows(this.#identityRows(identity));
|
||||||
.select({ type: ledgerEvents.type, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload })
|
}
|
||||||
.from(ledgerEvents)
|
|
||||||
.where(eq(ledgerEvents.identity, identity))
|
/** All ledger rows of one identity, oldest first (the fold order every helper expects). */
|
||||||
.orderBy(ledgerEvents.index)
|
#identityRows(identity: string): LedgerRow[] {
|
||||||
.all();
|
return this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).orderBy(ledgerEvents.index).all();
|
||||||
|
}
|
||||||
|
|
||||||
|
static #lastPaymentFromRows(
|
||||||
|
rows: readonly Pick<LedgerRow, "type" | "occurredAt" | "payload">[],
|
||||||
|
): { paidAt: string; graceExitMin: number | null } | null {
|
||||||
let last: { paidAt: string; graceExitMin: number | null } | null = null;
|
let last: { paidAt: string; graceExitMin: number | null } | null = null;
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
if (r.type !== "payment") continue;
|
if (r.type !== "payment") continue;
|
||||||
@@ -373,6 +395,53 @@ export class PayStation {
|
|||||||
return { amountMinor, currency: q.currency };
|
return { amountMinor, currency: q.currency };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FORGIVEN EXIT (wiki/decisions/forgiven-exit.md): the owner lets a ticketed car out
|
||||||
|
* with no money. Signs a ZERO-amount payment that carries the fee the car owed as
|
||||||
|
* `forgoneMinor`, so the shift's cash/card/drawer are untouched by construction while
|
||||||
|
* the Z-report shows the forgone amount as its own line; the exit that follows closes
|
||||||
|
* the ticket (no reuse). Refused when the quote carries module charge lines (a wash on
|
||||||
|
* the ticket): parking is forgiven, a wash is not — settle it first. Throws
|
||||||
|
* NoOpenSessionError / NoTariffError like `quote()`.
|
||||||
|
*/
|
||||||
|
async forgive(
|
||||||
|
identity: string,
|
||||||
|
opts: { operator: string; note: string },
|
||||||
|
): Promise<{ ok: true; forgoneMinor: number; currency: string } | { ok: false; reason: string }> {
|
||||||
|
const q = this.quote(identity);
|
||||||
|
if (q.chargesMinor > 0) {
|
||||||
|
return { ok: false, reason: "ticket carries a module charge (e.g. a wash) — settle it first; only parking can be forgiven" };
|
||||||
|
}
|
||||||
|
await this.#log.append({
|
||||||
|
type: "payment",
|
||||||
|
source: "manual",
|
||||||
|
identity,
|
||||||
|
payload: {
|
||||||
|
sessionRef: identity,
|
||||||
|
amountMinor: 0,
|
||||||
|
forgoneMinor: q.amountMinor,
|
||||||
|
currency: q.currency,
|
||||||
|
till: BOOTH_TILL,
|
||||||
|
tariffVersionId: q.tariffVersionId,
|
||||||
|
graceExitMin: q.graceExitMin,
|
||||||
|
operator: opts.operator,
|
||||||
|
...reasonPayload("exit.forgiven", {
|
||||||
|
operator: opts.operator,
|
||||||
|
forgone: (q.amountMinor / 100).toFixed(2),
|
||||||
|
currency: q.currency,
|
||||||
|
note: opts.note || "(no reason given)",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
this.#db.update(sessions).set({ state: "paid" }).where(eq(sessions.id, identity)).run();
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`session-cache mark-paid failed for ${identity}: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
this.#logger.warn(`FORGIVEN exit for ${identity} by ${opts.operator}: ${q.amountMinor} ${q.currency} waived — ${opts.note}`);
|
||||||
|
return { ok: true, forgoneMinor: q.amountMinor, currency: q.currency };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One-read session view for the booth pay/exit modal: entry/exit times, paid
|
* One-read session view for the booth pay/exit modal: entry/exit times, paid
|
||||||
* state, amount owed now, and walk-back-grace status. Read-only — folds the
|
* state, amount owed now, and walk-back-grace status. Read-only — folds the
|
||||||
@@ -494,9 +563,15 @@ export class PayStation {
|
|||||||
subscriptionId?: string | null;
|
subscriptionId?: string | null;
|
||||||
};
|
};
|
||||||
const byId = new Map<string, Acc>();
|
const byId = new Map<string, Acc>();
|
||||||
|
// Every row per identity (oldest first — `rows` is index-ordered), so the quotes
|
||||||
|
// below price from THIS scan instead of re-reading the ledger per session.
|
||||||
|
const rowsById = new Map<string, LedgerRow[]>();
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
const id = r.identity;
|
const id = r.identity;
|
||||||
if (!id) continue;
|
if (!id) continue;
|
||||||
|
const group = rowsById.get(id);
|
||||||
|
if (group) group.push(r);
|
||||||
|
else rowsById.set(id, [r]);
|
||||||
if (r.type === "vehicle_entry") {
|
if (r.type === "vehicle_entry") {
|
||||||
const a = byId.get(id) ?? { source: r.source ?? null };
|
const a = byId.get(id) ?? { source: r.source ?? null };
|
||||||
a.enteredAt = r.occurredAt;
|
a.enteredAt = r.occurredAt;
|
||||||
@@ -523,6 +598,8 @@ export class PayStation {
|
|||||||
// Resolve advisory plates for all candidate identities in ONE device_events scan
|
// Resolve advisory plates for all candidate identities in ONE device_events scan
|
||||||
// (cheaper than one lookup per row).
|
// (cheaper than one lookup per row).
|
||||||
const plates = platesForIdentities(this.#db, byId.keys());
|
const plates = platesForIdentities(this.#db, byId.keys());
|
||||||
|
// One tariff read for the whole list (quotes below reuse it).
|
||||||
|
const tariffFor = this.#tariffResolver();
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const out: ActiveSession[] = [];
|
const out: ActiveSession[] = [];
|
||||||
@@ -560,7 +637,9 @@ export class PayStation {
|
|||||||
let currency: string | null = null;
|
let currency: string | null = null;
|
||||||
if (open && !isSubscription && (a.paidAt == null || overstay)) {
|
if (open && !isSubscription && (a.paidAt == null || overstay)) {
|
||||||
try {
|
try {
|
||||||
const q = this.quote(identity);
|
// Priced from the rows already in hand — no per-session ledger reads. The
|
||||||
|
// charge providers (car wash) still run one indexed lookup per row.
|
||||||
|
const q = this.#quoteFromRows(identity, rowsById.get(identity) ?? [], tariffFor);
|
||||||
amountMinor = q.amountMinor;
|
amountMinor = q.amountMinor;
|
||||||
currency = q.currency;
|
currency = q.currency;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -663,12 +742,10 @@ export class PayStation {
|
|||||||
|
|
||||||
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
||||||
#openEntry(identity: string) {
|
#openEntry(identity: string) {
|
||||||
const rows = this.#db
|
return PayStation.#openEntryFromRows(this.#identityRows(identity));
|
||||||
.select()
|
}
|
||||||
.from(ledgerEvents)
|
|
||||||
.where(eq(ledgerEvents.identity, identity))
|
static #openEntryFromRows(rows: readonly LedgerRow[]): LedgerRow | null {
|
||||||
.orderBy(ledgerEvents.index)
|
|
||||||
.all();
|
|
||||||
const entry = rows.find((r) => r.type === "vehicle_entry");
|
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||||
if (!entry) return null;
|
if (!entry) return null;
|
||||||
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed
|
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed
|
||||||
@@ -678,14 +755,20 @@ export class PayStation {
|
|||||||
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
|
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
|
||||||
* (single, for now) active site tariff. */
|
* (single, for now) active site tariff. */
|
||||||
#tariffVersionFor(at: string) {
|
#tariffVersionFor(at: string) {
|
||||||
|
return this.#tariffResolver()(at);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read the site tariff + its versions ONCE and return a resolver over them. A list
|
||||||
|
* view builds one resolver per request instead of two tariff reads per row. */
|
||||||
|
#tariffResolver(): TariffResolver {
|
||||||
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||||
if (!tariff) return null;
|
if (!tariff) return () => null;
|
||||||
const versions = this.#db
|
const versions = this.#db
|
||||||
.select()
|
.select()
|
||||||
.from(tariffVersions)
|
.from(tariffVersions)
|
||||||
.where(eq(tariffVersions.tariffId, tariff.id))
|
.where(eq(tariffVersions.tariffId, tariff.id))
|
||||||
.orderBy(desc(tariffVersions.effectiveFrom))
|
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||||
.all();
|
.all();
|
||||||
return versions.find((v) => v.effectiveFrom <= at) ?? null;
|
return (at) => versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { devices, deviceEvents as deviceEventsTable, ledgerEvents, subscriptionCredentials, subscriptions, type Db } from "@parking/db";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import { ReadDispatcher, readDebounceMs, DEFAULT_READ_DEBOUNCE_MS } from "./read-dispatch.js";
|
||||||
|
import { ExitFlow } from "./exit-flow.js";
|
||||||
|
import { SubscriptionFlow } from "./subscription-flow.js";
|
||||||
|
import type { DeviceReadEvent } from "./device-events.js";
|
||||||
|
import { makeLog, silentLogger } from "./test-helpers.js";
|
||||||
|
|
||||||
|
// SAME-CODE DEBOUNCE at the dispatcher (2026-10-11): the same value from the same reader
|
||||||
|
// inside the reader's `debounceMs` window is ONE presentation — the first verdict is
|
||||||
|
// replayed, nothing is signed twice, the repeat lands in device_events as telemetry.
|
||||||
|
// Born at park-2: the DT-008 reported one card twice 560 ms apart; the permit flow opened
|
||||||
|
// two sessions and pulsed the barrier twice. Every lane, every credential kind.
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
|
||||||
|
function seed(readerCfg: Record<string, unknown>, direction: "entry" | "exit" = "exit"): ReadDispatcher {
|
||||||
|
({ db } = createTestDb());
|
||||||
|
db.insert(devices).values({
|
||||||
|
id: "ctl",
|
||||||
|
category: "access",
|
||||||
|
driverId: "stub-access",
|
||||||
|
config: { relays: [{ relay: 1, direction }] },
|
||||||
|
enabled: true,
|
||||||
|
}).run();
|
||||||
|
db.insert(devices).values({
|
||||||
|
id: "reader",
|
||||||
|
category: "reader",
|
||||||
|
driverId: "dingtian-qr-reader",
|
||||||
|
config: { serial: "H05MA5B0", controllerId: "ctl", relay: 1, ...readerCfg },
|
||||||
|
enabled: true,
|
||||||
|
}).run();
|
||||||
|
const log = makeLog(db);
|
||||||
|
return new ReadDispatcher(db, new ExitFlow(db, log, silentLogger()), new SubscriptionFlow(db, log, silentLogger()), silentLogger());
|
||||||
|
}
|
||||||
|
|
||||||
|
function read(value: string, opts: { kind?: DeviceReadEvent["kind"]; channel?: DeviceReadEvent["channel"] } = {}): DeviceReadEvent {
|
||||||
|
return {
|
||||||
|
driverId: "dingtian-qr-reader",
|
||||||
|
deviceId: "reader",
|
||||||
|
value,
|
||||||
|
kind: opts.kind ?? "qr",
|
||||||
|
...(opts.channel ? { channel: opts.channel } : {}),
|
||||||
|
at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ledger = () => db.select().from(ledgerEvents).all();
|
||||||
|
const debounced = () =>
|
||||||
|
db.select().from(deviceEventsTable).all()
|
||||||
|
.map((r) => r.detail as { debounced?: boolean; value?: string; sinceMs?: number; replayedAccepted?: boolean })
|
||||||
|
.filter((d) => d.debounced === true);
|
||||||
|
|
||||||
|
describe("readDebounceMs", () => {
|
||||||
|
it("defaults to 5000 when the reader has no value; honours numbers and form strings; 0 = off", () => {
|
||||||
|
expect(readDebounceMs({})).toBe(DEFAULT_READ_DEBOUNCE_MS);
|
||||||
|
expect(readDebounceMs({ debounceMs: "" })).toBe(5000);
|
||||||
|
expect(readDebounceMs({ debounceMs: 2500 })).toBe(2500);
|
||||||
|
expect(readDebounceMs({ debounceMs: "800" })).toBe(800);
|
||||||
|
expect(readDebounceMs({ debounceMs: 0 })).toBe(0);
|
||||||
|
expect(readDebounceMs({ debounceMs: "nope" })).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("read-dispatch same-code debounce", () => {
|
||||||
|
it("a repeat of the same unknown ticket at exit signs ONE refusal, replays the verdict, logs telemetry", async () => {
|
||||||
|
const d = seed({}); // default window
|
||||||
|
const first = await d.dispatch(read("00000000000")); // Luhn-valid, no session → refused + signed
|
||||||
|
const second = await d.dispatch(read("00000000000"));
|
||||||
|
expect(ledger()).toHaveLength(1); // not a second red row for the same scan
|
||||||
|
expect(second).toEqual(first); // same verdict → same beep
|
||||||
|
expect(debounced()).toHaveLength(1);
|
||||||
|
expect(debounced()[0]).toMatchObject({ value: "00000000000", replayedAccepted: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a double-read SUBSCRIBER card at ENTRY opens ONE occurrence and the repeat is accepted (replayed)", async () => {
|
||||||
|
const d = seed({}, "entry");
|
||||||
|
db.insert(subscriptions).values({ id: "s1", status: "active", quantity: 1, period: "month" }).run();
|
||||||
|
db.insert(subscriptionCredentials).values({ id: "c1", subscriptionId: "s1", kind: "rf", value: "3F3AFC" }).run();
|
||||||
|
const first = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" }));
|
||||||
|
const second = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" }));
|
||||||
|
expect(first.accepted).toBe(true);
|
||||||
|
expect(second.accepted).toBe(true); // the card WAS read; beep ok, but no second entry
|
||||||
|
expect(ledger().filter((e) => e.type === "vehicle_entry")).toHaveLength(1);
|
||||||
|
expect(debounced()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a DIFFERENT code inside the window is not debounced", async () => {
|
||||||
|
const d = seed({});
|
||||||
|
await d.dispatch(read("00000000000"));
|
||||||
|
await d.dispatch(read("00000000026")); // another Luhn-valid shape
|
||||||
|
expect(ledger()).toHaveLength(2);
|
||||||
|
expect(debounced()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the window comes from the reader's config and expires", async () => {
|
||||||
|
const d = seed({ debounceMs: 30 });
|
||||||
|
await d.dispatch(read("00000000000"));
|
||||||
|
await new Promise((r) => setTimeout(r, 45));
|
||||||
|
await d.dispatch(read("00000000000")); // outside the 30ms window → a fresh decision
|
||||||
|
expect(ledger()).toHaveLength(2);
|
||||||
|
expect(debounced()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("debounceMs = 0 turns it off", async () => {
|
||||||
|
const d = seed({ debounceMs: 0 });
|
||||||
|
await d.dispatch(read("00000000000"));
|
||||||
|
await d.dispatch(read("00000000000"));
|
||||||
|
expect(ledger()).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a FAILED first decision is not replayed: the repeat decides afresh, no unhandled rejection", async () => {
|
||||||
|
seed({});
|
||||||
|
// Make the exit flow blow up once (e.g. a signer hiccup), then work.
|
||||||
|
const log = makeLog(db);
|
||||||
|
const flaky = new ExitFlow(db, log, silentLogger());
|
||||||
|
let calls = 0;
|
||||||
|
const orig = flaky.handleAt.bind(flaky);
|
||||||
|
flaky.handleAt = async (...args: Parameters<ExitFlow["handleAt"]>) => {
|
||||||
|
calls++;
|
||||||
|
if (calls === 1) throw new Error("signer busy");
|
||||||
|
return orig(...args);
|
||||||
|
};
|
||||||
|
const d2 = new ReadDispatcher(db, flaky, new SubscriptionFlow(db, log, silentLogger()), silentLogger());
|
||||||
|
const rejections: unknown[] = [];
|
||||||
|
const onUnhandled = (r: unknown) => rejections.push(r);
|
||||||
|
process.on("unhandledRejection", onUnhandled);
|
||||||
|
try {
|
||||||
|
await expect(d2.dispatch(read("00000000000"))).rejects.toThrow("signer busy");
|
||||||
|
const second = await d2.dispatch(read("00000000000")); // inside the window, but nothing to replay
|
||||||
|
expect(second.accepted).toBe(false); // a real decision (refused: no session), signed once
|
||||||
|
expect(ledger()).toHaveLength(1);
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
expect(rejections).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
process.off("unhandledRejection", onUnhandled);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a repeat arriving while the first read is still deciding gets the SAME decision", async () => {
|
||||||
|
const d = seed({});
|
||||||
|
const [a, b] = await Promise.all([d.dispatch(read("00000000000")), d.dispatch(read("00000000000"))]);
|
||||||
|
expect(b).toEqual(a);
|
||||||
|
expect(ledger()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,7 +5,7 @@ import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
|||||||
import type { ExitFlow } from "./exit-flow.js";
|
import type { ExitFlow } from "./exit-flow.js";
|
||||||
import { validateTicketCode } from "./entry-flow.js";
|
import { validateTicketCode } from "./entry-flow.js";
|
||||||
import type { SubscriptionFlow } from "./subscription-flow.js";
|
import type { SubscriptionFlow } from "./subscription-flow.js";
|
||||||
import { relayForDevice } from "./device-resolve.js";
|
import { relayForDevice, type ResolvedRelay } from "./device-resolve.js";
|
||||||
|
|
||||||
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
|
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
|
||||||
// can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the
|
// can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the
|
||||||
@@ -35,12 +35,49 @@ import { relayForDevice } from "./device-resolve.js";
|
|||||||
// - ANY read on a CONFIRMED RF channel (a physically present card, enrolled or
|
// - ANY read on a CONFIRMED RF channel (a physically present card, enrolled or
|
||||||
// not, is a real event — RF is never sun noise),
|
// not, is a real event — RF is never sun noise),
|
||||||
// - plates (different population; never shape-filtered here).
|
// - plates (different population; never shape-filtered here).
|
||||||
|
//
|
||||||
|
// SAME-CODE DEBOUNCE (2026-10-11, park-2). The DT-008 reported one card TWICE 560 ms
|
||||||
|
// apart; the permit flow opened two sessions on the same permit and pulsed the barrier
|
||||||
|
// twice. Any reader can double-read (a card held a beat too long, a QR re-decoded while
|
||||||
|
// the hand moves), and at exit a second scan of a ticket inside its grace period would
|
||||||
|
// sign a noSession refusal for a car that just left. So the SAME value from the SAME
|
||||||
|
// reader within the reader's `debounceMs` (Setup → reader; default 5000; 0 = off) is one
|
||||||
|
// presentation: the first verdict is REPLAYED (same beep, no second decision, nothing
|
||||||
|
// signed twice) and the repeat is kept as unsigned telemetry. Every lane, every kind
|
||||||
|
// (card / QR / ticket / plate) — the ANPR bridge debounces plates itself, longer.
|
||||||
|
|
||||||
|
/** Default same-code debounce when a reader's config has none (ms). */
|
||||||
|
export const DEFAULT_READ_DEBOUNCE_MS = 5000;
|
||||||
|
/** Recent-reads map housekeeping: prune above the soft cap, never exceed the hard cap, and
|
||||||
|
* treat any entry older than this as expired whatever the reader's configured window. */
|
||||||
|
const RECENT_READS_SOFT_CAP = 512;
|
||||||
|
const RECENT_READS_HARD_CAP = 4096;
|
||||||
|
const RECENT_READS_MAX_AGE_MS = 60_000;
|
||||||
|
|
||||||
|
interface ReaderConfig {
|
||||||
|
readonly debounceMs?: number | string | null;
|
||||||
|
readonly [k: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The reader's debounce window: its config value (the Setup form may store a string),
|
||||||
|
* else the default; 0 (or a negative/garbage value coerced to 0) disables. */
|
||||||
|
export function readDebounceMs(config: unknown): number {
|
||||||
|
const v = (config as ReaderConfig | null)?.debounceMs;
|
||||||
|
if (v == null || v === "") return DEFAULT_READ_DEBOUNCE_MS;
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
export class ReadDispatcher {
|
export class ReadDispatcher {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #exit: ExitFlow;
|
readonly #exit: ExitFlow;
|
||||||
readonly #subscription: SubscriptionFlow;
|
readonly #subscription: SubscriptionFlow;
|
||||||
readonly #logger: FastifyBaseLogger;
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
/** Recent reads keyed `deviceId:kind:value` → when last seen + the FIRST verdict (a
|
||||||
|
* promise, so a repeat arriving while the first is still deciding gets that same
|
||||||
|
* decision). `at` slides on each repeat: a card held against the reader stays one
|
||||||
|
* presentation for as long as it keeps re-reading. */
|
||||||
|
readonly #recent = new Map<string, { at: number; outcome: Promise<ReadOutcome> }>();
|
||||||
|
|
||||||
constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) {
|
constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
@@ -59,6 +96,50 @@ export class ReadDispatcher {
|
|||||||
return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" };
|
return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Same code, same reader, inside the window → replay the first verdict. Checked
|
||||||
|
// BEFORE matching so a repeat never reaches a flow (no second entry, no second exit,
|
||||||
|
// no refusal anomaly for a car that was just admitted).
|
||||||
|
const debounceMs = readDebounceMs(reader.config);
|
||||||
|
const key = `${e.deviceId}:${e.kind}:${e.value}`;
|
||||||
|
const now = Date.now();
|
||||||
|
const prev = this.#recent.get(key);
|
||||||
|
if (debounceMs > 0 && prev && now - prev.at < debounceMs) {
|
||||||
|
const sinceMs = now - prev.at;
|
||||||
|
prev.at = now;
|
||||||
|
this.#logger.info(
|
||||||
|
`read debounced: '${e.value}' (${e.kind}) again on ${e.deviceId} after ${sinceMs}ms (window ${debounceMs}ms) — first verdict replayed`,
|
||||||
|
);
|
||||||
|
prev.outcome.then(
|
||||||
|
(o) => this.#recordDebounced(e, sinceMs, debounceMs, o),
|
||||||
|
() => undefined, // the first decision failed: the caller gets that rejection, not us
|
||||||
|
);
|
||||||
|
return prev.outcome;
|
||||||
|
}
|
||||||
|
const outcome = this.#decide(resolved, e);
|
||||||
|
if (debounceMs > 0) {
|
||||||
|
this.#recent.set(key, { at: now, outcome });
|
||||||
|
// A failed decision is NOT a verdict to replay — forget it so the next read retries.
|
||||||
|
outcome.catch(() => this.#recent.delete(key));
|
||||||
|
this.#pruneRecent(now);
|
||||||
|
}
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the recent-reads map small: drop expired entries, and if a flood of distinct
|
||||||
|
* values inside one window still leaves it over the cap, drop the oldest. Bounded
|
||||||
|
* memory whatever a misbehaving (or hostile) reader sends. */
|
||||||
|
#pruneRecent(now: number): void {
|
||||||
|
if (this.#recent.size <= RECENT_READS_SOFT_CAP) return;
|
||||||
|
for (const [k, r] of this.#recent) if (now - r.at >= RECENT_READS_MAX_AGE_MS) this.#recent.delete(k);
|
||||||
|
while (this.#recent.size > RECENT_READS_HARD_CAP) {
|
||||||
|
const oldest = this.#recent.keys().next().value; // insertion order = oldest first
|
||||||
|
if (oldest === undefined) break;
|
||||||
|
this.#recent.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The actual routing of a FRESH read (not a debounced repeat). */
|
||||||
|
async #decide(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||||
const sub = this.#subscription.match(e);
|
const sub = this.#subscription.match(e);
|
||||||
if (sub) {
|
if (sub) {
|
||||||
return this.#subscription.run(resolved, e, sub);
|
return this.#subscription.run(resolved, e, sub);
|
||||||
@@ -86,6 +167,34 @@ export class ReadDispatcher {
|
|||||||
return this.#exit.handleAt(resolved, e);
|
return this.#exit.handleAt(resolved, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Unsigned telemetry for a debounced repeat — auditable in device_events (the double
|
||||||
|
* read is still a fact about the hardware), out of the signed feed. */
|
||||||
|
#recordDebounced(e: DeviceReadEvent, sinceMs: number, debounceMs: number, replayed: ReadOutcome): void {
|
||||||
|
try {
|
||||||
|
this.#db
|
||||||
|
.insert(deviceEventsTable)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
deviceId: e.deviceId,
|
||||||
|
category: "reader",
|
||||||
|
kind: "read",
|
||||||
|
detail: {
|
||||||
|
debounced: true,
|
||||||
|
value: e.value,
|
||||||
|
readKind: e.kind,
|
||||||
|
...(e.channel ? { channel: e.channel } : {}),
|
||||||
|
sinceMs,
|
||||||
|
debounceMs,
|
||||||
|
replayedAccepted: replayed.accepted,
|
||||||
|
},
|
||||||
|
occurredAt: e.at,
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`debounced-read telemetry insert failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Unsigned telemetry for a filtered read — auditable in device_events, out of the
|
/** Unsigned telemetry for a filtered read — auditable in device_events, out of the
|
||||||
* signed feed. Mirrors the entry flow's suppressed-press pattern. */
|
* signed feed. Mirrors the entry flow's suppressed-press pattern. */
|
||||||
#recordUnrecognized(e: DeviceReadEvent): void {
|
#recordUnrecognized(e: DeviceReadEvent): void {
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import { devices, deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db";
|
||||||
|
import { pulseBarrier } from "./relay-pulse.js";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
|
||||||
|
const silentLogger = { info() {}, warn() {}, error() {}, debug() {} } as unknown as FastifyBaseLogger;
|
||||||
|
|
||||||
|
// Every barrier pulse — success or failure — must leave an UNSIGNED device_events row
|
||||||
|
// (kind "relay") naming the relay, the direction, the identity and who asked, so a
|
||||||
|
// "did the server open the barrier?" question is answerable from telemetry alone
|
||||||
|
// (park-2, 2026-10-09). A failure is recorded AND re-thrown (each flow keeps its own
|
||||||
|
// anomaly handling).
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
let close: () => void;
|
||||||
|
let controller: DeviceRow;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const t = createTestDb();
|
||||||
|
db = t.db;
|
||||||
|
close = t.close;
|
||||||
|
db.insert(devices)
|
||||||
|
.values({
|
||||||
|
id: "ctl-1",
|
||||||
|
category: "access",
|
||||||
|
driverId: "stub-access",
|
||||||
|
config: { relays: [{ relay: 2, direction: "exit" }] },
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
controller = db.select().from(devices).get()!;
|
||||||
|
});
|
||||||
|
afterEach(() => close());
|
||||||
|
|
||||||
|
function relayRows() {
|
||||||
|
return db
|
||||||
|
.select()
|
||||||
|
.from(deviceEventsTable)
|
||||||
|
.all()
|
||||||
|
.filter((r) => r.kind === "relay")
|
||||||
|
.map((r) => ({ deviceId: r.deviceId, category: r.category, detail: r.detail as Record<string, unknown> }));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("pulseBarrier", () => {
|
||||||
|
it("pulses the relay and records a successful relay event with the context", async () => {
|
||||||
|
const fired: number[] = [];
|
||||||
|
const access = { pulseOpen: async (door: number) => void fired.push(door) };
|
||||||
|
await pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, {
|
||||||
|
direction: "exit",
|
||||||
|
identity: "forgiven:abc",
|
||||||
|
source: "booth",
|
||||||
|
operator: "admin",
|
||||||
|
});
|
||||||
|
expect(fired).toEqual([2]);
|
||||||
|
const rows = relayRows();
|
||||||
|
expect(rows).toHaveLength(1);
|
||||||
|
expect(rows[0].deviceId).toBe("ctl-1");
|
||||||
|
expect(rows[0].category).toBe("access");
|
||||||
|
expect(rows[0].detail).toMatchObject({
|
||||||
|
driverId: "stub-access",
|
||||||
|
relay: 2,
|
||||||
|
direction: "exit",
|
||||||
|
identity: "forgiven:abc",
|
||||||
|
source: "booth",
|
||||||
|
operator: "admin",
|
||||||
|
ok: true,
|
||||||
|
});
|
||||||
|
expect(typeof rows[0].detail.tookMs).toBe("number");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records a failed pulse with the error, then re-throws it", async () => {
|
||||||
|
const access = {
|
||||||
|
pulseOpen: async () => {
|
||||||
|
throw new Error("timeout");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await expect(
|
||||||
|
pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, { direction: "exit", identity: "T1", source: "ticket" }),
|
||||||
|
).rejects.toThrow("timeout");
|
||||||
|
const rows = relayRows();
|
||||||
|
expect(rows).toHaveLength(1);
|
||||||
|
expect(rows[0].detail).toMatchObject({ relay: 2, identity: "T1", source: "ticket", ok: false, error: "timeout" });
|
||||||
|
expect(rows[0].detail.operator).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db";
|
||||||
|
import type { AccessControlDevice } from "@parking/devices";
|
||||||
|
import type { Direction } from "./device-resolve.js";
|
||||||
|
|
||||||
|
// The ONE place a barrier relay is pulsed from business logic. Every pulse is logged at
|
||||||
|
// info (relay, controller, who asked and for which identity) and echoed into the UNSIGNED
|
||||||
|
// device_events stream (kind "relay") whether it succeeded or failed — so "did the server
|
||||||
|
// open the barrier at 15:50?" is answerable from `docker logs` or the telemetry table
|
||||||
|
// without reading the ledger. The signed ledger stays the authority on WHY (the
|
||||||
|
// vehicle_entry/exit/anomaly is appended BEFORE the pulse); this is the device-side echo
|
||||||
|
// (wiki/concepts/device-events.md). Failures are recorded, then re-thrown so each flow keeps
|
||||||
|
// its own anomaly/result handling. park-2 2026-10-09: a "barrier opened by itself" claim
|
||||||
|
// took ledger + snapshots to settle because pulses were only logged when they failed.
|
||||||
|
|
||||||
|
export interface PulseContext {
|
||||||
|
/** The barrier's direction (the relay's configured event). */
|
||||||
|
readonly direction: Direction;
|
||||||
|
/** The session/ticket/card/ref the open is for (matches the signed event's identity). */
|
||||||
|
readonly identity: string;
|
||||||
|
/** Who asked: ticket | manual | booth | lpr | subscription | relay-test … (free-form). */
|
||||||
|
readonly source: string;
|
||||||
|
readonly operator?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pulseBarrier(
|
||||||
|
db: Db,
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
access: Pick<AccessControlDevice, "pulseOpen">,
|
||||||
|
target: { readonly controller: DeviceRow; readonly relay: number },
|
||||||
|
ctx: PulseContext,
|
||||||
|
): Promise<void> {
|
||||||
|
const { controller, relay } = target;
|
||||||
|
const who = ctx.operator ? ` by ${ctx.operator}` : "";
|
||||||
|
logger.info(
|
||||||
|
`relay pulse: ${ctx.direction} relay ${relay} on ${controller.driverId} ${controller.id} ← ${ctx.source} ${ctx.identity}${who}`,
|
||||||
|
);
|
||||||
|
const startedAt = Date.now();
|
||||||
|
const firedAt = new Date(startedAt).toISOString();
|
||||||
|
try {
|
||||||
|
await access.pulseOpen(relay);
|
||||||
|
record(db, logger, controller, relay, ctx, firedAt, { ok: true, tookMs: Date.now() - startedAt });
|
||||||
|
} catch (err) {
|
||||||
|
const error = (err as Error).message;
|
||||||
|
logger.error(`relay pulse FAILED: ${ctx.direction} relay ${relay} on ${controller.id} for ${ctx.identity}: ${error}`);
|
||||||
|
record(db, logger, controller, relay, ctx, firedAt, { ok: false, error, tookMs: Date.now() - startedAt });
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function record(
|
||||||
|
db: Db,
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
controller: DeviceRow,
|
||||||
|
relay: number,
|
||||||
|
ctx: PulseContext,
|
||||||
|
firedAt: string,
|
||||||
|
outcome: { ok: boolean; error?: string; tookMs: number },
|
||||||
|
): void {
|
||||||
|
// Telemetry must never block or fail the open — swallow insert errors (logged).
|
||||||
|
try {
|
||||||
|
db.insert(deviceEventsTable)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
deviceId: controller.id,
|
||||||
|
category: "access",
|
||||||
|
kind: "relay",
|
||||||
|
detail: {
|
||||||
|
driverId: controller.driverId,
|
||||||
|
relay,
|
||||||
|
direction: ctx.direction,
|
||||||
|
identity: ctx.identity,
|
||||||
|
source: ctx.source,
|
||||||
|
...(ctx.operator ? { operator: ctx.operator } : {}),
|
||||||
|
...outcome,
|
||||||
|
},
|
||||||
|
occurredAt: firedAt,
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
} catch (err) {
|
||||||
|
logger.error(`relay pulse telemetry insert failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import { buildServer } from "./server.js";
|
||||||
|
|
||||||
|
// Request logging shape (2026-10-08 noise cut, wiki/concepts/app-logs.md §Noise cut):
|
||||||
|
// - /health logs NOTHING (Docker probes it every 30 s — it was half a quiet booth's log),
|
||||||
|
// - every other request logs ONE line "METHOD url → status Nms" (not pino's two),
|
||||||
|
// - a handler failure still logs the error with its stack, because
|
||||||
|
// `disableRequestLogging` also silences Fastify's default error-handler logging.
|
||||||
|
// The logger's stream is process.stdout (pinoDbStream tees warn+ into app_logs), so
|
||||||
|
// capture stdout writes and look at the JSON lines.
|
||||||
|
|
||||||
|
const lines: Record<string, unknown>[] = [];
|
||||||
|
let restore: (() => void) | null = null;
|
||||||
|
|
||||||
|
function captureStdout() {
|
||||||
|
const spy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
|
||||||
|
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
|
||||||
|
for (const l of text.split("\n")) {
|
||||||
|
if (!l.trim()) continue;
|
||||||
|
try {
|
||||||
|
lines.push(JSON.parse(l));
|
||||||
|
} catch {
|
||||||
|
/* non-JSON stdout noise — ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}) as typeof process.stdout.write);
|
||||||
|
restore = () => spy.mockRestore();
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
restore?.();
|
||||||
|
restore = null;
|
||||||
|
lines.length = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
const msgs = () => lines.map((l) => String(l.msg ?? ""));
|
||||||
|
|
||||||
|
describe("request logging", () => {
|
||||||
|
it("/health is silent; other requests log exactly one line; 5xx keeps the error", async () => {
|
||||||
|
const t = createTestDb();
|
||||||
|
captureStdout();
|
||||||
|
// vitest.config forces LOG_LEVEL=silent for every test; this one needs the real level.
|
||||||
|
const prevLevel = process.env.LOG_LEVEL;
|
||||||
|
process.env.LOG_LEVEL = "info";
|
||||||
|
const app = await buildServer({ db: t.db });
|
||||||
|
process.env.LOG_LEVEL = prevLevel;
|
||||||
|
app.get("/boom", async () => {
|
||||||
|
throw new Error("kaboom");
|
||||||
|
});
|
||||||
|
await app.ready();
|
||||||
|
try {
|
||||||
|
lines.length = 0; // drop startup lines
|
||||||
|
|
||||||
|
expect((await app.inject({ method: "GET", url: "/health" })).statusCode).toBe(200);
|
||||||
|
expect(msgs().filter((m) => m.includes("/health"))).toEqual([]);
|
||||||
|
|
||||||
|
expect((await app.inject({ method: "GET", url: "/api/nope" })).statusCode).toBe(404);
|
||||||
|
const notFound = msgs().filter((m) => m.includes("/api/nope"));
|
||||||
|
expect(notFound).toHaveLength(1);
|
||||||
|
expect(notFound[0]).toMatch(/^GET \/api\/nope → 404 \d+ms$/);
|
||||||
|
expect(msgs().some((m) => /incoming request|request completed/.test(m))).toBe(false);
|
||||||
|
|
||||||
|
expect((await app.inject({ method: "GET", url: "/boom" })).statusCode).toBe(500);
|
||||||
|
const boom = lines.filter((l) => String(l.msg).includes("/boom"));
|
||||||
|
// one error line (with the err object) + the one-line request summary
|
||||||
|
expect(boom.map((l) => [l.level, String(l.msg).replace(/\d+ms/, "Nms")])).toEqual([
|
||||||
|
["error", "GET /boom failed: kaboom"],
|
||||||
|
["info", "GET /boom → 500 Nms"],
|
||||||
|
]);
|
||||||
|
expect((boom[0]!.err as { message?: string })?.message).toBe("kaboom");
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
t.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -37,6 +37,24 @@ interface FontScaleBody {
|
|||||||
fontScale: number;
|
fontScale: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Booth camera tiles the user left open (camera device ids, in opening order). Bounded:
|
||||||
|
// a booth has a handful of cameras; the cap stops a client from storing junk.
|
||||||
|
const OPEN_CAMERAS_MAX = 8;
|
||||||
|
const DEVICE_ID_MAX = 64;
|
||||||
|
interface OpenCamerasBody {
|
||||||
|
openCameras: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** users.open_cameras (JSON text) → string[]; anything malformed reads as none open. */
|
||||||
|
function parseOpenCameras(raw: string | null | undefined): string[] {
|
||||||
|
try {
|
||||||
|
const v: unknown = JSON.parse(raw ?? "[]");
|
||||||
|
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, OPEN_CAMERAS_MAX) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Self-service profile: a signed-in user edits their OWN display name + email. This is
|
// Self-service profile: a signed-in user edits their OWN display name + email. This is
|
||||||
// NOT the admin user-management path (routes/users.ts) — it only ever touches the caller
|
// NOT the admin user-management path (routes/users.ts) — it only ever touches the caller
|
||||||
// (req.user.sub), needs no `user:*` permission, and can't change username, role, or any
|
// (req.user.sub), needs no `user:*` permission, and can't change username, role, or any
|
||||||
@@ -90,6 +108,7 @@ function sessionView(
|
|||||||
language: string;
|
language: string;
|
||||||
theme: string;
|
theme: string;
|
||||||
fontScale: number;
|
fontScale: number;
|
||||||
|
openCameras?: string | null;
|
||||||
fullName?: string | null;
|
fullName?: string | null;
|
||||||
email?: string | null;
|
email?: string | null;
|
||||||
},
|
},
|
||||||
@@ -106,6 +125,7 @@ function sessionView(
|
|||||||
language: user.language,
|
language: user.language,
|
||||||
theme: user.theme,
|
theme: user.theme,
|
||||||
fontScale: user.fontScale,
|
fontScale: user.fontScale,
|
||||||
|
openCameras: parseOpenCameras(user.openCameras),
|
||||||
fullName: user.fullName ?? null,
|
fullName: user.fullName ?? null,
|
||||||
email: user.email ?? null,
|
email: user.email ?? null,
|
||||||
// Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes
|
// Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes
|
||||||
@@ -219,6 +239,33 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Which booth camera tiles I left open (any signed-in user; only touches the caller).
|
||||||
|
// Persisted like `theme`, restored on the next login from any booth. Ids are not
|
||||||
|
// checked against `devices`: a removed camera's tile is simply not rendered.
|
||||||
|
app.put<{ Body: OpenCamerasBody }>(
|
||||||
|
"/api/auth/open-cameras",
|
||||||
|
{ preHandler: requireAuth },
|
||||||
|
async (req, reply) => {
|
||||||
|
const raw = req.body?.openCameras;
|
||||||
|
if (
|
||||||
|
!Array.isArray(raw) ||
|
||||||
|
raw.length > OPEN_CAMERAS_MAX ||
|
||||||
|
!raw.every((x) => typeof x === "string" && x.length > 0 && x.length <= DEVICE_ID_MAX)
|
||||||
|
) {
|
||||||
|
return reply
|
||||||
|
.code(400)
|
||||||
|
.send({ error: `openCameras must be up to ${OPEN_CAMERAS_MAX} device ids` });
|
||||||
|
}
|
||||||
|
const openCameras = [...new Set(raw as string[])];
|
||||||
|
await db
|
||||||
|
.update(users)
|
||||||
|
.set({ openCameras: JSON.stringify(openCameras) })
|
||||||
|
.where(eq(users.id, req.user.sub))
|
||||||
|
.run();
|
||||||
|
return { openCameras };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Edit MY own display name / email (any signed-in user; no permission needed — it only
|
// Edit MY own display name / email (any signed-in user; no permission needed — it only
|
||||||
// touches the caller). Cannot change username or role — those stay admin-only (users.ts).
|
// touches the caller). Cannot change username or role — those stay admin-only (users.ts).
|
||||||
app.put<{ Body: ProfileBody }>(
|
app.put<{ Body: ProfileBody }>(
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { devices, snapshots, type Db } from "@parking/db";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { buildServer } from "../server.js";
|
||||||
|
import { login, seedUser } from "../test-helpers.js";
|
||||||
|
|
||||||
|
// Booth camera tiles: latest-snapshot lookup (session:read), the live socket's auth gate
|
||||||
|
// (same handshake as /api/ws, then device:read), and the per-user open-tiles preference.
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
let close: () => void;
|
||||||
|
let app: FastifyInstance;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const t = createTestDb();
|
||||||
|
db = t.db;
|
||||||
|
close = t.close;
|
||||||
|
app = await buildServer({ db });
|
||||||
|
await app.ready();
|
||||||
|
// A Dahua camera: no live-view capability, so the socket answers without any network.
|
||||||
|
db.insert(devices)
|
||||||
|
.values({ id: "cam-dahua", category: "camera", driverId: "dahua", config: { host: "192.0.2.1" } })
|
||||||
|
.run();
|
||||||
|
db.insert(devices).values({ id: "relay-1", category: "access", driverId: "stub-access", config: {} }).run();
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
close();
|
||||||
|
});
|
||||||
|
|
||||||
|
function shot(id: string, deviceId: string, capturedAt: string) {
|
||||||
|
db.insert(snapshots)
|
||||||
|
.values({ id, direction: "entry", deviceId, identity: "x", contentType: "image/jpeg", bytes: Buffer.from([1]), capturedAt })
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("GET /api/cameras/:id/latest-snapshot", () => {
|
||||||
|
it("returns the camera's newest snapshot", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
shot("s1", "cam-dahua", "2026-11-17T10:00:00.000Z");
|
||||||
|
shot("s2", "cam-dahua", "2026-11-17T11:00:00.000Z");
|
||||||
|
shot("s3", "other", "2026-11-17T12:00:00.000Z");
|
||||||
|
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: auth.cookie } });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(res.json()).toMatchObject({ id: "s2", direction: "entry" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("404s when the camera has none, 403s without session:read", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const admin = await login(app, "admin", "pw");
|
||||||
|
const none = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: admin.cookie } });
|
||||||
|
expect(none.statusCode).toBe(404);
|
||||||
|
|
||||||
|
await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] });
|
||||||
|
const dev = await login(app, "dev", "pw");
|
||||||
|
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: dev.cookie } });
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/cameras/:id/snapshots/:snapshotId/neighbors", () => {
|
||||||
|
const url = (cam: string, id: string) => `/api/cameras/${cam}/snapshots/${id}/neighbors`;
|
||||||
|
|
||||||
|
it("steps through one camera's snapshots by time, ties broken by id", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const { cookie } = await login(app, "admin", "pw");
|
||||||
|
shot("a", "cam-dahua", "2026-11-17T10:00:00.000Z");
|
||||||
|
shot("b", "cam-dahua", "2026-11-17T11:00:00.000Z");
|
||||||
|
shot("c", "cam-dahua", "2026-11-17T11:00:00.000Z"); // same instant as b
|
||||||
|
shot("d", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||||
|
shot("x", "other", "2026-11-17T11:30:00.000Z"); // another camera: never a neighbour
|
||||||
|
const get = async (id: string) => (await app.inject({ url: url("cam-dahua", id), headers: { cookie } })).json();
|
||||||
|
const ids = (r: { older: { id: string } | null; newer: { id: string } | null }) => [r.older?.id ?? null, r.newer?.id ?? null];
|
||||||
|
expect(ids(await get("a"))).toEqual([null, "b"]);
|
||||||
|
expect(ids(await get("b"))).toEqual(["a", "c"]);
|
||||||
|
expect(ids(await get("c"))).toEqual(["b", "d"]);
|
||||||
|
expect(ids(await get("d"))).toEqual(["c", null]);
|
||||||
|
expect(await get("b")).toMatchObject({ older: { id: "a", direction: "entry", capturedAt: "2026-11-17T10:00:00.000Z" } });
|
||||||
|
// latest-snapshot uses the same tie-break, so "newer" is never offered from the latest
|
||||||
|
const latest = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } });
|
||||||
|
expect(latest.json().id).toBe("d");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a tie at the newest end: latest-snapshot is the one with no newer", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const { cookie } = await login(app, "admin", "pw");
|
||||||
|
shot("p", "cam-dahua", "2026-11-17T10:00:00.000Z");
|
||||||
|
shot("q", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||||
|
shot("r", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||||
|
const latest = (await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } })).json();
|
||||||
|
const n = (await app.inject({ url: url("cam-dahua", latest.id), headers: { cookie } })).json();
|
||||||
|
expect(latest.id).toBe("r");
|
||||||
|
expect(n).toMatchObject({ older: { id: "q" }, newer: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("404s another camera's snapshot, 403s without session:read", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const admin = await login(app, "admin", "pw");
|
||||||
|
shot("x", "other", "2026-11-17T11:30:00.000Z");
|
||||||
|
const foreign = await app.inject({ url: url("cam-dahua", "x"), headers: { cookie: admin.cookie } });
|
||||||
|
expect(foreign.statusCode).toBe(404);
|
||||||
|
|
||||||
|
await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] });
|
||||||
|
const dev = await login(app, "dev", "pw");
|
||||||
|
const res = await app.inject({ url: url("other", "x"), headers: { cookie: dev.cookie } });
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("WS /api/cameras/:id/live", () => {
|
||||||
|
const origin = "http://booth.local:8080";
|
||||||
|
|
||||||
|
it("rejects a cross-origin handshake", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
await expect(
|
||||||
|
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin: "http://evil.example", host: "booth.local:8080" } }),
|
||||||
|
).rejects.toThrow(/403/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a role without device:read", async () => {
|
||||||
|
await seedUser(db, { username: "cash", password: "pw", roleId: "cashier2", permissions: ["session:read"] });
|
||||||
|
const auth = await login(app, "cash", "pw");
|
||||||
|
await expect(
|
||||||
|
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
|
||||||
|
).rejects.toThrow(/403/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("404s a device that is not a camera", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
await expect(
|
||||||
|
app.injectWS("/api/cameras/relay-1/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
|
||||||
|
).rejects.toThrow(/404/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tells the viewer when the camera has no live view", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
let resolveMsg!: (m: string) => void;
|
||||||
|
const first = new Promise<string>((r) => (resolveMsg = r));
|
||||||
|
const ws = await app.injectWS(
|
||||||
|
"/api/cameras/cam-dahua/live",
|
||||||
|
{ headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } },
|
||||||
|
{ onInit: (sock) => sock.once("message", (d) => resolveMsg(String(d))) },
|
||||||
|
);
|
||||||
|
const msg = await first;
|
||||||
|
expect(JSON.parse(msg)).toEqual({
|
||||||
|
kind: "status",
|
||||||
|
state: "unavailable",
|
||||||
|
reason: "live view not supported by this camera driver",
|
||||||
|
});
|
||||||
|
ws.terminate();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("PUT /api/auth/open-cameras", () => {
|
||||||
|
it("persists the open tiles and returns them on /me", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
const put = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: "/api/auth/open-cameras",
|
||||||
|
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
|
||||||
|
payload: { openCameras: ["cam-b", "cam-a", "cam-b"] },
|
||||||
|
});
|
||||||
|
expect(put.statusCode).toBe(200);
|
||||||
|
expect(put.json()).toEqual({ openCameras: ["cam-b", "cam-a"] });
|
||||||
|
const me = await app.inject({ url: "/api/auth/me", headers: { cookie: auth.cookie } });
|
||||||
|
expect(me.json().openCameras).toEqual(["cam-b", "cam-a"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a malformed list", async () => {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
const auth = await login(app, "admin", "pw");
|
||||||
|
const res = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: "/api/auth/open-cameras",
|
||||||
|
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
|
||||||
|
payload: { openCameras: Array.from({ length: 9 }, (_, i) => `c${i}`) },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { and, asc, desc, devices, eq, gt, gte, lt, lte, or, snapshots, type Db } from "@parking/db";
|
||||||
|
import { isLiveStreamDevice } from "@parking/devices";
|
||||||
|
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||||
|
import { buildCamera } from "../snapshot.js";
|
||||||
|
import type { CameraLiveHub, LiveResolver, LiveStatus } from "../camera-live.js";
|
||||||
|
import { authenticateWsHandshake } from "./ws.js";
|
||||||
|
|
||||||
|
// The booth's camera tiles (wiki/decisions/camera-live-view.md):
|
||||||
|
// - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest
|
||||||
|
// entry/exit evidence still this camera captured (metadata; bytes stay at
|
||||||
|
// /api/snapshots/:id). Evidence → `session:read`, like every snapshot read.
|
||||||
|
// - GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors — the large view's ‹ ›:
|
||||||
|
// this camera's next older and next newer snapshot ({ older, newer }, each meta or
|
||||||
|
// null). Same permission. Order is (capturedAt, id) everywhere so ties are stable.
|
||||||
|
// - WS /api/cameras/:deviceId/live — live video while the camera sees a vehicle.
|
||||||
|
// Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie),
|
||||||
|
// then `device:read` (the footer's permission). Server → client: text JSON
|
||||||
|
// `{kind:"status", ...LiveStatus}` and binary messages, each one complete JPEG.
|
||||||
|
// Advisory viewing only: no route here writes anything.
|
||||||
|
|
||||||
|
/** Bytes a viewer's socket may hold unsent before frames are skipped for it. */
|
||||||
|
const MAX_BUFFERED_BYTES = 256 * 1024;
|
||||||
|
|
||||||
|
/** Resolve a camera id to its live capability, or the reason it has none. */
|
||||||
|
export function liveResolverFor(db: Db): LiveResolver {
|
||||||
|
return (deviceId) => {
|
||||||
|
const row = db.select().from(devices).where(eq(devices.id, deviceId)).get();
|
||||||
|
if (!row || row.category !== "camera") return "unknown camera";
|
||||||
|
if (!row.enabled) return "camera disabled";
|
||||||
|
const camera = buildCamera(row);
|
||||||
|
if (!camera) return "camera driver unavailable";
|
||||||
|
if (!isLiveStreamDevice(camera)) return "live view not supported by this camera driver";
|
||||||
|
return camera;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLiveHub): Promise<void> {
|
||||||
|
app.get<{ Params: { deviceId: string } }>(
|
||||||
|
"/api/cameras/:deviceId/latest-snapshot",
|
||||||
|
{ preHandler: requirePermission("session:read") },
|
||||||
|
async (req, reply) => {
|
||||||
|
// Uses snapshots_device_time_idx (migration 0033): one index seek, not a scan.
|
||||||
|
const row = db
|
||||||
|
.select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt })
|
||||||
|
.from(snapshots)
|
||||||
|
.where(eq(snapshots.deviceId, req.params.deviceId))
|
||||||
|
.orderBy(desc(snapshots.capturedAt), desc(snapshots.id))
|
||||||
|
.limit(1)
|
||||||
|
.get();
|
||||||
|
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
|
||||||
|
return row;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.get<{ Params: { deviceId: string; snapshotId: string } }>(
|
||||||
|
"/api/cameras/:deviceId/snapshots/:snapshotId/neighbors",
|
||||||
|
{ preHandler: requirePermission("session:read") },
|
||||||
|
async (req, reply) => {
|
||||||
|
const { deviceId, snapshotId } = req.params;
|
||||||
|
const at = db
|
||||||
|
.select({ capturedAt: snapshots.capturedAt })
|
||||||
|
.from(snapshots)
|
||||||
|
.where(and(eq(snapshots.id, snapshotId), eq(snapshots.deviceId, deviceId)))
|
||||||
|
.get();
|
||||||
|
if (!at) return reply.code(404).send({ error: "no such snapshot for this camera" });
|
||||||
|
const meta = { id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt };
|
||||||
|
// capturedAt is always toISOString() (UTC, fixed width), so string order = time order.
|
||||||
|
// The plain lte/gte bound next to the OR lets SQLite seek snapshots_device_time_idx
|
||||||
|
// from this snapshot instead of walking the camera's index from one end.
|
||||||
|
const older = db
|
||||||
|
.select(meta)
|
||||||
|
.from(snapshots)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(snapshots.deviceId, deviceId),
|
||||||
|
lte(snapshots.capturedAt, at.capturedAt),
|
||||||
|
or(lt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), lt(snapshots.id, snapshotId))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(desc(snapshots.capturedAt), desc(snapshots.id))
|
||||||
|
.limit(1)
|
||||||
|
.get();
|
||||||
|
const newer = db
|
||||||
|
.select(meta)
|
||||||
|
.from(snapshots)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(snapshots.deviceId, deviceId),
|
||||||
|
gte(snapshots.capturedAt, at.capturedAt),
|
||||||
|
or(gt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), gt(snapshots.id, snapshotId))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(asc(snapshots.capturedAt), asc(snapshots.id))
|
||||||
|
.limit(1)
|
||||||
|
.get();
|
||||||
|
return { older: older ?? null, newer: newer ?? null };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.get<{ Params: { deviceId: string } }>(
|
||||||
|
"/api/cameras/:deviceId/live",
|
||||||
|
{
|
||||||
|
websocket: true,
|
||||||
|
preHandler: async (req) => {
|
||||||
|
const roleId = await authenticateWsHandshake(req);
|
||||||
|
if (!roleHasPermissions(roleId, ["device:read"])) {
|
||||||
|
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||||
|
}
|
||||||
|
const row = db.select({ category: devices.category }).from(devices).where(eq(devices.id, req.params.deviceId)).get();
|
||||||
|
if (!row || row.category !== "camera") {
|
||||||
|
throw Object.assign(new Error("unknown camera"), { statusCode: 404 });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(socket, req) => {
|
||||||
|
const open = () => socket.readyState === 1;
|
||||||
|
const unsubscribe = hub.subscribe(req.params.deviceId, {
|
||||||
|
sendFrame: (jpeg) => {
|
||||||
|
if (open()) socket.send(jpeg, { binary: true });
|
||||||
|
},
|
||||||
|
sendStatus: (status: LiveStatus) => {
|
||||||
|
if (open()) socket.send(JSON.stringify({ kind: "status", ...status }));
|
||||||
|
},
|
||||||
|
busy: () => !open() || socket.bufferedAmount > MAX_BUFFERED_BYTES,
|
||||||
|
});
|
||||||
|
socket.on("close", unsubscribe);
|
||||||
|
socket.on("error", unsubscribe);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import { ledgerEvents, eq, type Db } from "@parking/db";
|
||||||
|
import { buildServer } from "../server.js";
|
||||||
|
import { login, makeLog, minutesAgo, seedTariff, seedUser } from "../test-helpers.js";
|
||||||
|
|
||||||
|
// HTTP integration for the FORGIVEN exit (wiki/decisions/forgiven-exit.md): the route is
|
||||||
|
// gated on `barrier:create` (admin by default, grantable per role), needs an open shift
|
||||||
|
// and a reason, and signs a $0 payment carrying the forgone fee + the exit. Drives the
|
||||||
|
// REAL app over a fresh in-memory DB via app.inject.
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
let close: () => void;
|
||||||
|
let app: FastifyInstance;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const t = createTestDb();
|
||||||
|
db = t.db;
|
||||||
|
close = t.close;
|
||||||
|
app = await buildServer({ db });
|
||||||
|
await app.ready();
|
||||||
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
close();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function as(opts: { username: string; roleId?: string; permissions?: Parameters<typeof seedUser>[1]["permissions"] }) {
|
||||||
|
const { username, password } = await seedUser(db, opts);
|
||||||
|
const { cookie, csrf } = await login(app, username, password);
|
||||||
|
return { cookie, "x-csrf-token": csrf };
|
||||||
|
}
|
||||||
|
async function enter(identity: string) {
|
||||||
|
await makeLog(db).append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: minutesAgo(90), payload: null });
|
||||||
|
}
|
||||||
|
function events(identity: string) {
|
||||||
|
return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("POST /api/barrier/forgive", () => {
|
||||||
|
it("is refused without barrier:create (an operator who can take payment but was not granted it)", async () => {
|
||||||
|
const h = await as({ username: "op", roleId: "operator", permissions: ["payment:create", "session:read", "shift:create"] });
|
||||||
|
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
|
||||||
|
await enter("T1");
|
||||||
|
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "friend" } });
|
||||||
|
expect(r.statusCode).toBe(403);
|
||||||
|
expect(events("T1").map((e) => e.type)).toEqual(["vehicle_entry"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a role the owner granted barrier:create can forgive; the reason is optional; a shift must be open", async () => {
|
||||||
|
const h = await as({ username: "trusted", roleId: "senior", permissions: ["payment:create", "session:read", "shift:create", "shift:read", "barrier:create"] });
|
||||||
|
await enter("T1");
|
||||||
|
// No shift yet → the money-path gate refuses.
|
||||||
|
let r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "x" } });
|
||||||
|
expect(r.statusCode).toBe(409);
|
||||||
|
expect(r.json()).toMatchObject({ code: "no_shift" });
|
||||||
|
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
|
||||||
|
// Forgiven: $0 payment with the fee as forgone, then the exit. No relay configured →
|
||||||
|
// ok:true, opened:false with the open-by-hand reason (the ledger side is complete).
|
||||||
|
r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "known customer, lost ticket" } });
|
||||||
|
expect(r.statusCode).toBe(200);
|
||||||
|
expect(r.json()).toMatchObject({ ok: true, opened: false, forgoneMinor: 20000 });
|
||||||
|
const types = events("T1").map((e) => e.type);
|
||||||
|
expect(types).toEqual(["vehicle_entry", "payment", "anomaly", "vehicle_exit"]);
|
||||||
|
const payment = events("T1").find((e) => e.type === "payment")!;
|
||||||
|
expect(payment.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "trusted", reasonCode: "exit.forgiven" });
|
||||||
|
// The Z-report carries it as its own line, and the takings stay at zero.
|
||||||
|
const rep = (await app.inject({ method: "GET", url: "/api/shift/report", headers: h })).json() as Record<string, unknown>;
|
||||||
|
expect(rep).toMatchObject({ cashTotalMinor: 0, cardTotalMinor: 0, forgoneTotalMinor: 20000, forgoneCount: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no ticket, no reason: admin opens the exit for a car with no session → anomaly only, readable sentence", async () => {
|
||||||
|
const h = await as({ username: "boss", roleId: "admin" });
|
||||||
|
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
|
||||||
|
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: {} });
|
||||||
|
expect(r.statusCode).toBe(200);
|
||||||
|
const all = db.select().from(ledgerEvents).all();
|
||||||
|
const anomaly = all.find((e) => e.type === "anomaly")!;
|
||||||
|
expect(anomaly.identity).toMatch(/^forgiven:/);
|
||||||
|
expect(anomaly.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", operator: "boss" });
|
||||||
|
expect((anomaly.payload as { reason: string }).reason).toContain("(no reason given)");
|
||||||
|
expect(all.filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@ import type { FastifyInstance } from "fastify";
|
|||||||
import { buildServer } from "../server.js";
|
import { buildServer } from "../server.js";
|
||||||
import { hikvisionAlarmRoutes } from "./hikvision-alarm.js";
|
import { hikvisionAlarmRoutes } from "./hikvision-alarm.js";
|
||||||
import type { AnprBridge } from "../anpr-entry.js";
|
import type { AnprBridge } from "../anpr-entry.js";
|
||||||
|
import type { CameraActivity } from "../camera-activity.js";
|
||||||
import { seedUser, login } from "../test-helpers.js";
|
import { seedUser, login } from "../test-helpers.js";
|
||||||
|
|
||||||
// Hikvision Alarm Server push ingress. Verifies the discovery endpoint: a vehicle-
|
// Hikvision Alarm Server push ingress. Verifies the discovery endpoint: a vehicle-
|
||||||
@@ -235,6 +236,7 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
|
|||||||
let rawDb: Db;
|
let rawDb: Db;
|
||||||
let rawClose: () => void;
|
let rawClose: () => void;
|
||||||
let onVehicleDetected: ReturnType<typeof vi.fn>;
|
let onVehicleDetected: ReturnType<typeof vi.fn>;
|
||||||
|
let cameraSaw: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const t = createTestDb();
|
const t = createTestDb();
|
||||||
@@ -243,7 +245,9 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
|
|||||||
onVehicleDetected = vi.fn(async () => {});
|
onVehicleDetected = vi.fn(async () => {});
|
||||||
const bridge = { onVehicleDetected } as unknown as AnprBridge;
|
const bridge = { onVehicleDetected } as unknown as AnprBridge;
|
||||||
rawApp = Fastify();
|
rawApp = Fastify();
|
||||||
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge);
|
cameraSaw = vi.fn();
|
||||||
|
const activity = { vehicleDetected: cameraSaw } as unknown as CameraActivity;
|
||||||
|
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge, activity);
|
||||||
await rawApp.ready();
|
await rawApp.ready();
|
||||||
rawDb.insert(devices).values({
|
rawDb.insert(devices).values({
|
||||||
id: CAM_ID,
|
id: CAM_ID,
|
||||||
@@ -275,10 +279,16 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
|
|||||||
expect(onVehicleDetected).toHaveBeenCalledWith(CAM_ID);
|
expect(onVehicleDetected).toHaveBeenCalledWith(CAM_ID);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("marks THIS camera active for the booth camera tile", async () => {
|
||||||
|
await post(VEHICLE_XML);
|
||||||
|
expect(cameraSaw).toHaveBeenCalledWith(CAM_ID);
|
||||||
|
});
|
||||||
|
|
||||||
it("does NOT call the bridge for a human target", async () => {
|
it("does NOT call the bridge for a human target", async () => {
|
||||||
const human = VEHICLE_XML.replace("vehicle", "human");
|
const human = VEHICLE_XML.replace("vehicle", "human");
|
||||||
await post(human);
|
await post(human);
|
||||||
expect(onVehicleDetected).not.toHaveBeenCalled();
|
expect(onVehicleDetected).not.toHaveBeenCalled();
|
||||||
|
expect(cameraSaw).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does NOT call the bridge on an `inactive` (leave) vehicle event", async () => {
|
it("does NOT call the bridge on an `inactive` (leave) vehicle event", async () => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { requirePermission } from "../auth.js";
|
|||||||
import { verifyDigest } from "../digest-auth.js";
|
import { verifyDigest } from "../digest-auth.js";
|
||||||
import type { LaneStatus } from "../lane-status.js";
|
import type { LaneStatus } from "../lane-status.js";
|
||||||
import type { AnprBridge } from "../anpr-entry.js";
|
import type { AnprBridge } from "../anpr-entry.js";
|
||||||
|
import type { CameraActivity } from "../camera-activity.js";
|
||||||
|
|
||||||
// Hikvision "Alarm Server" event PUSH ingress. The newer-firmware cameras (Event →
|
// Hikvision "Alarm Server" event PUSH ingress. The newer-firmware cameras (Event →
|
||||||
// Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm
|
// Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm
|
||||||
@@ -101,6 +102,7 @@ export async function hikvisionAlarmRoutes(
|
|||||||
db: Db,
|
db: Db,
|
||||||
laneStatus?: LaneStatus,
|
laneStatus?: LaneStatus,
|
||||||
anprBridge?: AnprBridge,
|
anprBridge?: AnprBridge,
|
||||||
|
cameraActivity?: CameraActivity,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Accept ANY content-type as a raw Buffer (the camera may POST application/xml,
|
// Accept ANY content-type as a raw Buffer (the camera may POST application/xml,
|
||||||
// multipart/form-data with a JPEG, or text). Fastify's default JSON parser would 415
|
// multipart/form-data with a JPEG, or text). Fastify's default JSON parser would 415
|
||||||
@@ -159,9 +161,11 @@ export async function hikvisionAlarmRoutes(
|
|||||||
const contentType = String(req.headers["content-type"] ?? "");
|
const contentType = String(req.headers["content-type"] ?? "");
|
||||||
const raw: Buffer = Buffer.isBuffer(req.body) ? (req.body as Buffer) : Buffer.from("");
|
const raw: Buffer = Buffer.isBuffer(req.body) ? (req.body as Buffer) : Buffer.from("");
|
||||||
const summary = summarize(raw.toString("utf8"));
|
const summary = summarize(raw.toString("utf8"));
|
||||||
// Log EVERY hit immediately (method + ip + size), before any guard — so even a probe
|
// Log EVERY hit immediately (method + ip + size), before any guard — so under
|
||||||
// that gets rejected is visible in the dev log the instant it arrives.
|
// LOG_LEVEL=debug even a probe that gets rejected is visible the instant it arrives.
|
||||||
app.log.info(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
|
// debug, not info: every accepted hit is followed by the ACCEPTED line (which carries
|
||||||
|
// all of this plus the verdict) and every rejected one by the REJECTED warn.
|
||||||
|
app.log.debug(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
|
||||||
|
|
||||||
// Guard: must be a known hikvision device with alarm-push enabled, posting from its
|
// Guard: must be a known hikvision device with alarm-push enabled, posting from its
|
||||||
// configured host IP. Source-IP is the primary guard on the LAN (like the Dingtian).
|
// configured host IP. Source-IP is the primary guard on the LAN (like the Dingtian).
|
||||||
@@ -211,6 +215,10 @@ export async function hikvisionAlarmRoutes(
|
|||||||
if (laneStatus && isVehicleActive) {
|
if (laneStatus && isVehicleActive) {
|
||||||
laneStatus.vehicleDetected(deviceId);
|
laneStatus.vehicleDetected(deviceId);
|
||||||
}
|
}
|
||||||
|
// The same signal per camera: the booth's tile for THIS camera switches to live video.
|
||||||
|
if (cameraActivity && isVehicleActive) {
|
||||||
|
cameraActivity.vehicleDetected(deviceId);
|
||||||
|
}
|
||||||
|
|
||||||
// ANPR BRIDGE: on a vehicle detection, if this camera opts into ANPR (config.anpr),
|
// ANPR BRIDGE: on a vehicle detection, if this camera opts into ANPR (config.anpr),
|
||||||
// pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read
|
// pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ export async function payRoutes(
|
|||||||
const guard = requirePermission("payment:create");
|
const guard = requirePermission("payment:create");
|
||||||
const readGuard = requirePermission("session:read");
|
const readGuard = requirePermission("session:read");
|
||||||
const voidGuard = requirePermission("event:void");
|
const voidGuard = requirePermission("event:void");
|
||||||
|
const forgiveGuard = requirePermission("barrier:create");
|
||||||
|
|
||||||
// Money-path gate: a shift must be open site-wide before any payment/exit/voucher/
|
// Money-path gate: a shift must be open site-wide before any payment/exit/voucher/
|
||||||
// re-open is processed, so every taking is attributed to a shift (one operator's
|
// re-open is processed, so every taking is attributed to a shift (one operator's
|
||||||
@@ -144,6 +145,37 @@ export async function payRoutes(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// FORGIVEN exit (wiki/decisions/forgiven-exit.md): an operator holding barrier:create
|
||||||
|
// lets a car out with NO money. With a ticket: PayStation.forgive signs a $0 payment
|
||||||
|
// carrying the forgone fee (never in cash/card), then the human-intervention re-open
|
||||||
|
// signs the exit + pulses. Without a ticket: anomaly + snapshot + pulse. A free-text
|
||||||
|
// reason is OPTIONAL (user, 2026-10-09 — the signature + snapshot + Z-report line are
|
||||||
|
// the accountability); an open shift is required so it lands on someone's Z-report.
|
||||||
|
// Prints nothing.
|
||||||
|
app.post<{ Body: { identity?: string; note?: string } }>(
|
||||||
|
"/api/barrier/forgive",
|
||||||
|
{ preHandler: [forgiveGuard, requireShift] },
|
||||||
|
async (req, reply) => {
|
||||||
|
const note = (req.body?.note ?? "").trim();
|
||||||
|
const identity = (req.body?.identity ?? "").trim();
|
||||||
|
const operator = req.user?.username ?? "?";
|
||||||
|
if (!identity) {
|
||||||
|
const r = await exitFlow.forgiveExitNoSession(operator, note);
|
||||||
|
if (!r.ok) return reply.code(409).send({ error: r.reason });
|
||||||
|
return reply.code(200).send(r);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const f = await payStation.forgive(identity, { operator, note });
|
||||||
|
if (!f.ok) return reply.code(409).send({ error: f.reason });
|
||||||
|
const r = await exitFlow.reopenBarrier(identity, operator, { forgiven: { note, forgoneMinor: f.forgoneMinor, currency: f.currency } });
|
||||||
|
if (!r.ok) return reply.code(409).send({ error: r.reason });
|
||||||
|
return reply.code(200).send({ ...r, forgoneMinor: f.forgoneMinor, currency: f.currency });
|
||||||
|
} catch (err) {
|
||||||
|
return mapError(reply, err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Cancel (void) a wrongly-printed transient ticket. Appends a SIGNED `void` event
|
// Cancel (void) a wrongly-printed transient ticket. Appends a SIGNED `void` event
|
||||||
// referencing the entry, with the operator + a REQUIRED reason — the entry itself is
|
// referencing the entry, with the operator + a REQUIRED reason — the entry itself is
|
||||||
// never edited/deleted (append-only). The session projection folds the void to CLOSED,
|
// never edited/deleted (append-only). The session projection folds the void to CLOSED,
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { devices, eq, type Db } from "@parking/db";
|
||||||
|
import { createTestDb } from "@parking/db/testing";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { buildServer } from "../server.js";
|
||||||
|
import { seedUser, login } from "../test-helpers.js";
|
||||||
|
|
||||||
|
// A camera's crossing line (passage confirmation) rides in its config as `crossing`. The
|
||||||
|
// save validates it (the driver never reads it), and since an edit MERGES onto the stored
|
||||||
|
// config, clearing it must be an explicit `null`.
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
let close: () => void;
|
||||||
|
let app: FastifyInstance;
|
||||||
|
const CAM = "cam-1";
|
||||||
|
const line = { p1: { x: 0.1, y: 0.6 }, p2: { x: 0.9, y: 0.55 }, direction: "a-to-b" };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
({ db, close } = createTestDb());
|
||||||
|
db.insert(devices).values({
|
||||||
|
id: CAM,
|
||||||
|
category: "camera",
|
||||||
|
driverId: "dahua",
|
||||||
|
config: { host: "127.0.0.1", port: 80, username: "u", password: "p" },
|
||||||
|
enabled: true,
|
||||||
|
}).run();
|
||||||
|
app = await buildServer({ db });
|
||||||
|
await app.ready();
|
||||||
|
auth = undefined;
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
close();
|
||||||
|
});
|
||||||
|
|
||||||
|
let auth: { cookie: string; csrf: string } | undefined;
|
||||||
|
async function edit(config: Record<string, unknown>) {
|
||||||
|
if (!auth) {
|
||||||
|
await seedUser(db, { username: "admin", password: "pw" });
|
||||||
|
auth = await login(app, "admin", "pw");
|
||||||
|
}
|
||||||
|
return app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: `/api/setup/assign/${CAM}`,
|
||||||
|
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
|
||||||
|
payload: { config: { host: "127.0.0.1", port: 80, username: "u", password: "p", ...config } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const stored = () => db.select().from(devices).where(eq(devices.id, CAM)).get()!.config as Record<string, unknown>;
|
||||||
|
|
||||||
|
describe("camera crossing line on save", () => {
|
||||||
|
it("stores a valid line", async () => {
|
||||||
|
const res = await edit({ crossing: line });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(stored().crossing).toEqual(line);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the stored line when the edit doesn't mention it, and clears it on null", async () => {
|
||||||
|
await edit({ crossing: line });
|
||||||
|
await edit({});
|
||||||
|
expect(stored().crossing).toEqual(line);
|
||||||
|
const res = await edit({ crossing: null });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(stored()).not.toHaveProperty("crossing");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an invalid line and leaves the stored config alone", async () => {
|
||||||
|
const res = await edit({ crossing: { ...line, p2: { x: 1.4, y: 0.5 } } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
expect(stored()).not.toHaveProperty("crossing");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { randomBytes, randomUUID } from "node:crypto";
|
import { randomBytes, randomUUID } from "node:crypto";
|
||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { eq, devices, setupState, type Db } from "@parking/db";
|
import { eq, devices, setupState, type Db } from "@parking/db";
|
||||||
|
import { pulseBarrier } from "../relay-pulse.js";
|
||||||
import {
|
import {
|
||||||
hasPreconditions,
|
hasPreconditions,
|
||||||
hasPushConfig,
|
hasPushConfig,
|
||||||
@@ -15,7 +16,7 @@ import {
|
|||||||
type DeviceCategory,
|
type DeviceCategory,
|
||||||
type DeviceConfig,
|
type DeviceConfig,
|
||||||
} from "@parking/devices";
|
} from "@parking/devices";
|
||||||
import { reasonPayload } from "@parking/shared";
|
import { parseCrossingLine, reasonPayload } from "@parking/shared";
|
||||||
import { requirePermission } from "../auth.js";
|
import { requirePermission } from "../auth.js";
|
||||||
import type { EventLog } from "../event-log.js";
|
import type { EventLog } from "../event-log.js";
|
||||||
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
|
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
|
||||||
@@ -146,6 +147,17 @@ async function configureDevice(
|
|||||||
// webPasswordCurrent is an input-only credential (the OLD password used to
|
// webPasswordCurrent is an input-only credential (the OLD password used to
|
||||||
// authorize the change) — never persist it as typed.
|
// authorize the change) — never persist it as typed.
|
||||||
delete fullConfig.webPasswordCurrent;
|
delete fullConfig.webPasswordCurrent;
|
||||||
|
// Camera crossing line (passage confirmation): validated here, since the driver doesn't
|
||||||
|
// read it. `null` clears it — the merge above would otherwise keep the stored line.
|
||||||
|
if ("crossing" in config) {
|
||||||
|
if (config.crossing === null) {
|
||||||
|
delete fullConfig.crossing;
|
||||||
|
} else {
|
||||||
|
const line = parseCrossingLine(config.crossing);
|
||||||
|
if (!line) return { error: { code: 400, message: "invalid crossing line" } };
|
||||||
|
fullConfig.crossing = { ...line };
|
||||||
|
}
|
||||||
|
}
|
||||||
// Residual-risk warnings from device hardening (shown to the admin; the
|
// Residual-risk warnings from device hardening (shown to the admin; the
|
||||||
// save still succeeds — these are "configured, but note X" advisories).
|
// save still succeeds — these are "configured, but note X" advisories).
|
||||||
const hardenWarnings: string[] = [];
|
const hardenWarnings: string[] = [];
|
||||||
@@ -191,31 +203,44 @@ async function configureDevice(
|
|||||||
|
|
||||||
if (hasPushConfig(device)) {
|
if (hasPushConfig(device)) {
|
||||||
const host = String(config.host ?? "");
|
const host = String(config.host ?? "");
|
||||||
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
if (!host) {
|
||||||
const pushHost = backendIp ?? backendIpForDevice(host);
|
// Only reachable for a push device whose host is OPTIONAL (the DT-008 reader:
|
||||||
if (!pushHost) {
|
// scans resolve by serial, the IP is what lets us configure it). Nothing to talk
|
||||||
return {
|
// to → save, but say so: the reader must then be set up by hand.
|
||||||
error: {
|
hardenWarnings.push(
|
||||||
code: 400,
|
"no IP given — the reader was NOT configured: set its output type to HTTP and its server to this booth with the vendor tool (or add its IP here and save again)",
|
||||||
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
);
|
||||||
},
|
} else {
|
||||||
};
|
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
||||||
|
const pushHost = backendIp ?? backendIpForDevice(host);
|
||||||
|
if (!pushHost) {
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
code: 400,
|
||||||
|
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const pushUser = "dingtian";
|
||||||
|
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
||||||
|
// (longer is silently truncated → auth mismatch), so keep it short.
|
||||||
|
const pushPassword = randomBytes(12).toString("hex");
|
||||||
|
await device.configureInputPush({
|
||||||
|
host: pushHost,
|
||||||
|
port: backendPort(),
|
||||||
|
pathBase: `/api/devices/${driverId}/${id}/input`,
|
||||||
|
auth: { user: pushUser, password: pushPassword },
|
||||||
|
});
|
||||||
|
// A device whose push carries no credentials (the DT-008 scan GET) has no use
|
||||||
|
// for these — don't persist a secret nothing checks.
|
||||||
|
if (device.usesPushAuth !== false) {
|
||||||
|
fullConfig.pushUser = pushUser;
|
||||||
|
fullConfig.pushPassword = pushPassword;
|
||||||
|
}
|
||||||
|
// Record the backend IP the device was told to push to — lets us detect
|
||||||
|
// a later mismatch if the host's IP changes.
|
||||||
|
fullConfig.backendIp = pushHost;
|
||||||
}
|
}
|
||||||
const pushUser = "dingtian";
|
|
||||||
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
|
||||||
// (longer is silently truncated → auth mismatch), so keep it short.
|
|
||||||
const pushPassword = randomBytes(12).toString("hex");
|
|
||||||
await device.configureInputPush({
|
|
||||||
host: pushHost,
|
|
||||||
port: backendPort(),
|
|
||||||
pathBase: `/api/devices/${driverId}/${id}/input`,
|
|
||||||
auth: { user: pushUser, password: pushPassword },
|
|
||||||
});
|
|
||||||
fullConfig.pushUser = pushUser;
|
|
||||||
fullConfig.pushPassword = pushPassword;
|
|
||||||
// Record the backend IP the device was told to push to — lets us detect
|
|
||||||
// a later mismatch if the host's IP changes.
|
|
||||||
fullConfig.backendIp = pushHost;
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
|
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
|
||||||
@@ -231,7 +256,7 @@ export async function setupRoutes(
|
|||||||
eventLog?: EventLog | null,
|
eventLog?: EventLog | null,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
registerBuiltinDrivers();
|
registerBuiltinDrivers();
|
||||||
setDeviceLogSink((line) => app.log.info(line));
|
setDeviceLogSink((line, level) => app.log[level](line));
|
||||||
|
|
||||||
// Device setup is site administration — it changes which hardware the site runs
|
// Device setup is site administration — it changes which hardware the site runs
|
||||||
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
|
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
|
||||||
@@ -494,7 +519,7 @@ export async function setupRoutes(
|
|||||||
return reply.code(400).send({ error: `device ${id} is not a controller` });
|
return reply.code(400).send({ error: `device ${id} is not a controller` });
|
||||||
}
|
}
|
||||||
const cfg = (row.config ?? {}) as Record<string, unknown>;
|
const cfg = (row.config ?? {}) as Record<string, unknown>;
|
||||||
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number }[]) : [];
|
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number; direction?: string }[]) : [];
|
||||||
if (!relays.some((r) => r.relay === relay)) {
|
if (!relays.some((r) => r.relay === relay)) {
|
||||||
return reply.code(400).send({ error: `controller ${id} has no relay ${relay}` });
|
return reply.code(400).send({ error: `controller ${id} has no relay ${relay}` });
|
||||||
}
|
}
|
||||||
@@ -532,8 +557,14 @@ export async function setupRoutes(
|
|||||||
});
|
});
|
||||||
|
|
||||||
const startedAt = Date.now();
|
const startedAt = Date.now();
|
||||||
|
const relayDir = relays.find((r) => r.relay === relay)?.direction;
|
||||||
try {
|
try {
|
||||||
await device.pulseOpen(relay);
|
await pulseBarrier(db, req.log, device, { controller: row, relay }, {
|
||||||
|
direction: relayDir === "entry" || relayDir === "exit" ? relayDir : "both",
|
||||||
|
identity: `relay-test:${id}:${relay}`,
|
||||||
|
source: "relay-test",
|
||||||
|
operator,
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// The failure we're testing for (relay unreachable, wrong password). The open is
|
// The failure we're testing for (relay unreachable, wrong password). The open is
|
||||||
// already signed; report the pulse failure, don't 500.
|
// already signed; report the pulse failure, don't 500.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||||
import type { Db } from "@parking/db";
|
import type { Db } from "@parking/db";
|
||||||
import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared";
|
import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared";
|
||||||
import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js";
|
import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js";
|
||||||
@@ -9,7 +9,9 @@ import {
|
|||||||
type LaneStatusEvent,
|
type LaneStatusEvent,
|
||||||
type LanePresenceEvent,
|
type LanePresenceEvent,
|
||||||
type PlateRecognizedEvent,
|
type PlateRecognizedEvent,
|
||||||
|
type CameraActivityEvent,
|
||||||
} from "../device-events.js";
|
} from "../device-events.js";
|
||||||
|
import type { CameraActivity } from "../camera-activity.js";
|
||||||
import { enrichEvent } from "../event-enrich.js";
|
import { enrichEvent } from "../event-enrich.js";
|
||||||
import type { DeviceMonitor } from "../device-monitor.js";
|
import type { DeviceMonitor } from "../device-monitor.js";
|
||||||
import type { LaneStatus } from "../lane-status.js";
|
import type { LaneStatus } from "../lane-status.js";
|
||||||
@@ -111,6 +113,32 @@ function isAllowedOrigin(origin: string | undefined, host: string | undefined):
|
|||||||
return allow.includes(origin);
|
return allow.includes(origin);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate a WebSocket handshake and return the caller's role id: Origin allowlist
|
||||||
|
* FIRST (anti-CSWSH), then a desktop ticket (x-ws-ticket) or the JWT cookie. Shared by
|
||||||
|
* every socket route (/api/ws, /api/cameras/:id/live) so they cannot drift apart.
|
||||||
|
* Permission checks stay with each route.
|
||||||
|
*/
|
||||||
|
export async function authenticateWsHandshake(req: FastifyRequest): Promise<string> {
|
||||||
|
if (!isAllowedOrigin(req.headers.origin, req.headers.host)) {
|
||||||
|
throw Object.assign(new Error("forbidden origin"), { statusCode: 403 });
|
||||||
|
}
|
||||||
|
const rawTicket = req.headers[WS_TICKET_HEADER];
|
||||||
|
const ticket = Array.isArray(rawTicket) ? rawTicket[0] : rawTicket;
|
||||||
|
if (ticket !== undefined) {
|
||||||
|
const t = consumeWsTicket(ticket);
|
||||||
|
if (!t) {
|
||||||
|
throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 });
|
||||||
|
}
|
||||||
|
return t.roleId;
|
||||||
|
}
|
||||||
|
await req.jwtVerify(); // reads the HttpOnly cookie (browser path)
|
||||||
|
if (!req.user) {
|
||||||
|
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||||
|
}
|
||||||
|
return currentRoleId(req.user.sub) ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
type OutMsg =
|
type OutMsg =
|
||||||
| {
|
| {
|
||||||
kind: "hello";
|
kind: "hello";
|
||||||
@@ -118,12 +146,15 @@ type OutMsg =
|
|||||||
devices: unknown;
|
devices: unknown;
|
||||||
lanes: LaneStatusEvent | null;
|
lanes: LaneStatusEvent | null;
|
||||||
radar: LanePresenceEvent | null;
|
radar: LanePresenceEvent | null;
|
||||||
|
/** Camera ids currently seeing a vehicle (camera tiles go live). */
|
||||||
|
cameras: string[] | null;
|
||||||
}
|
}
|
||||||
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> | null }
|
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> | null }
|
||||||
| { kind: "printer-status"; event: unknown }
|
| { kind: "printer-status"; event: unknown }
|
||||||
| { kind: "device-status"; event: unknown }
|
| { kind: "device-status"; event: unknown }
|
||||||
| { kind: "lane-status"; lanes: LaneStatusEvent }
|
| { kind: "lane-status"; lanes: LaneStatusEvent }
|
||||||
| { kind: "lane-presence"; radar: LanePresenceEvent }
|
| { kind: "lane-presence"; radar: LanePresenceEvent }
|
||||||
|
| { kind: "camera-activity"; camera: CameraActivityEvent }
|
||||||
| { kind: "plate-recognized"; plate: PlateRecognizedEvent };
|
| { kind: "plate-recognized"; plate: PlateRecognizedEvent };
|
||||||
|
|
||||||
declare module "fastify" {
|
declare module "fastify" {
|
||||||
@@ -139,6 +170,7 @@ export async function wsRoutes(
|
|||||||
deviceMonitor: DeviceMonitor,
|
deviceMonitor: DeviceMonitor,
|
||||||
laneStatus: LaneStatus,
|
laneStatus: LaneStatus,
|
||||||
lanePresence: LanePresence,
|
lanePresence: LanePresence,
|
||||||
|
cameraActivity: CameraActivity,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Desktop-only: mint a WS ticket for the signed-in session (see file header).
|
// Desktop-only: mint a WS ticket for the signed-in session (see file header).
|
||||||
// Ordinary cookie + CSRF auth — the desktop client CAN do that over HTTP (via
|
// Ordinary cookie + CSRF auth — the desktop client CAN do that over HTTP (via
|
||||||
@@ -157,25 +189,7 @@ export async function wsRoutes(
|
|||||||
// cross/absent origin before touching either credential, so a hijack
|
// cross/absent origin before touching either credential, so a hijack
|
||||||
// attempt never reaches an authenticated socket.
|
// attempt never reaches an authenticated socket.
|
||||||
preHandler: async (req) => {
|
preHandler: async (req) => {
|
||||||
if (!isAllowedOrigin(req.headers.origin, req.headers.host)) {
|
const roleId = await authenticateWsHandshake(req);
|
||||||
throw Object.assign(new Error("forbidden origin"), { statusCode: 403 });
|
|
||||||
}
|
|
||||||
const rawTicket = req.headers[WS_TICKET_HEADER];
|
|
||||||
const ticket = Array.isArray(rawTicket) ? rawTicket[0] : rawTicket;
|
|
||||||
let roleId: string;
|
|
||||||
if (ticket !== undefined) {
|
|
||||||
const t = consumeWsTicket(ticket);
|
|
||||||
if (!t) {
|
|
||||||
throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 });
|
|
||||||
}
|
|
||||||
roleId = t.roleId;
|
|
||||||
} else {
|
|
||||||
await req.jwtVerify(); // reads the HttpOnly cookie (browser path)
|
|
||||||
if (!req.user) {
|
|
||||||
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
|
||||||
}
|
|
||||||
roleId = currentRoleId(req.user.sub) ?? "";
|
|
||||||
}
|
|
||||||
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
|
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
|
||||||
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||||
req.wsRoleId = roleId;
|
req.wsRoleId = roleId;
|
||||||
@@ -206,6 +220,7 @@ export async function wsRoutes(
|
|||||||
devices: seesDevices ? deviceMonitor.snapshot() : null,
|
devices: seesDevices ? deviceMonitor.snapshot() : null,
|
||||||
lanes: seesDevices ? laneStatus.snapshot() : null,
|
lanes: seesDevices ? laneStatus.snapshot() : null,
|
||||||
radar: seesDevices ? lanePresence.snapshot() : null,
|
radar: seesDevices ? lanePresence.snapshot() : null,
|
||||||
|
cameras: seesDevices ? cameraActivity.snapshot() : null,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Subscribe to the live buses. Each handler recomputes occupancy from the
|
// Subscribe to the live buses. Each handler recomputes occupancy from the
|
||||||
@@ -233,6 +248,10 @@ export async function wsRoutes(
|
|||||||
const offPresence = deviceEvents.onLanePresence((radar) => {
|
const offPresence = deviceEvents.onLanePresence((radar) => {
|
||||||
if (seesDevices) send({ kind: "lane-presence", radar });
|
if (seesDevices) send({ kind: "lane-presence", radar });
|
||||||
});
|
});
|
||||||
|
// A camera started/stopped seeing a vehicle → its booth tile switches live/snapshot.
|
||||||
|
const offCamera = deviceEvents.onCameraActivity((camera) => {
|
||||||
|
if (seesDevices) send({ kind: "camera-activity", camera });
|
||||||
|
});
|
||||||
// A late async plate recognition → backfill the badge on the matching feed row. Advisory.
|
// A late async plate recognition → backfill the badge on the matching feed row. Advisory.
|
||||||
const offPlate = deviceEvents.onPlateRecognized((plate) => {
|
const offPlate = deviceEvents.onPlateRecognized((plate) => {
|
||||||
if (seesOccupancy) send({ kind: "plate-recognized", plate });
|
if (seesOccupancy) send({ kind: "plate-recognized", plate });
|
||||||
@@ -245,6 +264,7 @@ export async function wsRoutes(
|
|||||||
offLane();
|
offLane();
|
||||||
offPresence();
|
offPresence();
|
||||||
offPlate();
|
offPlate();
|
||||||
|
offCamera();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ import { entryRoutes } from "./routes/entry.js";
|
|||||||
import { siteRoutes } from "./routes/site.js";
|
import { siteRoutes } from "./routes/site.js";
|
||||||
import { registerModules } from "./modules/index.js";
|
import { registerModules } from "./modules/index.js";
|
||||||
import { snapshotRoutes } from "./routes/snapshots.js";
|
import { snapshotRoutes } from "./routes/snapshots.js";
|
||||||
|
import { cameraRoutes, liveResolverFor } from "./routes/cameras.js";
|
||||||
|
import { CameraActivity } from "./camera-activity.js";
|
||||||
|
import { CameraLiveHub } from "./camera-live.js";
|
||||||
import { tariffRoutes } from "./routes/tariffs.js";
|
import { tariffRoutes } from "./routes/tariffs.js";
|
||||||
import { printerRoutes } from "./routes/printers.js";
|
import { printerRoutes } from "./routes/printers.js";
|
||||||
import { setupRoutes } from "./routes/setup.js";
|
import { setupRoutes } from "./routes/setup.js";
|
||||||
@@ -82,6 +85,25 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
formatters: { level: (label) => ({ level: label }) },
|
formatters: { level: (label) => ({ level: label }) },
|
||||||
stream: pinoDbStream(logService, process.stdout),
|
stream: pinoDbStream(logService, process.stdout),
|
||||||
},
|
},
|
||||||
|
// ONE line per request (the onResponse hook below) instead of Fastify's default
|
||||||
|
// "incoming request" + "request completed" pair — on a quiet booth the pair was
|
||||||
|
// most of the log. NB: with this flag Fastify's default error handler ALSO stops
|
||||||
|
// logging handler errors, so the onError hook below re-adds that for 5xx.
|
||||||
|
disableRequestLogging: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Request log, one line: method, url, status, elapsed. Routes declared with
|
||||||
|
// `logLevel: "silent"` (the /health probe) are skipped because `req.log` is theirs.
|
||||||
|
app.addHook("onResponse", async (req, reply) => {
|
||||||
|
req.log.info(`${req.method} ${req.url} → ${reply.statusCode} ${Math.round(reply.elapsedTime)}ms`);
|
||||||
|
});
|
||||||
|
// Handler failures (5xx) keep their stack in the log — disableRequestLogging would
|
||||||
|
// otherwise swallow them (fastify/lib/error-handler.js checks the same flag).
|
||||||
|
app.addHook("onError", async (req, _reply, err) => {
|
||||||
|
// onError runs BEFORE the error handler sets the reply status, so the reply still
|
||||||
|
// says 200 here; an error without its own statusCode is a 500 by definition.
|
||||||
|
const code = (err as { statusCode?: number }).statusCode ?? 500;
|
||||||
|
if (code >= 500) req.log.error({ err }, `${req.method} ${req.url} failed: ${err.message}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
|
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
|
||||||
@@ -109,7 +131,9 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
// Unauthenticated liveness probe. `app` lets a client (the desktop ConnectScreen
|
// Unauthenticated liveness probe. `app` lets a client (the desktop ConnectScreen
|
||||||
// test — apps/web/src/lib/backend-config.ts) tell THIS server apart from any
|
// test — apps/web/src/lib/backend-config.ts) tell THIS server apart from any
|
||||||
// other service that happens to answer on the address the operator typed.
|
// other service that happens to answer on the address the operator typed.
|
||||||
app.get("/health", async () => ({ status: "ok", app: "parking-system" }));
|
// `logLevel: "silent"`: Docker's HEALTHCHECK hits this every 30 s; logging each
|
||||||
|
// probe was half of a quiet booth's output (park-2, 2026-10-08).
|
||||||
|
app.get("/health", { logLevel: "silent" }, async () => ({ status: "ok", app: "parking-system" }));
|
||||||
|
|
||||||
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
||||||
await authRoutes(app, db);
|
await authRoutes(app, db);
|
||||||
@@ -155,6 +179,14 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
const laneStatus = new LaneStatus(db, app.log);
|
const laneStatus = new LaneStatus(db, app.log);
|
||||||
app.addHook("onClose", async () => laneStatus.stop());
|
app.addHook("onClose", async () => laneStatus.stop());
|
||||||
|
|
||||||
|
// Per-CAMERA vehicle activity (same pushes, keyed by camera) + the live-video hub for
|
||||||
|
// the booth camera tiles: a tile goes live while its camera sees a vehicle. Advisory
|
||||||
|
// viewing only. See camera-live.ts, wiki/decisions/camera-live-view.md.
|
||||||
|
const cameraActivity = new CameraActivity(app.log);
|
||||||
|
app.addHook("onClose", async () => cameraActivity.stop());
|
||||||
|
const cameraLive = new CameraLiveHub(liveResolverFor(db), app.log);
|
||||||
|
app.addHook("onClose", async () => cameraLive.stopAll());
|
||||||
|
|
||||||
// Per-lane RADAR presence (presence-input edges → barrier-light blink). Mirrors the
|
// Per-lane RADAR presence (presence-input edges → barrier-light blink). Mirrors the
|
||||||
// physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI.
|
// physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI.
|
||||||
const lanePresence = new LanePresence(db, app.log);
|
const lanePresence = new LanePresence(db, app.log);
|
||||||
@@ -195,10 +227,11 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
|
|
||||||
// Live booth feed: server-pushed ledger + occupancy + printer-status over a
|
// Live booth feed: server-pushed ledger + occupancy + printer-status over a
|
||||||
// single authenticated WebSocket (/api/ws). See routes/ws.ts.
|
// single authenticated WebSocket (/api/ws). See routes/ws.ts.
|
||||||
await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence);
|
await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence, cameraActivity);
|
||||||
|
|
||||||
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
|
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
|
||||||
await snapshotRoutes(app, db);
|
await snapshotRoutes(app, db);
|
||||||
|
await cameraRoutes(app, db, cameraLive);
|
||||||
|
|
||||||
// Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen.
|
// Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen.
|
||||||
// Subscribes to the SAME input bus as the telemetry writer below; the two are
|
// Subscribes to the SAME input bus as the telemetry writer below; the two are
|
||||||
@@ -249,7 +282,7 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
// each detected target (vehicle). Source-IP guarded + optional Digest; records the raw
|
// each detected target (vehicle). Source-IP guarded + optional Digest; records the raw
|
||||||
// payload as a `kind:"alarm"` device_event, drives lane busy/free, AND hands a vehicle
|
// payload as a `kind:"alarm"` device_event, drives lane busy/free, AND hands a vehicle
|
||||||
// detection to the ANPR bridge above. See routes/hikvision-alarm.ts.
|
// detection to the ANPR bridge above. See routes/hikvision-alarm.ts.
|
||||||
await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge);
|
await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge, cameraActivity);
|
||||||
|
|
||||||
// Credential capture ("enroll a card"): lets the operator present an RFID card to a
|
// Credential capture ("enroll a card"): lets the operator present an RFID card to a
|
||||||
// CHOSEN reader to populate a subscription credential, without blocking the other
|
// CHOSEN reader to populate a subscription credential, without blocking the other
|
||||||
|
|||||||
@@ -34,12 +34,14 @@ afterEach(() => close());
|
|||||||
/** Append a signed payment with source-split flags, as the booth/pay paths do. */
|
/** Append a signed payment with source-split flags, as the booth/pay paths do. */
|
||||||
async function payment(
|
async function payment(
|
||||||
amountMinor: number,
|
amountMinor: number,
|
||||||
opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean } = {},
|
opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean; forgoneMinor?: number } = {},
|
||||||
) {
|
) {
|
||||||
await log.append({
|
await log.append({
|
||||||
type: "payment", source: "manual", identity: "T",
|
type: "payment", source: "manual", identity: "T",
|
||||||
payload: {
|
payload: {
|
||||||
sessionRef: "T", amountMinor, currency: "ALL", tender: opts.tender ?? "cash",
|
sessionRef: "T", amountMinor, currency: "ALL",
|
||||||
|
// A forgiven exit's $0 payment carries no tender (nothing was tendered).
|
||||||
|
...(opts.forgoneMinor != null ? { forgoneMinor: opts.forgoneMinor } : { tender: opts.tender ?? "cash" }),
|
||||||
...(opts.subscriptionSale ? { subscriptionSale: true } : {}),
|
...(opts.subscriptionSale ? { subscriptionSale: true } : {}),
|
||||||
...(opts.subscriptionWindowCharge ? { subscriptionWindowCharge: true } : {}),
|
...(opts.subscriptionWindowCharge ? { subscriptionWindowCharge: true } : {}),
|
||||||
},
|
},
|
||||||
@@ -74,6 +76,29 @@ describe("single-open invariant", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("forgiven exits on the Z-report", () => {
|
||||||
|
it("a $0 forgiven payment adds nothing to cash/card/drawer and is reported as its own line", async () => {
|
||||||
|
await shift.open("alice");
|
||||||
|
await payment(10000); // a real ticket, cash
|
||||||
|
await payment(0, { forgoneMinor: 25000 });
|
||||||
|
await payment(0, { forgoneMinor: 5000 });
|
||||||
|
|
||||||
|
const r = shift.currentReport()!;
|
||||||
|
expect(r.cashTotalMinor).toBe(10000);
|
||||||
|
expect(r.cardTotalMinor).toBe(0);
|
||||||
|
expect(r.ticketTotalMinor).toBe(10000);
|
||||||
|
expect(r.forgoneTotalMinor).toBe(30000);
|
||||||
|
expect(r.forgoneCount).toBe(2);
|
||||||
|
expect(r.discountTotalMinor).toBe(0); // not a merchant validation
|
||||||
|
expect(r.expectedDrawerMinor).toBe(r.openingFloatMinor + 10000);
|
||||||
|
|
||||||
|
const closed = await shift.close("alice");
|
||||||
|
expect(closed).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2, cashTotalMinor: 10000 });
|
||||||
|
const hist = shift.listShifts();
|
||||||
|
expect(hist[0]).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("takings split by source", () => {
|
describe("takings split by source", () => {
|
||||||
it("separates subscription sales, out-of-window charges, and transient tickets", async () => {
|
it("separates subscription sales, out-of-window charges, and transient tickets", async () => {
|
||||||
await shift.open("alice");
|
await shift.open("alice");
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ export interface ShiftSummary {
|
|||||||
readonly subscriptionSalesMinor: number;
|
readonly subscriptionSalesMinor: number;
|
||||||
readonly subscriptionWindowMinor: number;
|
readonly subscriptionWindowMinor: number;
|
||||||
readonly discountTotalMinor: number;
|
readonly discountTotalMinor: number;
|
||||||
|
readonly forgoneTotalMinor: number;
|
||||||
|
readonly forgoneCount: number;
|
||||||
readonly chargesByModuleMinor: ChargesByModule;
|
readonly chargesByModuleMinor: ChargesByModule;
|
||||||
readonly openingFloatMinor: number;
|
readonly openingFloatMinor: number;
|
||||||
readonly cashAddedMinor: number;
|
readonly cashAddedMinor: number;
|
||||||
@@ -105,6 +107,10 @@ export interface ShiftReport {
|
|||||||
/** Merchant-validation DISCOUNT total given away in the window (leakage — the
|
/** Merchant-validation DISCOUNT total given away in the window (leakage — the
|
||||||
* cash/card figures above are already NET of it). See validation-discounts.md. */
|
* cash/card figures above are already NET of it). See validation-discounts.md. */
|
||||||
readonly discountTotalMinor: number;
|
readonly discountTotalMinor: number;
|
||||||
|
/** FORGIVEN exits (wiki/decisions/forgiven-exit.md): fees waived by an operator holding
|
||||||
|
* barrier:create, and how many. $0 payments — never inside cash/card; its own line. */
|
||||||
|
readonly forgoneTotalMinor: number;
|
||||||
|
readonly forgoneCount: number;
|
||||||
/** Module charges settled on this till's payments (a booth-paid wash), by module. */
|
/** Module charges settled on this till's payments (a booth-paid wash), by module. */
|
||||||
readonly chargesByModuleMinor: ChargesByModule;
|
readonly chargesByModuleMinor: ChargesByModule;
|
||||||
// --- Drawer (physical cash till; carries across shifts) ---
|
// --- Drawer (physical cash till; carries across shifts) ---
|
||||||
@@ -266,6 +272,8 @@ export class ShiftService {
|
|||||||
subscriptionSalesMinor?: number;
|
subscriptionSalesMinor?: number;
|
||||||
subscriptionWindowMinor?: number;
|
subscriptionWindowMinor?: number;
|
||||||
discountTotalMinor?: number;
|
discountTotalMinor?: number;
|
||||||
|
forgoneTotalMinor?: number;
|
||||||
|
forgoneCount?: number;
|
||||||
chargesByModuleMinor?: ChargesByModule;
|
chargesByModuleMinor?: ChargesByModule;
|
||||||
openingFloatMinor?: number;
|
openingFloatMinor?: number;
|
||||||
cashAddedMinor?: number;
|
cashAddedMinor?: number;
|
||||||
@@ -302,6 +310,9 @@ export class ShiftService {
|
|||||||
(pl.cashTotalMinor ?? 0) + (pl.cardTotalMinor ?? 0) - (pl.subscriptionTotalMinor ?? 0),
|
(pl.cashTotalMinor ?? 0) + (pl.cardTotalMinor ?? 0) - (pl.subscriptionTotalMinor ?? 0),
|
||||||
// Merchant-validation leakage (added 2026-07-13). Old reports lack it → 0.
|
// Merchant-validation leakage (added 2026-07-13). Old reports lack it → 0.
|
||||||
discountTotalMinor: pl.discountTotalMinor ?? 0,
|
discountTotalMinor: pl.discountTotalMinor ?? 0,
|
||||||
|
// Forgiven exits (added 2026-10-08). Old reports lack it → 0.
|
||||||
|
forgoneTotalMinor: pl.forgoneTotalMinor ?? 0,
|
||||||
|
forgoneCount: pl.forgoneCount ?? 0,
|
||||||
// Module charges on the ticket (added 2026-09-06). Old reports lack it → none.
|
// Module charges on the ticket (added 2026-09-06). Old reports lack it → none.
|
||||||
chargesByModuleMinor: pl.chargesByModuleMinor ?? {},
|
chargesByModuleMinor: pl.chargesByModuleMinor ?? {},
|
||||||
openingFloatMinor: pl.openingFloatMinor ?? 0,
|
openingFloatMinor: pl.openingFloatMinor ?? 0,
|
||||||
@@ -599,6 +610,10 @@ export class ShiftService {
|
|||||||
// Merchant-validation leakage: Σ discountMinor across the window's payments. The
|
// Merchant-validation leakage: Σ discountMinor across the window's payments. The
|
||||||
// tender totals are already NET; this is the "given away" figure beside them.
|
// tender totals are already NET; this is the "given away" figure beside them.
|
||||||
let discountTotalMinor = 0;
|
let discountTotalMinor = 0;
|
||||||
|
// Forgiven exits: $0 payments whose `forgoneMinor` is the fee waived. Not money —
|
||||||
|
// the tender sums above add 0 for them; this is the "let out for free" figure.
|
||||||
|
let forgoneTotalMinor = 0;
|
||||||
|
let forgoneCount = 0;
|
||||||
// Module charges folded into this till's payments (chargeLines on a booth payment),
|
// Module charges folded into this till's payments (chargeLines on a booth payment),
|
||||||
// summed by owning module. Part of cash/card; NOT ticket money.
|
// summed by owning module. Part of cash/card; NOT ticket money.
|
||||||
const chargesByModuleMinor: ChargesByModule = {};
|
const chargesByModuleMinor: ChargesByModule = {};
|
||||||
@@ -617,6 +632,10 @@ export class ShiftService {
|
|||||||
else if (pl.subscriptionWindowCharge === true) subscriptionWindowMinor += amt;
|
else if (pl.subscriptionWindowCharge === true) subscriptionWindowMinor += amt;
|
||||||
// (else → transient ticket; derived below as total − subscription)
|
// (else → transient ticket; derived below as total − subscription)
|
||||||
if (typeof pl.discountMinor === "number") discountTotalMinor += pl.discountMinor;
|
if (typeof pl.discountMinor === "number") discountTotalMinor += pl.discountMinor;
|
||||||
|
if (typeof pl.forgoneMinor === "number") {
|
||||||
|
forgoneTotalMinor += pl.forgoneMinor;
|
||||||
|
forgoneCount += 1;
|
||||||
|
}
|
||||||
for (const l of pl.chargeLines ?? []) {
|
for (const l of pl.chargeLines ?? []) {
|
||||||
if (typeof l.amountMinor !== "number" || !l.module) continue;
|
if (typeof l.amountMinor !== "number" || !l.module) continue;
|
||||||
chargesByModuleMinor[l.module] = (chargesByModuleMinor[l.module] ?? 0) + l.amountMinor;
|
chargesByModuleMinor[l.module] = (chargesByModuleMinor[l.module] ?? 0) + l.amountMinor;
|
||||||
@@ -682,6 +701,8 @@ export class ShiftService {
|
|||||||
subscriptionSalesMinor,
|
subscriptionSalesMinor,
|
||||||
subscriptionWindowMinor,
|
subscriptionWindowMinor,
|
||||||
discountTotalMinor,
|
discountTotalMinor,
|
||||||
|
forgoneTotalMinor,
|
||||||
|
forgoneCount,
|
||||||
chargesByModuleMinor,
|
chargesByModuleMinor,
|
||||||
openingFloatMinor,
|
openingFloatMinor,
|
||||||
cashAddedMinor,
|
cashAddedMinor,
|
||||||
@@ -723,6 +744,8 @@ export class ShiftService {
|
|||||||
subscriptionSalesMinor,
|
subscriptionSalesMinor,
|
||||||
subscriptionWindowMinor,
|
subscriptionWindowMinor,
|
||||||
discountTotalMinor,
|
discountTotalMinor,
|
||||||
|
forgoneTotalMinor,
|
||||||
|
forgoneCount,
|
||||||
chargesByModuleMinor,
|
chargesByModuleMinor,
|
||||||
openingFloatMinor,
|
openingFloatMinor,
|
||||||
cashAddedMinor,
|
cashAddedMinor,
|
||||||
@@ -748,6 +771,8 @@ export class ShiftService {
|
|||||||
subscriptionSalesMinor,
|
subscriptionSalesMinor,
|
||||||
subscriptionWindowMinor,
|
subscriptionWindowMinor,
|
||||||
discountTotalMinor,
|
discountTotalMinor,
|
||||||
|
// Forgiven exits — only when any happened (older payloads stay identical).
|
||||||
|
...(forgoneCount > 0 ? { forgoneTotalMinor, forgoneCount } : {}),
|
||||||
// Only when a module charged in the window (older slips/payloads stay identical).
|
// Only when a module charged in the window (older slips/payloads stay identical).
|
||||||
...(Object.keys(chargesByModuleMinor).length ? { chargesByModuleMinor } : {}),
|
...(Object.keys(chargesByModuleMinor).length ? { chargesByModuleMinor } : {}),
|
||||||
openingFloatMinor,
|
openingFloatMinor,
|
||||||
@@ -806,6 +831,8 @@ export class ShiftService {
|
|||||||
// Merchant-validation leakage — printed only when the shift actually gave any
|
// Merchant-validation leakage — printed only when the shift actually gave any
|
||||||
// (older slips stay byte-identical). The takings above are already NET of it.
|
// (older slips stay byte-identical). The takings above are already NET of it.
|
||||||
...(r.discountTotalMinor > 0 ? [`Zbritje (validime): ${money(r.discountTotalMinor)} ${cur}`] : []),
|
...(r.discountTotalMinor > 0 ? [`Zbritje (validime): ${money(r.discountTotalMinor)} ${cur}`] : []),
|
||||||
|
// Forgiven exits — fees waived by an operator; $0 payments, NOT in the takings.
|
||||||
|
...(r.forgoneCount > 0 ? [`Dalje manuale (${r.forgoneCount}): ${money(r.forgoneTotalMinor)} ${cur}`] : []),
|
||||||
"",
|
"",
|
||||||
"-- Arka --",
|
"-- Arka --",
|
||||||
`Gjëndje fillestare: ${money(r.openingFloatMinor)} ${cur}`,
|
`Gjëndje fillestare: ${money(r.openingFloatMinor)} ${cur}`,
|
||||||
|
|||||||
+25
-12
@@ -2,12 +2,12 @@ import { randomUUID } from "node:crypto";
|
|||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
|
import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
|
||||||
import { registry, type CameraDevice, type Snapshot } from "@parking/devices";
|
import { registry, type CameraDevice, type Snapshot } from "@parking/devices";
|
||||||
import { reasonPayload } from "@parking/shared";
|
import { reasonPayload, type NormBox } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
||||||
import { deviceEvents } from "./device-events.js";
|
import { deviceEvents } from "./device-events.js";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
import type { VisionClient } from "./vision-client.js";
|
import type { VisionClient, VisionResult } from "./vision-client.js";
|
||||||
|
|
||||||
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
|
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
|
||||||
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
|
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
|
||||||
@@ -171,23 +171,16 @@ async function recognizePlate(
|
|||||||
// Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a
|
// Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a
|
||||||
// downscaled copy — see reencodeForStorage), so the wash's review crop can cut the
|
// downscaled copy — see reencodeForStorage), so the wash's review crop can cut the
|
||||||
// vehicle out of whatever copy survives and blur the plate inside it.
|
// vehicle out of whatever copy survives and blur the plate inside it.
|
||||||
const frame = await frameSize(shot.bytes);
|
const boxes = await normalizedBoxes(shot.bytes, result);
|
||||||
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined) =>
|
|
||||||
b && frame
|
|
||||||
? {
|
|
||||||
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
|
|
||||||
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
|
|
||||||
}
|
|
||||||
: null;
|
|
||||||
// The vehicle's body type (advisory; the wash desk's category suggestion — see
|
// The vehicle's body type (advisory; the wash desk's category suggestion — see
|
||||||
// venue-modules.md §Vehicle category). Rides the plate's read row when there is one,
|
// venue-modules.md §Vehicle category). Rides the plate's read row when there is one,
|
||||||
// else a row of its own: a car with an unreadable plate is still a car of some class.
|
// else a row of its own: a car with an unreadable plate is still a car of some class.
|
||||||
const vehicleBox = norm(result.vehicle?.bbox);
|
const vehicleBox = boxes.vehicleBox;
|
||||||
const vehicle = result.vehicle
|
const vehicle = result.vehicle
|
||||||
? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) }
|
? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) }
|
||||||
: {};
|
: {};
|
||||||
const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase();
|
const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase();
|
||||||
const plateBox = plate ? norm(result.plate?.bbox) : null;
|
const plateBox = plate ? boxes.plateBox : null;
|
||||||
if (!plate && !result.vehicle) return; // nothing trustworthy to record
|
if (!plate && !result.vehicle) return; // nothing trustworthy to record
|
||||||
db.insert(deviceEventsTable)
|
db.insert(deviceEventsTable)
|
||||||
.values({
|
.values({
|
||||||
@@ -216,6 +209,7 @@ async function recognizePlate(
|
|||||||
deviceEvents.emitVehicleRead({
|
deviceEvents.emitVehicleRead({
|
||||||
identity,
|
identity,
|
||||||
direction,
|
direction,
|
||||||
|
deviceId,
|
||||||
read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox },
|
read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -241,6 +235,25 @@ function clamp01(v: number): number {
|
|||||||
return Math.max(0, Math.min(1, v));
|
return Math.max(0, Math.min(1, v));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The vehicle's and the plate's boxes as FRACTIONS of the analysed frame (null when the
|
||||||
|
* stage found none or the frame size is unreadable). Fractions, so the box fits the
|
||||||
|
* downscaled stored copy the wash's review crop is cut from. Shared by the session-tied
|
||||||
|
* recognition above and the ANPR bridge's per-car pass sample (anpr-entry.ts). */
|
||||||
|
export async function normalizedBoxes(
|
||||||
|
bytes: Buffer,
|
||||||
|
result: VisionResult,
|
||||||
|
): Promise<{ vehicleBox: NormBox | null; plateBox: NormBox | null }> {
|
||||||
|
const frame = await frameSize(bytes);
|
||||||
|
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined): NormBox | null =>
|
||||||
|
b && frame
|
||||||
|
? {
|
||||||
|
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
|
||||||
|
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
return { vehicleBox: norm(result.vehicle?.bbox), plateBox: norm(result.plate?.bbox) };
|
||||||
|
}
|
||||||
|
|
||||||
/** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */
|
/** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */
|
||||||
async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {
|
async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||||
import { reasonPayload, type PlanTimeframes, type ReasonCode } from "@parking/shared";
|
import { reasonPayload, type PlanTimeframes, type ReasonCode } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { pulseBarrier } from "./relay-pulse.js";
|
||||||
import { printWindowChargeNotice } from "./booth-print.js";
|
import { printWindowChargeNotice } from "./booth-print.js";
|
||||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
@@ -211,8 +212,9 @@ export class SubscriptionFlow {
|
|||||||
// `permitId` carries the subscription id; `via` records which credential left.
|
// `permitId` carries the subscription id; `via` records which credential left.
|
||||||
payload: { sessionRef: occurrenceId, permitId: m.subscriptionId, via: m.via },
|
payload: { sessionRef: occurrenceId, permitId: m.subscriptionId, via: m.via },
|
||||||
});
|
});
|
||||||
await this.#open(resolved, "exit", occurrenceId, "subscription exit");
|
// Cache close before the pulse, for the same reason as the entry-side insert.
|
||||||
this.#closeCache(occurrenceId);
|
this.#closeCache(occurrenceId);
|
||||||
|
await this.#open(resolved, "exit", occurrenceId, "subscription exit");
|
||||||
return { accepted: true, direction: "exit" };
|
return { accepted: true, direction: "exit" };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +270,9 @@ export class SubscriptionFlow {
|
|||||||
`subscription out-of-window entry marked on ${occurrenceId} (charge priced from parked minutes at exit)`,
|
`subscription out-of-window entry marked on ${occurrenceId} (charge priced from parked minutes at exit)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
await this.#open(resolved, "entry", occurrenceId, "subscription entry");
|
// Session cache BEFORE the pulse: the entry is already signed, so the projection must
|
||||||
|
// reflect it even if the relay call throws (otherwise the ledger and the sessions
|
||||||
|
// table disagree about the same read — seen at park-2, 2026-10-24).
|
||||||
try {
|
try {
|
||||||
this.#db
|
this.#db
|
||||||
.insert(sessions)
|
.insert(sessions)
|
||||||
@@ -284,6 +288,7 @@ export class SubscriptionFlow {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.#logger.error(`session-cache insert failed for ${occurrenceId}: ${(err as Error).message}`);
|
this.#logger.error(`session-cache insert failed for ${occurrenceId}: ${(err as Error).message}`);
|
||||||
}
|
}
|
||||||
|
await this.#open(resolved, "entry", occurrenceId, "subscription entry");
|
||||||
// BEST-EFFORT: print the out-of-window TICKET so the subscriber has the paper the
|
// BEST-EFFORT: print the out-of-window TICKET so the subscriber has the paper the
|
||||||
// operator scans to settle at the booth. It carries the occurrence id as a scannable
|
// operator scans to settle at the booth. It carries the occurrence id as a scannable
|
||||||
// code; the amount is computed at settlement from the minutes actually parked
|
// code; the amount is computed at settlement from the minutes actually parked
|
||||||
@@ -409,12 +414,16 @@ export class SubscriptionFlow {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
||||||
const access = this.#buildAccess(resolved.controller);
|
// SNAPSHOT FIRST — fire the directional camera(s), never awaited (evidence, not a
|
||||||
if (access) await access.pulseOpen(resolved.relay);
|
// gate). Before the pulse, so a pulse failure (the pulse helper rethrows) still leaves
|
||||||
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
// an image for the signed event: at park-2 four signed entries had no snapshot because
|
||||||
|
// the relay timed out and this method unwound before reaching the camera (2026-10-24).
|
||||||
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
|
|
||||||
this.#fireSnapshot(dir, carKey);
|
this.#fireSnapshot(dir, carKey);
|
||||||
|
|
||||||
|
const access = this.#buildAccess(resolved.controller);
|
||||||
|
if (access) {
|
||||||
|
await pulseBarrier(this.#db, this.#logger, access, resolved, { direction: dir, identity: carKey, source: "subscription" });
|
||||||
|
} else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
||||||
}
|
}
|
||||||
|
|
||||||
#closeCache(carKey: string): void {
|
#closeCache(carKey: string): void {
|
||||||
|
|||||||
@@ -21,6 +21,16 @@ export interface AppliedValidation extends SessionValidation {
|
|||||||
readonly consumedBy: string | null;
|
readonly consumedBy: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The ledger columns the validation fold reads. Any identity-scoped, index-ordered
|
||||||
|
* slice of `ledger_events` satisfies it (a direct query, or the per-identity group of a
|
||||||
|
* whole-ledger scan — see PayStation.activeSessions). */
|
||||||
|
export interface LedgerRowLike {
|
||||||
|
readonly id: string;
|
||||||
|
readonly type: string;
|
||||||
|
readonly occurredAt: string;
|
||||||
|
readonly payload: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
/** All validations ever applied to a session (newest last), with voided/consumed
|
/** All validations ever applied to a session (newest last), with voided/consumed
|
||||||
* state folded from the chain. One identity-scoped ledger scan. */
|
* state folded from the chain. One identity-scoped ledger scan. */
|
||||||
export function sessionValidations(db: Db, identity: string): AppliedValidation[] {
|
export function sessionValidations(db: Db, identity: string): AppliedValidation[] {
|
||||||
@@ -35,7 +45,13 @@ export function sessionValidations(db: Db, identity: string): AppliedValidation[
|
|||||||
.where(eq(ledgerEvents.identity, identity))
|
.where(eq(ledgerEvents.identity, identity))
|
||||||
.orderBy(ledgerEvents.index)
|
.orderBy(ledgerEvents.index)
|
||||||
.all();
|
.all();
|
||||||
|
return sessionValidationsFromRows(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same fold over rows the caller already holds (identity-scoped, oldest first). Lets a
|
||||||
|
* list view price hundreds of sessions from ONE ledger scan instead of one per row —
|
||||||
|
* the per-row scans were what froze the booth server (park-2, 2026-10-24). */
|
||||||
|
export function sessionValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] {
|
||||||
const voided = new Set<string>();
|
const voided = new Set<string>();
|
||||||
const consumedBy = new Map<string, string>();
|
const consumedBy = new Map<string, string>();
|
||||||
const applies: AppliedValidation[] = [];
|
const applies: AppliedValidation[] = [];
|
||||||
@@ -88,6 +104,11 @@ export function liveValidations(db: Db, identity: string): AppliedValidation[] {
|
|||||||
return sessionValidations(db, identity).filter((v) => !v.voided && v.consumedBy == null);
|
return sessionValidations(db, identity).filter((v) => !v.voided && v.consumedBy == null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `liveValidations` over rows the caller already holds (see sessionValidationsFromRows). */
|
||||||
|
export function liveValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] {
|
||||||
|
return sessionValidationsFromRows(rows).filter((v) => !v.voided && v.consumedBy == null);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Apply (shared by the merchant route and the Car Wash module) ----------------
|
// --- Apply (shared by the merchant route and the Car Wash module) ----------------
|
||||||
|
|
||||||
export interface ApplyValidationInput {
|
export interface ApplyValidationInput {
|
||||||
|
|||||||
+13
-7
@@ -1,9 +1,11 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
# Parking TRAINER image: the phase-B body-type classifier job. Build CONTEXT is apps/trainer
|
# Parking TRAINER image: the phase-B body-type classifier. Build CONTEXT is apps/trainer
|
||||||
# (self-contained Python package). A ONE-OFF JOB on the reviewer's host (art-docker-station),
|
# (self-contained Python package). Runs on the reviewer's host (art-docker-station) beside
|
||||||
# never a booth service: it reads the wash collector's volume (collector.sqlite + crops/)
|
# the collector, never on a booth: by default it SERVES the job API the collector's Training
|
||||||
# and writes a versioned model folder. CPU-only PyTorch — the host has no usable GPU and a
|
# section drives (`serve`); the same image runs the CLI one-off (`train`, `inspect`, …). It
|
||||||
# few thousand crops train in minutes/an hour on four Xeon cores.
|
# reads the wash collector's volume (collector.sqlite + crops/) and writes versioned model
|
||||||
|
# folders. CPU-only PyTorch — the host has no usable GPU and a few thousand crops train in
|
||||||
|
# minutes/an hour on four Xeon cores.
|
||||||
# See wiki/decisions/bodytype-classifier-training.md.
|
# See wiki/decisions/bodytype-classifier-training.md.
|
||||||
|
|
||||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS base
|
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS base
|
||||||
@@ -37,7 +39,11 @@ RUN useradd --system --create-home --uid 999 trainer \
|
|||||||
USER trainer
|
USER trainer
|
||||||
|
|
||||||
ENV TRAINER_DATA_DIR=/data \
|
ENV TRAINER_DATA_DIR=/data \
|
||||||
TRAINER_OUT_DIR=/out
|
TRAINER_OUT_DIR=/out \
|
||||||
|
TRAINER_PORT=8091
|
||||||
VOLUME ["/out"]
|
VOLUME ["/out"]
|
||||||
|
EXPOSE 8091
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8091/health').status==200 else 1)" || exit 1
|
||||||
ENTRYPOINT ["uv", "run", "--no-sync", "parking-trainer"]
|
ENTRYPOINT ["uv", "run", "--no-sync", "parking-trainer"]
|
||||||
CMD ["inspect"]
|
CMD ["serve"]
|
||||||
|
|||||||
@@ -25,12 +25,12 @@ A passing run writes `<out>/<version>/`:
|
|||||||
| `report.md` | the human report: accuracy, per-class recall/precision, confusion matrix, dropped classes, loss weights |
|
| `report.md` | the human report: accuracy, per-class recall/precision, confusion matrix, dropped classes, loss weights |
|
||||||
| `metrics.json` | the same numbers, machine-readable |
|
| `metrics.json` | the same numbers, machine-readable |
|
||||||
|
|
||||||
On the reviewer's host (the `wash-collector` stack):
|
On the reviewer's host the image runs `serve` as the `trainer` service of the
|
||||||
|
`wash-collector` stack: a job API (`/health`, `/readiness`, `/versions`, `/jobs`) on the compose
|
||||||
```
|
network that the collector's **Training section** (`/review`) drives — readiness, Train /
|
||||||
docker compose -f docker-compose.collector.yml --profile train run --rm trainer inspect
|
Evaluate / Publish, reports and logs. Jobs run as subprocesses of the CLI, one at a time; state
|
||||||
docker compose -f docker-compose.collector.yml --profile train run --rm trainer train --min-accuracy 0.85
|
and logs persist under `/out/jobs/`. The CLI stays for debugging:
|
||||||
```
|
`docker compose -f docker-compose.collector.yml exec trainer parking-trainer inspect`.
|
||||||
|
|
||||||
Local dev: `uv sync --extra train` (CPU torch, ~200 MB), `uv run pytest -q`. The test suite
|
Local dev: `uv sync --extra train` (CPU torch, ~200 MB), `uv run pytest -q`. The test suite
|
||||||
runs without the extra (torch tests skip), matching CI.
|
runs without the extra (torch tests skip), matching CI.
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""The job API: readiness, one job at a time, subprocess jobs with persisted logs, versions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from http.server import ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from trainer.server import Handler, Jobs, readiness, versions, wait_idle
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def api(collector_dir: Path, tmp_path: Path): # type: ignore[no-untyped-def]
|
||||||
|
out = tmp_path / "out"
|
||||||
|
Handler.jobs = Jobs(collector_dir, out, "https://example.invalid/pkg", "tok")
|
||||||
|
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||||
|
t = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||||
|
t.start()
|
||||||
|
base = f"http://127.0.0.1:{httpd.server_address[1]}"
|
||||||
|
|
||||||
|
def call(method: str, path: str, body: dict | None = None): # type: ignore[no-untyped-def]
|
||||||
|
req = urllib.request.Request(base + path, method=method)
|
||||||
|
data = None
|
||||||
|
if body is not None:
|
||||||
|
data = json.dumps(body).encode()
|
||||||
|
req.add_header("Content-Type", "application/json")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, data=data, timeout=10) as r:
|
||||||
|
raw = r.read()
|
||||||
|
return r.status, (
|
||||||
|
json.loads(raw) if r.headers.get_content_type() == "application/json" else raw.decode()
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return e.code, json.loads(e.read() or b"{}")
|
||||||
|
|
||||||
|
yield call, out
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_readiness_and_empty_versions(api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
call, _ = api
|
||||||
|
code, r = call("GET", "/readiness")
|
||||||
|
assert code == 200 and r["ready"] is True and r["run"]["classes"] == ["sedan", "suv", "van"]
|
||||||
|
assert r["defaults"]["minAccuracy"] == 0.85 and "finetune" in r["modes"]
|
||||||
|
assert call("GET", "/versions") == (200, {"versions": []})
|
||||||
|
assert call("GET", "/health")[1]["busy"] is False
|
||||||
|
assert readiness(Path("/nonexistent"))["ready"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_job_runs_as_a_subprocess_and_is_recorded(api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
call, out = api
|
||||||
|
code, job = call("POST", "/jobs", {"kind": "evaluate", "version": "nope"})
|
||||||
|
assert code == 202 and job["status"] == "running" and job["kind"] == "evaluate"
|
||||||
|
wait_idle(Handler.jobs)
|
||||||
|
code, j = call("GET", f"/jobs/{job['id']}")
|
||||||
|
assert code == 200 and j["status"] == "failed" and j["exitCode"] == 1
|
||||||
|
assert "evaluate --data" in j["log"] and "nope" in j["log"]
|
||||||
|
assert (out / "jobs" / f"{job['id']}.json").is_file() and (out / "jobs" / f"{job['id']}.log").is_file()
|
||||||
|
code, lst = call("GET", "/jobs")
|
||||||
|
assert code == 200 and lst["jobs"][0]["id"] == job["id"] and lst["current"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_requests(api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
call, _ = api
|
||||||
|
assert call("POST", "/jobs", {"kind": "nuke"})[0] == 400
|
||||||
|
assert call("POST", "/jobs", {"kind": "train", "mode": "magic"})[0] == 400
|
||||||
|
assert call("POST", "/jobs", {"kind": "evaluate", "version": "../etc"})[0] == 400
|
||||||
|
assert call("POST", "/jobs", {"kind": "publish", "version": "v1", "url": "ftp://x"})[0] == 400
|
||||||
|
assert call("GET", "/versions/../x/report")[0] == 400
|
||||||
|
assert call("GET", "/versions/v9/report")[0] == 404
|
||||||
|
assert call("GET", "/jobs/nope")[0] == 404
|
||||||
|
assert call("GET", "/nothing")[0] == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_train_job_then_versions_and_report(api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
pytest.importorskip("torch")
|
||||||
|
call, out = api
|
||||||
|
body = {"kind": "train", "mode": "features", "minAccuracy": 0.0, "epochs": 100, "version": "vapi"}
|
||||||
|
# The test-only flags are not offered by the API; inject them via the CLI args the runner builds.
|
||||||
|
orig = Jobs._argv
|
||||||
|
|
||||||
|
def patched(self, kind, a): # type: ignore[no-untyped-def]
|
||||||
|
argv = orig(self, kind, a)
|
||||||
|
return argv + ["--no-pretrained", "--input-size", "64", "--no-cache"] if kind == "train" else argv
|
||||||
|
|
||||||
|
Jobs._argv = patched # type: ignore[method-assign]
|
||||||
|
try:
|
||||||
|
code, job = call("POST", "/jobs", body)
|
||||||
|
assert code == 202
|
||||||
|
assert call("POST", "/jobs", {"kind": "evaluate", "version": "vapi"})[0] == 409 # one at a time
|
||||||
|
wait_idle(Handler.jobs, 120)
|
||||||
|
finally:
|
||||||
|
Jobs._argv = orig # type: ignore[method-assign]
|
||||||
|
code, j = call("GET", f"/jobs/{job['id']}")
|
||||||
|
assert j["status"] == "done" and "MODEL WRITTEN" in j["log"]
|
||||||
|
code, v = call("GET", "/versions")
|
||||||
|
assert code == 200 and v["versions"][0]["version"] == "vapi" and v["versions"][0]["written"] is True
|
||||||
|
assert v["versions"][0]["classes"] == ["sedan", "suv", "van"] and v["versions"][0]["accuracy"] >= 0.9
|
||||||
|
code, report = call("GET", "/versions/vapi/report")
|
||||||
|
assert code == 200 and report.startswith("# Body-type classifier vapi")
|
||||||
|
assert versions(out)[0]["floor"] == 0.0
|
||||||
|
# evaluate on the written model now succeeds
|
||||||
|
code, job2 = call("POST", "/jobs", {"kind": "evaluate", "version": "vapi"})
|
||||||
|
wait_idle(Handler.jobs)
|
||||||
|
assert call("GET", f"/jobs/{job2['id']}")[1]["status"] == "done"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_handler_error_is_a_500_json_reply_not_a_dropped_connection(tmp_path: Path) -> None:
|
||||||
|
"""A collector DB from before the `kind` column (art-docker-station, 2026-09-16): readiness
|
||||||
|
raised sqlite3.OperationalError, the stdlib server printed the traceback and closed the
|
||||||
|
socket, and the collector could only say "trainer not reachable: fetch failed". The
|
||||||
|
handler must answer 500 JSON naming the error instead."""
|
||||||
|
old = tmp_path / "old"
|
||||||
|
old.mkdir()
|
||||||
|
con = sqlite3.connect(old / "collector.sqlite")
|
||||||
|
con.executescript(
|
||||||
|
"CREATE TABLE items (id TEXT PRIMARY KEY, booth TEXT NOT NULL, order_ref TEXT NOT NULL,"
|
||||||
|
" at TEXT NOT NULL, service TEXT NOT NULL, vision_class TEXT NOT NULL,"
|
||||||
|
" vision_confidence REAL NOT NULL, image_width INTEGER NOT NULL, image_height INTEGER NOT NULL,"
|
||||||
|
" plate_blurred INTEGER NOT NULL, image_path TEXT NOT NULL, received_at TEXT NOT NULL,"
|
||||||
|
" review_label TEXT, reviewed_at TEXT, reviewer TEXT)"
|
||||||
|
)
|
||||||
|
con.commit()
|
||||||
|
con.close()
|
||||||
|
Handler.jobs = Jobs(old, tmp_path / "out", "https://example.invalid/pkg", "tok")
|
||||||
|
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||||
|
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/readiness")
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as ei:
|
||||||
|
urllib.request.urlopen(req, timeout=10)
|
||||||
|
assert ei.value.code == 500
|
||||||
|
body = json.loads(ei.value.read())
|
||||||
|
assert "no such column: kind" in body["error"]
|
||||||
|
# /health does not touch the DB and still answers.
|
||||||
|
with urllib.request.urlopen(f"http://127.0.0.1:{httpd.server_address[1]}/health", timeout=10) as r:
|
||||||
|
assert r.status == 200
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
@@ -272,6 +272,9 @@ def cmd_publish(a: argparse.Namespace) -> int:
|
|||||||
_log(f"{f} missing — nothing to publish (a run below the floor writes no model)")
|
_log(f"{f} missing — nothing to publish (a run below the floor writes no model)")
|
||||||
return 1
|
return 1
|
||||||
version = Sidecar.read(d / SIDECAR_FILE).version
|
version = Sidecar.read(d / SIDECAR_FILE).version
|
||||||
|
if not a.url:
|
||||||
|
_log("no publish url: pass --url or set TRAINER_PUBLISH_URL")
|
||||||
|
return 1
|
||||||
token = a.token or os.environ.get("TRAINER_PUBLISH_TOKEN", "")
|
token = a.token or os.environ.get("TRAINER_PUBLISH_TOKEN", "")
|
||||||
if not token:
|
if not token:
|
||||||
_log("no token: pass --token or set TRAINER_PUBLISH_TOKEN")
|
_log("no token: pass --token or set TRAINER_PUBLISH_TOKEN")
|
||||||
@@ -289,6 +292,20 @@ def cmd_publish(a: argparse.Namespace) -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_serve(a: argparse.Namespace) -> int:
|
||||||
|
from .server import serve
|
||||||
|
|
||||||
|
serve(
|
||||||
|
a.data,
|
||||||
|
a.out,
|
||||||
|
a.host,
|
||||||
|
a.port,
|
||||||
|
os.environ.get("TRAINER_PUBLISH_URL", ""),
|
||||||
|
os.environ.get("TRAINER_PUBLISH_TOKEN", ""),
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -366,10 +383,19 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
u = sub.add_parser("publish", help="PUT a version folder to a Gitea generic package")
|
u = sub.add_parser("publish", help="PUT a version folder to a Gitea generic package")
|
||||||
u.add_argument("dir", type=Path, help="the <version>/ folder a passing run wrote")
|
u.add_argument("dir", type=Path, help="the <version>/ folder a passing run wrote")
|
||||||
u.add_argument(
|
u.add_argument(
|
||||||
"--url", required=True, help="https://<gitea>/api/packages/<owner>/generic/parking-bodytype"
|
"--url",
|
||||||
|
default=os.environ.get("TRAINER_PUBLISH_URL", ""),
|
||||||
|
help="https://<gitea>/api/packages/<owner>/generic/parking-bodytype (or TRAINER_PUBLISH_URL)",
|
||||||
)
|
)
|
||||||
u.add_argument("--token", default="", help="Gitea token with package:write (or TRAINER_PUBLISH_TOKEN)")
|
u.add_argument("--token", default="", help="Gitea token with package:write (or TRAINER_PUBLISH_TOKEN)")
|
||||||
u.set_defaults(fn=cmd_publish)
|
u.set_defaults(fn=cmd_publish)
|
||||||
|
|
||||||
|
s = sub.add_parser("serve", help="the job API the collector's Training section talks to")
|
||||||
|
data_args(s)
|
||||||
|
s.add_argument("--out", type=Path, default=Path(os.environ.get("TRAINER_OUT_DIR", "/out")))
|
||||||
|
s.add_argument("--host", default=os.environ.get("TRAINER_HOST", "0.0.0.0"))
|
||||||
|
s.add_argument("--port", type=int, default=int(os.environ.get("TRAINER_PORT", "8091")))
|
||||||
|
s.set_defaults(fn=cmd_serve)
|
||||||
return p
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,402 @@
|
|||||||
|
"""`parking-trainer serve` — the job API behind the collector's Training section.
|
||||||
|
|
||||||
|
A tiny stdlib HTTP server (no framework, no extra deps) on the compose-internal network,
|
||||||
|
never published: the collector proxies to it behind the reviewer's login. One job at a
|
||||||
|
time; each job is the CLI run as a SUBPROCESS (`python -m trainer.cli …`) with its output
|
||||||
|
captured to a log file — torch's memory goes away with the process, and a crashing job
|
||||||
|
cannot take the service down. Job state + logs persist under `<out>/jobs/` so a restart
|
||||||
|
still shows history.
|
||||||
|
|
||||||
|
GET /health {ok, busy, version}
|
||||||
|
GET /readiness what `inspect` prints (+ the defaults the UI offers)
|
||||||
|
GET /versions every <out>/<version>/ folder: written?, metrics, sidecar
|
||||||
|
GET /versions/<v>/report report.md (text/markdown)
|
||||||
|
GET /jobs recent jobs, newest first
|
||||||
|
GET /jobs/<id> one job incl. the log tail
|
||||||
|
POST /jobs {kind: train|evaluate|publish, …args} → 202 {id} | 409 busy
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .cli import METRICS_FILE, MODEL_FILE, REPORT_FILE, SIDECAR_FILE
|
||||||
|
from .data import load_labelled, make_split, summarise
|
||||||
|
from .preprocess import Sidecar
|
||||||
|
|
||||||
|
_VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
||||||
|
BACKBONES = ("resnet18", "mobilenet_v3_small", "efficientnet_b0")
|
||||||
|
MODES = ("features", "finetune")
|
||||||
|
LOG_TAIL_BYTES = 16_000
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
class Jobs:
|
||||||
|
"""The single-slot job runner. `start` refuses while one runs."""
|
||||||
|
|
||||||
|
def __init__(self, data_dir: Path, out_dir: Path, publish_url: str, publish_token: str) -> None:
|
||||||
|
self.data_dir = data_dir
|
||||||
|
self.out_dir = out_dir
|
||||||
|
self.publish_url = publish_url
|
||||||
|
self.publish_token = publish_token
|
||||||
|
self.jobs_dir = out_dir / "jobs"
|
||||||
|
self.jobs_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._current: dict[str, Any] | None = None
|
||||||
|
self._proc: subprocess.Popen[bytes] | None = None
|
||||||
|
|
||||||
|
# ---- state -----------------------------------------------------------------------
|
||||||
|
def _write(self, job: dict[str, Any]) -> None:
|
||||||
|
(self.jobs_dir / f"{job['id']}.json").write_text(json.dumps(job, indent=2))
|
||||||
|
|
||||||
|
def _read(self, job_id: str) -> dict[str, Any] | None:
|
||||||
|
p = self.jobs_dir / f"{job_id}.json"
|
||||||
|
if not p.is_file():
|
||||||
|
return None
|
||||||
|
return json.loads(p.read_text()) # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
def log_tail(self, job_id: str) -> str:
|
||||||
|
p = self.jobs_dir / f"{job_id}.log"
|
||||||
|
if not p.is_file():
|
||||||
|
return ""
|
||||||
|
size = p.stat().st_size
|
||||||
|
with p.open("rb") as f:
|
||||||
|
if size > LOG_TAIL_BYTES:
|
||||||
|
f.seek(size - LOG_TAIL_BYTES)
|
||||||
|
return f.read().decode("utf-8", "replace")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def busy(self) -> bool:
|
||||||
|
return self._current is not None
|
||||||
|
|
||||||
|
def current(self) -> dict[str, Any] | None:
|
||||||
|
return dict(self._current) if self._current else None
|
||||||
|
|
||||||
|
def get(self, job_id: str) -> dict[str, Any] | None:
|
||||||
|
if self._current and self._current["id"] == job_id:
|
||||||
|
job = dict(self._current)
|
||||||
|
else:
|
||||||
|
job = self._read(job_id) or {}
|
||||||
|
if not job:
|
||||||
|
return None
|
||||||
|
job["log"] = self.log_tail(job_id)
|
||||||
|
return job
|
||||||
|
|
||||||
|
def recent(self, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
|
files = sorted(self.jobs_dir.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||||
|
out = []
|
||||||
|
for p in files[:limit]:
|
||||||
|
try:
|
||||||
|
out.append(json.loads(p.read_text()))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if self._current and all(j["id"] != self._current["id"] for j in out):
|
||||||
|
out.insert(0, dict(self._current))
|
||||||
|
out.sort(key=lambda j: j.get("startedAt", ""), reverse=True)
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ---- args → CLI ------------------------------------------------------------------
|
||||||
|
def _argv(self, kind: str, a: dict[str, Any]) -> list[str]:
|
||||||
|
base = [sys.executable, "-m", "trainer.cli"]
|
||||||
|
if kind == "train":
|
||||||
|
mode = a.get("mode", "features")
|
||||||
|
backbone = a.get("backbone", "resnet18")
|
||||||
|
if mode not in MODES or backbone not in BACKBONES:
|
||||||
|
raise ValueError("bad mode/backbone")
|
||||||
|
floor = float(a.get("minAccuracy", 0.85))
|
||||||
|
min_per = int(a.get("minPerClass", 20))
|
||||||
|
epochs = int(a.get("epochs", 0))
|
||||||
|
if not 0.0 <= floor <= 1.0 or min_per < 1 or epochs < 0:
|
||||||
|
raise ValueError("bad numbers")
|
||||||
|
argv = base + [
|
||||||
|
"train",
|
||||||
|
"--data",
|
||||||
|
str(self.data_dir),
|
||||||
|
"--out",
|
||||||
|
str(self.out_dir),
|
||||||
|
"--mode",
|
||||||
|
mode,
|
||||||
|
"--backbone",
|
||||||
|
backbone,
|
||||||
|
"--min-accuracy",
|
||||||
|
str(floor),
|
||||||
|
"--min-per-class",
|
||||||
|
str(min_per),
|
||||||
|
"--epochs",
|
||||||
|
str(epochs),
|
||||||
|
]
|
||||||
|
if a.get("version"):
|
||||||
|
argv += ["--version", self._version(a["version"])]
|
||||||
|
return argv
|
||||||
|
if kind == "evaluate":
|
||||||
|
v = self._version(a.get("version", ""))
|
||||||
|
return base + [
|
||||||
|
"evaluate",
|
||||||
|
"--data",
|
||||||
|
str(self.data_dir),
|
||||||
|
"--model",
|
||||||
|
str(self.out_dir / v / MODEL_FILE),
|
||||||
|
]
|
||||||
|
if kind == "publish":
|
||||||
|
v = self._version(a.get("version", ""))
|
||||||
|
url = str(a.get("url") or self.publish_url)
|
||||||
|
if not url.startswith("https://") and not url.startswith("http://"):
|
||||||
|
raise ValueError("bad publish url")
|
||||||
|
return base + ["publish", str(self.out_dir / v), "--url", url]
|
||||||
|
raise ValueError("kind must be train, evaluate or publish")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _version(v: Any) -> str:
|
||||||
|
if not isinstance(v, str) or not _VERSION_RE.match(v) or v in ("cache", "jobs"):
|
||||||
|
raise ValueError("bad version")
|
||||||
|
return v
|
||||||
|
|
||||||
|
# ---- run -------------------------------------------------------------------------
|
||||||
|
def start(self, kind: str, args: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
argv = self._argv(kind, args)
|
||||||
|
with self._lock:
|
||||||
|
if self._current is not None:
|
||||||
|
raise RuntimeError("busy")
|
||||||
|
job_id = f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}"
|
||||||
|
job: dict[str, Any] = {
|
||||||
|
"id": job_id,
|
||||||
|
"kind": kind,
|
||||||
|
"args": {k: v for k, v in args.items() if k != "token"},
|
||||||
|
"status": "running",
|
||||||
|
"startedAt": _now(),
|
||||||
|
"finishedAt": None,
|
||||||
|
"exitCode": None,
|
||||||
|
}
|
||||||
|
env = dict(os.environ)
|
||||||
|
if kind == "publish":
|
||||||
|
env["TRAINER_PUBLISH_TOKEN"] = self.publish_token
|
||||||
|
log = (self.jobs_dir / f"{job_id}.log").open("wb")
|
||||||
|
log.write(f"$ {' '.join(argv[3:])}\n".encode())
|
||||||
|
log.flush()
|
||||||
|
self._proc = subprocess.Popen(argv, stdout=log, stderr=subprocess.STDOUT, env=env)
|
||||||
|
self._current = job
|
||||||
|
self._write(job)
|
||||||
|
threading.Thread(target=self._wait, args=(job, log), daemon=True).start()
|
||||||
|
return dict(job)
|
||||||
|
|
||||||
|
def _wait(self, job: dict[str, Any], log: Any) -> None:
|
||||||
|
assert self._proc is not None
|
||||||
|
code = self._proc.wait()
|
||||||
|
log.close()
|
||||||
|
with self._lock:
|
||||||
|
job["exitCode"] = code
|
||||||
|
job["finishedAt"] = _now()
|
||||||
|
job["status"] = "done" if code == 0 else ("refused" if code in (2, 3) else "failed")
|
||||||
|
self._write(job)
|
||||||
|
self._current = None
|
||||||
|
self._proc = None
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def readiness(data_dir: Path, min_per_class: int = 20, val_fraction: float = 0.2) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
samples, missing = load_labelled(data_dir)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return {
|
||||||
|
"ready": False,
|
||||||
|
"labelled": {"total": 0, "byClass": {}},
|
||||||
|
"missingCrops": 0,
|
||||||
|
"error": "no collector database yet",
|
||||||
|
}
|
||||||
|
split = make_split(samples, val_fraction, min_per_class)
|
||||||
|
return {
|
||||||
|
"ready": len(split.classes) >= 2,
|
||||||
|
"labelled": summarise(samples),
|
||||||
|
"missingCrops": missing,
|
||||||
|
"run": {
|
||||||
|
"classes": list(split.classes),
|
||||||
|
"train": split.counts("train"),
|
||||||
|
"val": split.counts("val"),
|
||||||
|
"dropped": split.dropped,
|
||||||
|
"minPerClass": min_per_class,
|
||||||
|
"valFraction": val_fraction,
|
||||||
|
},
|
||||||
|
"defaults": {
|
||||||
|
"mode": "features",
|
||||||
|
"backbone": "resnet18",
|
||||||
|
"minAccuracy": 0.85,
|
||||||
|
"minPerClass": min_per_class,
|
||||||
|
},
|
||||||
|
"modes": list(MODES),
|
||||||
|
"backbones": list(BACKBONES),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def versions(out_dir: Path) -> list[dict[str, Any]]:
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
if not out_dir.is_dir():
|
||||||
|
return out
|
||||||
|
for d in sorted(out_dir.iterdir(), key=lambda p: p.name, reverse=True):
|
||||||
|
if not d.is_dir() or d.name in ("cache", "jobs"):
|
||||||
|
continue
|
||||||
|
if not (d / REPORT_FILE).is_file() and not (d / METRICS_FILE).is_file():
|
||||||
|
continue
|
||||||
|
entry: dict[str, Any] = {
|
||||||
|
"version": d.name,
|
||||||
|
"written": (d / MODEL_FILE).is_file() and (d / SIDECAR_FILE).is_file(),
|
||||||
|
"hasReport": (d / REPORT_FILE).is_file(),
|
||||||
|
"modifiedAt": datetime.fromtimestamp(d.stat().st_mtime, tz=timezone.utc)
|
||||||
|
.replace(microsecond=0)
|
||||||
|
.isoformat(),
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
m = json.loads((d / METRICS_FILE).read_text())
|
||||||
|
entry["accuracy"] = m.get("accuracy")
|
||||||
|
entry["macroRecall"] = m.get("macro_recall")
|
||||||
|
entry["n"] = m.get("n")
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
if entry["written"]:
|
||||||
|
try:
|
||||||
|
side = Sidecar.read(d / SIDECAR_FILE)
|
||||||
|
entry["classes"] = side.classes
|
||||||
|
entry["mode"] = side.mode
|
||||||
|
entry["backbone"] = side.backbone
|
||||||
|
entry["trainedAt"] = side.trained_at
|
||||||
|
entry["labels"] = side.labels
|
||||||
|
entry["floor"] = side.metrics.get("floor")
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
out.append(entry)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
jobs: Jobs # set on the class by serve()
|
||||||
|
server_version = "parking-trainer"
|
||||||
|
|
||||||
|
def log_message(self, fmt: str, *args: Any) -> None: # quieter than the default
|
||||||
|
sys.stderr.write(f"[trainer.serve] {self.address_string()} {fmt % args}\n")
|
||||||
|
|
||||||
|
def _json(self, code: int, body: Any) -> None:
|
||||||
|
raw = json.dumps(body).encode()
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(raw)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(raw)
|
||||||
|
|
||||||
|
def _text(self, code: int, body: str, ctype: str = "text/markdown; charset=utf-8") -> None:
|
||||||
|
raw = body.encode()
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", ctype)
|
||||||
|
self.send_header("Content-Length", str(len(raw)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(raw)
|
||||||
|
|
||||||
|
def do_GET(self) -> None: # noqa: N802
|
||||||
|
self._guarded(self._get)
|
||||||
|
|
||||||
|
def do_POST(self) -> None: # noqa: N802
|
||||||
|
self._guarded(self._post)
|
||||||
|
|
||||||
|
def _guarded(self, handler: Any) -> None:
|
||||||
|
"""Run a handler; an unexpected exception becomes a 500 JSON reply instead of a
|
||||||
|
dropped connection (the stdlib server would print the traceback and close the
|
||||||
|
socket, which the collector could only report as "fetch failed" — 2026-09-16,
|
||||||
|
a collector DB from before the `kind` column)."""
|
||||||
|
try:
|
||||||
|
handler()
|
||||||
|
except Exception as exc: # noqa: BLE001 — anything: the reply must be a reply
|
||||||
|
sys.stderr.write(f"[trainer.serve] {self.command} {self.path}: {type(exc).__name__}: {exc}\n")
|
||||||
|
try:
|
||||||
|
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
|
||||||
|
except Exception: # noqa: BLE001 — headers already sent; nothing left to do
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _get(self) -> None:
|
||||||
|
path = self.path.split("?", 1)[0]
|
||||||
|
j = self.jobs
|
||||||
|
if path == "/health":
|
||||||
|
self._json(200, {"ok": True, "busy": j.busy, "version": "parking-trainer"})
|
||||||
|
elif path == "/readiness":
|
||||||
|
self._json(200, readiness(j.data_dir))
|
||||||
|
elif path == "/versions":
|
||||||
|
self._json(200, {"versions": versions(j.out_dir)})
|
||||||
|
elif path.startswith("/versions/") and path.endswith("/report"):
|
||||||
|
v = path[len("/versions/") : -len("/report")]
|
||||||
|
try:
|
||||||
|
p = j.out_dir / Jobs._version(v) / REPORT_FILE
|
||||||
|
except ValueError:
|
||||||
|
self._json(400, {"error": "bad version"})
|
||||||
|
return
|
||||||
|
if not p.is_file():
|
||||||
|
self._json(404, {"error": "no report"})
|
||||||
|
else:
|
||||||
|
self._text(200, p.read_text())
|
||||||
|
elif path == "/jobs":
|
||||||
|
self._json(200, {"jobs": j.recent(), "current": j.current()})
|
||||||
|
elif path.startswith("/jobs/"):
|
||||||
|
job = j.get(path[len("/jobs/") :])
|
||||||
|
self._json(200, job) if job else self._json(404, {"error": "no such job"})
|
||||||
|
else:
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
|
||||||
|
def _post(self) -> None:
|
||||||
|
if self.path.split("?", 1)[0] != "/jobs":
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
return
|
||||||
|
n = int(self.headers.get("Content-Length") or 0)
|
||||||
|
if n > 64_000:
|
||||||
|
self._json(413, {"error": "too large"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
body = json.loads(self.rfile.read(n) or b"{}")
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise ValueError("object expected")
|
||||||
|
except ValueError as exc:
|
||||||
|
self._json(400, {"error": f"bad json: {exc}"})
|
||||||
|
return
|
||||||
|
kind = str(body.pop("kind", ""))
|
||||||
|
try:
|
||||||
|
job = self.jobs.start(kind, body)
|
||||||
|
except ValueError as exc:
|
||||||
|
self._json(400, {"error": str(exc)})
|
||||||
|
return
|
||||||
|
except RuntimeError:
|
||||||
|
self._json(409, {"error": "a job is already running", "current": self.jobs.current()})
|
||||||
|
return
|
||||||
|
self._json(202, job)
|
||||||
|
|
||||||
|
|
||||||
|
def serve(data_dir: Path, out_dir: Path, host: str, port: int, publish_url: str, publish_token: str) -> None:
|
||||||
|
Handler.jobs = Jobs(data_dir, out_dir, publish_url, publish_token)
|
||||||
|
httpd = ThreadingHTTPServer((host, port), Handler)
|
||||||
|
sys.stderr.write(f"[trainer.serve] listening on {host}:{port}, data {data_dir}, out {out_dir}\n")
|
||||||
|
try:
|
||||||
|
httpd.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_idle(jobs: Jobs, timeout: float = 60.0) -> None:
|
||||||
|
"""Test helper: block until no job runs."""
|
||||||
|
t0 = time.monotonic()
|
||||||
|
while jobs.busy and time.monotonic() - t0 < timeout:
|
||||||
|
time.sleep(0.1)
|
||||||
@@ -49,3 +49,25 @@ def test_analyze_rejects_empty_body() -> None:
|
|||||||
headers={"content-type": "application/octet-stream"},
|
headers={"content-type": "application/octet-stream"},
|
||||||
)
|
)
|
||||||
assert res.status_code == 400
|
assert res.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_access_log_lines_are_dropped() -> None:
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from vision_service.app import DropHealthAccessLog
|
||||||
|
|
||||||
|
flt = DropHealthAccessLog()
|
||||||
|
access = logging.getLogger("uvicorn.access")
|
||||||
|
# uvicorn's access record: '%s - "%s %s HTTP/%s" %d' with (client, method, path, version, status)
|
||||||
|
fmt = '%s - "%s %s HTTP/%s" %d'
|
||||||
|
|
||||||
|
def record(method: str, path: str) -> logging.LogRecord:
|
||||||
|
args = ("127.0.0.1:1", method, path, "1.1", 200)
|
||||||
|
return access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, args, None)
|
||||||
|
|
||||||
|
health = record("GET", "/health")
|
||||||
|
analyze = record("POST", "/analyze")
|
||||||
|
assert flt.filter(health) is False
|
||||||
|
assert flt.filter(analyze) is True
|
||||||
|
# The filter is installed on the live logger at import.
|
||||||
|
assert any(isinstance(f, DropHealthAccessLog) for f in access.filters)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ advisory, never the sole authority. See wiki/entities/opencv-anpr-service.md.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
from collections.abc import AsyncIterator
|
from collections.abc import AsyncIterator
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
@@ -34,6 +35,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|||||||
app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan)
|
app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan)
|
||||||
|
|
||||||
|
|
||||||
|
class DropHealthAccessLog(logging.Filter):
|
||||||
|
"""Drop uvicorn access-log lines for GET /health.
|
||||||
|
|
||||||
|
The probe is hit every 30 s by Docker's HEALTHCHECK and every 8 s by the booth
|
||||||
|
server's footer chip; on a quiet booth those lines were ~90 % of this container's
|
||||||
|
output (park-2, 2026-10-08). /analyze and everything else still log.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
return "/health" not in record.getMessage()
|
||||||
|
|
||||||
|
|
||||||
|
# uvicorn applies its logging config before importing the app, so a filter added here
|
||||||
|
# survives; dictConfig replaces handlers, not a logger's filters.
|
||||||
|
logging.getLogger("uvicorn.access").addFilter(DropHealthAccessLog())
|
||||||
|
|
||||||
|
|
||||||
# Typed accessors over the untyped `app.state` (so mypy --strict sees the real types).
|
# Typed accessors over the untyped `app.state` (so mypy --strict sees the real types).
|
||||||
def _recognizer(request: Request) -> Recognizer:
|
def _recognizer(request: Request) -> Recognizer:
|
||||||
rec: Recognizer = request.app.state.recognizer
|
rec: Recognizer = request.app.state.recognizer
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
boothExit,
|
boothExit,
|
||||||
can,
|
can,
|
||||||
fetchSiteConfig,
|
fetchSiteConfig,
|
||||||
|
forgiveExit,
|
||||||
lookupSession,
|
lookupSession,
|
||||||
openShift,
|
openShift,
|
||||||
paySession,
|
paySession,
|
||||||
@@ -61,6 +62,12 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
|
|||||||
const { user } = rootRoute.useRouteContext();
|
const { user } = rootRoute.useRouteContext();
|
||||||
const canVoid = can(user, "event:void");
|
const canVoid = can(user, "event:void");
|
||||||
const [voiding, setVoiding] = useState(false); // reason prompt revealed
|
const [voiding, setVoiding] = useState(false); // reason prompt revealed
|
||||||
|
// FORGIVEN exit (barrier:create; wiki/decisions/forgiven-exit.md): let the car out with
|
||||||
|
// NO payment. The fee owed is signed as forgone on a $0 payment — on the shift report
|
||||||
|
// as its own line, never as cash. Reason optional; nothing printed.
|
||||||
|
const canForgivePerm = can(user, "barrier:create");
|
||||||
|
const [forgiving, setForgiving] = useState(false); // reason prompt revealed
|
||||||
|
const [forgiveNote, setForgiveNote] = useState("");
|
||||||
// Plate-swap: set when boothExit returns swap_suspected. Holds the detail for the warning
|
// Plate-swap: set when boothExit returns swap_suspected. Holds the detail for the warning
|
||||||
// panel; the operator must consciously "Override & release". See plate-reconciliation.md.
|
// panel; the operator must consciously "Override & release". See plate-reconciliation.md.
|
||||||
const [swap, setSwap] = useState<{ plate: string; otherIdentity: string; otherEnteredAt: string | null } | null>(null);
|
const [swap, setSwap] = useState<{ plate: string; otherIdentity: string; otherEnteredAt: string | null } | null>(null);
|
||||||
@@ -150,6 +157,31 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
|
|||||||
// session (a subscription is closed via its own flow; a paid ticket is a refund). The
|
// session (a subscription is closed via its own flow; a paid ticket is a refund). The
|
||||||
// server enforces all of this too; the UI just hides the action when it can't apply.
|
// server enforces all of this too; the UI just hides the action when it can't apply.
|
||||||
const canCancel = !!(canVoid && shiftReady && s?.found && s.open && !isSubscription && !alreadyPaid);
|
const canCancel = !!(canVoid && shiftReady && s?.found && s.open && !isSubscription && !alreadyPaid);
|
||||||
|
// Forgivable = an OPEN transient that owes money now (unpaid, or an overstay top-up).
|
||||||
|
// A paid-within-grace car takes the plain re-open; a subscriber the assist path.
|
||||||
|
const canForgive = !!(canForgivePerm && shiftReady && s?.found && s.open && !isSubscription && (!alreadyPaid || isOverstay));
|
||||||
|
|
||||||
|
async function handleForgiveExit() {
|
||||||
|
const note = forgiveNote.trim(); // optional
|
||||||
|
setError(null);
|
||||||
|
setPhase("finishing");
|
||||||
|
try {
|
||||||
|
const r = await forgiveExit(identity, note);
|
||||||
|
const amount = formatMoney(r.forgoneMinor ?? 0, r.currency ?? s?.currency ?? "");
|
||||||
|
setResult(
|
||||||
|
r.opened
|
||||||
|
? t("pay.exitForgiven", { amount })
|
||||||
|
: t("pay.exitForgivenNotOpened", { amount, reason: r.reason ?? t("booth.openManually") }),
|
||||||
|
);
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.occupancy });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
||||||
|
setPhase("done");
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setPhase("error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleVoidTicket() {
|
async function handleVoidTicket() {
|
||||||
const reason = voidReason.trim();
|
const reason = voidReason.trim();
|
||||||
@@ -556,6 +588,26 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Forgiven-exit reason prompt (revealed by the "Forgive & open" button).
|
||||||
|
Free text, OPTIONAL. Signs a $0 payment carrying the forgone fee, then
|
||||||
|
the exit + barrier pulse. Nothing is printed. */}
|
||||||
|
{forgiving && phase !== "done" && (
|
||||||
|
<div className="rounded-term border border-term-red/50 bg-term-red/5 px-3 py-2">
|
||||||
|
<div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-term-red">
|
||||||
|
{t("pay.forgiveTitle")}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[0.75rem] text-term-text">
|
||||||
|
{t("pay.forgiveHint", { amount: formatMoney(s?.amountMinor ?? 0, s?.currency ?? "") })}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
className="input mt-2 w-full"
|
||||||
|
value={forgiveNote}
|
||||||
|
onChange={(e) => setForgiveNote(e.target.value)}
|
||||||
|
placeholder={t("pay.forgiveReasonPlaceholder")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* PLATE-SWAP warning: the exiting plate is already inside under another
|
{/* PLATE-SWAP warning: the exiting plate is already inside under another
|
||||||
ticket. A prominent, deliberate hold — the operator must consciously
|
ticket. A prominent, deliberate hold — the operator must consciously
|
||||||
override to release. See wiki/concepts/plate-reconciliation.md. */}
|
override to release. See wiki/concepts/plate-reconciliation.md. */}
|
||||||
@@ -661,6 +713,16 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
|
|||||||
{t("pay.assistOpenReveal")}
|
{t("pay.assistOpenReveal")}
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
|
) : forgiving ? (
|
||||||
|
// Forgiven-exit confirm (reason prompt is shown above).
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleForgiveExit}
|
||||||
|
disabled={phase === "finishing"}
|
||||||
|
className="btn btn-danger btn-lg"
|
||||||
|
>
|
||||||
|
{phase === "finishing" ? t("pay.forgiving") : t("pay.confirmForgive")}
|
||||||
|
</button>
|
||||||
) : voiding ? (
|
) : voiding ? (
|
||||||
// Cancel-ticket confirm (reason prompt is shown above).
|
// Cancel-ticket confirm (reason prompt is shown above).
|
||||||
<button
|
<button
|
||||||
@@ -684,6 +746,17 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
|
|||||||
{t("pay.cancelTicket")}
|
{t("pay.cancelTicket")}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{/* Forgive the fee and open the exit (barrier:create only). Reveals
|
||||||
|
the reason prompt above. */}
|
||||||
|
{canForgive && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setForgiving(true)}
|
||||||
|
className="btn btn-ghost btn-sm text-term-red"
|
||||||
|
>
|
||||||
|
{t("pay.forgiveExit")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{swap ? (
|
{swap ? (
|
||||||
// Plate-swap held → the only forward action is a conscious
|
// Plate-swap held → the only forward action is a conscious
|
||||||
// override (re-submit with override:true; payment already taken).
|
// override (re-submit with override:true; payment already taken).
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { useRef, useState } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js";
|
import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, forgiveExit, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js";
|
||||||
import { rootRoute } from "./router.js";
|
import { rootRoute } from "./router.js";
|
||||||
import { qk } from "./lib/query.js";
|
import { qk } from "./lib/query.js";
|
||||||
import { useLiveStore } from "./lib/live-store.js";
|
import { useLiveStore } from "./lib/live-store.js";
|
||||||
import { useShift } from "./lib/use-shift.js";
|
import { useShift } from "./lib/use-shift.js";
|
||||||
import { useScanner } from "./lib/use-scanner.js";
|
import { useScanner } from "./lib/use-scanner.js";
|
||||||
|
import { Modal } from "./ui/Modal.js";
|
||||||
import { Panel } from "./ui/Panel.js";
|
import { Panel } from "./ui/Panel.js";
|
||||||
import { StatusDot } from "./ui/StatusDot.js";
|
import { StatusDot } from "./ui/StatusDot.js";
|
||||||
import { BoothPayModal } from "./BoothPayModal.js";
|
import { BoothPayModal } from "./BoothPayModal.js";
|
||||||
@@ -130,6 +131,8 @@ function BarrierLight({
|
|||||||
issuing,
|
issuing,
|
||||||
bypassRadar,
|
bypassRadar,
|
||||||
bypassCamera,
|
bypassCamera,
|
||||||
|
onOpen,
|
||||||
|
opening,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
@@ -141,6 +144,11 @@ function BarrierLight({
|
|||||||
/** Admin bypass of a faulty device: a bypassed signal counts as present (server re-checks). */
|
/** Admin bypass of a faulty device: a bypassed signal counts as present (server re-checks). */
|
||||||
bypassRadar?: boolean;
|
bypassRadar?: boolean;
|
||||||
bypassCamera?: boolean;
|
bypassCamera?: boolean;
|
||||||
|
/** When set (exit light + barrier:create + own shift), clicking opens the manual-exit
|
||||||
|
* dialog — NOT presence-gated (the car may be anywhere in the lane, or the lane may be
|
||||||
|
* empty while the operator prepares). The light keeps showing the lane state. */
|
||||||
|
onOpen?: () => void;
|
||||||
|
opening?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
// Blink only when the radar sees something the camera hasn't confirmed.
|
// Blink only when the radar sees something the camera hasn't confirmed.
|
||||||
@@ -151,14 +159,15 @@ function BarrierLight({
|
|||||||
const radarOk = radar || !!bypassRadar;
|
const radarOk = radar || !!bypassRadar;
|
||||||
const cameraOk = busy || !!bypassCamera;
|
const cameraOk = busy || !!bypassCamera;
|
||||||
const canIssue = !!onIssue && radarOk && cameraOk && !issuing;
|
const canIssue = !!onIssue && radarOk && cameraOk && !issuing;
|
||||||
const clickable = !!onIssue && radarOk && cameraOk;
|
const clickable = (!!onIssue && radarOk && cameraOk) || !!onOpen;
|
||||||
|
const onClick = canIssue ? onIssue : onOpen && !opening ? onOpen : undefined;
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`flex items-center gap-2 rounded-term border px-3 py-2 ${blinking ? "lane-blink" : solid} ${
|
className={`flex items-center gap-2 rounded-term border px-3 py-2 ${blinking ? "lane-blink" : solid} ${
|
||||||
clickable ? "cursor-pointer hover:brightness-125" : ""
|
clickable ? "cursor-pointer hover:brightness-125" : ""
|
||||||
}`}
|
}`}
|
||||||
title={clickable ? t("booth.issueEntryTitle") : label}
|
title={onOpen ? t("booth.forgiveExitTitle") : clickable ? t("booth.issueEntryTitle") : label}
|
||||||
onClick={canIssue ? onIssue : undefined}
|
onClick={onClick}
|
||||||
role={clickable ? "button" : undefined}
|
role={clickable ? "button" : undefined}
|
||||||
>
|
>
|
||||||
{/* Barrier glyph: a post + an arm. `currentColor` follows the (possibly blinking) state. */}
|
{/* Barrier glyph: a post + an arm. `currentColor` follows the (possibly blinking) state. */}
|
||||||
@@ -170,7 +179,7 @@ function BarrierLight({
|
|||||||
<div className="leading-tight">
|
<div className="leading-tight">
|
||||||
<div className="text-[0.625rem] uppercase tracking-wider text-term-muted">{label}</div>
|
<div className="text-[0.625rem] uppercase tracking-wider text-term-muted">{label}</div>
|
||||||
<div className="text-xs font-bold">
|
<div className="text-xs font-bold">
|
||||||
{issuing ? "…" : clickable ? t("booth.issueEntry") : busy ? "●" : blinking ? "◐" : "○"}
|
{issuing || opening ? "…" : onIssue && clickable ? t("booth.issueEntry") : busy ? "●" : blinking ? "◐" : "○"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -216,6 +225,28 @@ function LaneIndicators() {
|
|||||||
if (window.confirm(t("booth.issueEntryConfirm"))) issue.mutate();
|
if (window.confirm(t("booth.issueEntryConfirm"))) issue.mutate();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FORGIVEN exit for a car with NO ticket (barrier:create; wiki/decisions/forgiven-exit.md):
|
||||||
|
// signed anomaly + exit snapshot + pulse, no money, nothing printed. A small styled
|
||||||
|
// dialog (same chrome as every other form) asks for an OPTIONAL reason, then confirms.
|
||||||
|
const canForgive = can(user, "barrier:create") && shiftOpen && isMine;
|
||||||
|
const [forgiveOpen, setForgiveOpen] = useState(false);
|
||||||
|
const [forgiveNote, setForgiveNote] = useState("");
|
||||||
|
const forgive = useMutation({
|
||||||
|
mutationFn: (note: string) => forgiveExit(null, note),
|
||||||
|
onSuccess: (r) => {
|
||||||
|
setForgiveOpen(false);
|
||||||
|
setForgiveNote("");
|
||||||
|
setMsg({ ok: r.opened, text: r.opened ? t("booth.forgiveExitOk") : t("booth.forgiveExitNotOpened", { reason: r.reason ?? "" }) });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
setTimeout(() => setMsg(null), 5000);
|
||||||
|
},
|
||||||
|
onError: (e) => {
|
||||||
|
setForgiveOpen(false);
|
||||||
|
setMsg({ ok: false, text: (e as Error).message });
|
||||||
|
setTimeout(() => setMsg(null), 5000);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<BarrierLight
|
<BarrierLight
|
||||||
@@ -227,7 +258,49 @@ function LaneIndicators() {
|
|||||||
bypassRadar={site?.bypassPresenceRadar ?? false}
|
bypassRadar={site?.bypassPresenceRadar ?? false}
|
||||||
bypassCamera={site?.bypassPresenceCamera ?? false}
|
bypassCamera={site?.bypassPresenceCamera ?? false}
|
||||||
/>
|
/>
|
||||||
<BarrierLight label={t("booth.laneExit")} busy={lanes?.exit ?? false} radar={radar?.exit ?? false} />
|
{/* The exit light IS the manual-exit control for whoever may use it (barrier:create +
|
||||||
|
own shift): same chrome as the entry light, still showing the lane state, labelled
|
||||||
|
"manual exit" and clickable. For everyone else it is the plain exit lane light. */}
|
||||||
|
<BarrierLight
|
||||||
|
label={canForgive ? t("booth.forgiveExit") : t("booth.laneExit")}
|
||||||
|
busy={lanes?.exit ?? false}
|
||||||
|
radar={radar?.exit ?? false}
|
||||||
|
onOpen={canForgive ? () => setForgiveOpen(true) : undefined}
|
||||||
|
opening={forgive.isPending}
|
||||||
|
/>
|
||||||
|
{/* Forgiven-exit dialog (no ticket): what it does, an optional reason, a deliberate red
|
||||||
|
confirm. Enter in the field confirms; Escape / ✕ / Cancel abort. */}
|
||||||
|
<Modal open={forgiveOpen} onClose={() => setForgiveOpen(false)} title={t("booth.forgiveDialogTitle")} width="max-w-md">
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!forgive.isPending) forgive.mutate(forgiveNote.trim());
|
||||||
|
}}
|
||||||
|
className="flex flex-col gap-3"
|
||||||
|
>
|
||||||
|
<div className="rounded-term border border-term-red/50 bg-term-red/5 px-3 py-2 text-[0.75rem] text-term-text">
|
||||||
|
{t("booth.forgiveDialogBody")}
|
||||||
|
</div>
|
||||||
|
<label className="flex flex-col gap-1 text-[0.6875rem] uppercase tracking-wider text-term-muted">
|
||||||
|
{t("booth.forgiveDialogReason")}
|
||||||
|
<input
|
||||||
|
className="input w-full normal-case tracking-normal"
|
||||||
|
value={forgiveNote}
|
||||||
|
onChange={(e) => setForgiveNote(e.target.value)}
|
||||||
|
placeholder={t("booth.forgiveDialogReasonPlaceholder")}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
<button type="button" onClick={() => setForgiveOpen(false)} className="btn btn-ghost btn-sm">
|
||||||
|
{t("common.cancel")}
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={forgive.isPending} className="btn btn-danger">
|
||||||
|
{forgive.isPending ? t("booth.forgiveDialogWorking") : t("booth.forgiveDialogConfirm")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
{msg && (
|
{msg && (
|
||||||
<span className={`text-[0.6875rem] ${msg.ok ? "text-term-green" : "text-term-red"}`}>{msg.text}</span>
|
<span className={`text-[0.6875rem] ${msg.ok ? "text-term-green" : "text-term-red"}`}>{msg.text}</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ import {
|
|||||||
fetchUsbPrinters,
|
fetchUsbPrinters,
|
||||||
} from "./api.js";
|
} from "./api.js";
|
||||||
import { Modal } from "./ui/Modal.js";
|
import { Modal } from "./ui/Modal.js";
|
||||||
|
import { CrossingLineEditor } from "./ui/CrossingLineEditor.js";
|
||||||
|
import { parseCrossingLine, type CrossingLine } from "@parking/shared";
|
||||||
|
|
||||||
// First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with
|
// First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with
|
||||||
// a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each
|
// a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each
|
||||||
@@ -534,6 +536,8 @@ function DeviceForm({
|
|||||||
// back-plate read would otherwise phantom-exit the car that just entered). Defaults ON
|
// back-plate read would otherwise phantom-exit the car that just entered). Defaults ON
|
||||||
// when anpr is on (back-compat). (config.anprAutoTrigger).
|
// when anpr is on (back-compat). (config.anprAutoTrigger).
|
||||||
const [anprAuto, setAnprAuto] = useState<boolean>(editCfg?.anprAutoTrigger !== false);
|
const [anprAuto, setAnprAuto] = useState<boolean>(editCfg?.anprAutoTrigger !== false);
|
||||||
|
// Crossing line drawn over this camera's view (passage confirmation). (config.crossing)
|
||||||
|
const [crossing, setCrossing] = useState<CrossingLine | null>(() => parseCrossingLine(editCfg?.crossing));
|
||||||
|
|
||||||
// Pre-fill scalar config fields from the existing assignment when editing.
|
// Pre-fill scalar config fields from the existing assignment when editing.
|
||||||
// (relays/controllerId/relay are model fields handled by their own state below.)
|
// (relays/controllerId/relay are model fields handled by their own state below.)
|
||||||
@@ -735,6 +739,8 @@ function DeviceForm({
|
|||||||
// park can explicitly DISABLE auto-open on a camera (e.g. the exit cam of a shared lane)
|
// park can explicitly DISABLE auto-open on a camera (e.g. the exit cam of a shared lane)
|
||||||
// while keeping recognition. Absent ⇒ defaults ON (back-compat for existing cameras).
|
// while keeping recognition. Absent ⇒ defaults ON (back-compat for existing cameras).
|
||||||
if (isCamera && anpr) out.anprAutoTrigger = anprAuto;
|
if (isCamera && anpr) out.anprAutoTrigger = anprAuto;
|
||||||
|
// Crossing line: always sent for a camera, `null` to clear (the server merges configs).
|
||||||
|
if (isCamera) out.crossing = crossing ? { p1: { ...crossing.p1 }, p2: { ...crossing.p2 }, direction: crossing.direction } : null;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -855,7 +861,7 @@ function DeviceForm({
|
|||||||
{scanning ? t("setup.scanning") : t("setup.scan")}
|
{scanning ? t("setup.scanning") : t("setup.scan")}
|
||||||
</button>
|
</button>
|
||||||
{scanError && <span className="ml-2 text-[0.75rem] text-term-red">{scanError}</span>}
|
{scanError && <span className="ml-2 text-[0.75rem] text-term-red">{scanError}</span>}
|
||||||
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noControllersFound")}</p>}
|
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noDevicesFound")}</p>}
|
||||||
{found && found.length > 0 && (
|
{found && found.length > 0 && (
|
||||||
<ul className="mt-2 list-none p-0">
|
<ul className="mt-2 list-none p-0">
|
||||||
{found.map((d) => (
|
{found.map((d) => (
|
||||||
@@ -865,7 +871,15 @@ function DeviceForm({
|
|||||||
</button>
|
</button>
|
||||||
<strong className="text-term-text">{d.label}</strong>
|
<strong className="text-term-text">{d.label}</strong>
|
||||||
<HealthBadge status={d.health.status} />
|
<HealthBadge status={d.health.status} />
|
||||||
{d.info?.firmware && <span className="text-term-muted"> · fw {d.info.firmware}</span>}
|
{/* Whatever the driver reports (firmware; for a reader its output mode +
|
||||||
|
current push target — so a reader still in WG26 or pointing at another
|
||||||
|
server is visible BEFORE it is assigned). */}
|
||||||
|
{d.info &&
|
||||||
|
Object.entries(d.info).map(([k, v]) => (
|
||||||
|
<span key={k} className="text-term-muted">
|
||||||
|
{" "}· {k} {v}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -1077,6 +1091,15 @@ function DeviceForm({
|
|||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* CAMERA: the crossing line (passage confirmation), drawn over the live picture.
|
||||||
|
Needs a saved camera — the live stream is addressed by its device id. */}
|
||||||
|
{isCamera &&
|
||||||
|
(editing?.id ? (
|
||||||
|
<CrossingLineEditor deviceId={editing.id} value={crossing} onChange={setCrossing} />
|
||||||
|
) : (
|
||||||
|
<p className="hint my-2">{t("setup.crossingSaveFirst")}</p>
|
||||||
|
))}
|
||||||
|
|
||||||
{/* CAMERA + Alarm Server push ON: show the camera's Alarm Server settings,
|
{/* CAMERA + Alarm Server push ON: show the camera's Alarm Server settings,
|
||||||
ready to copy, so the operator never has to find the deviceId or memorise the
|
ready to copy, so the operator never has to find the deviceId or memorise the
|
||||||
endpoint. The CAMERA reaches us over the device VLAN, NOT via the browser's
|
endpoint. The CAMERA reaches us over the device VLAN, NOT via the browser's
|
||||||
|
|||||||
@@ -174,6 +174,13 @@ function CloseShiftConfirm({
|
|||||||
part is broken out below it; subscription SALES is not (it's the remainder). */}
|
part is broken out below it; subscription SALES is not (it's the remainder). */}
|
||||||
<span />
|
<span />
|
||||||
<ConfirmFigure label={t("shift.srcSubWindow")} value={fmt(x.subscriptionWindowMinor)} sub />
|
<ConfirmFigure label={t("shift.srcSubWindow")} value={fmt(x.subscriptionWindowMinor)} sub />
|
||||||
|
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
|
||||||
|
{(x.forgoneCount ?? 0) > 0 && (
|
||||||
|
<>
|
||||||
|
<ConfirmFigure label={t("shift.srcForgone", { count: x.forgoneCount })} value={fmt(x.forgoneTotalMinor ?? 0)} />
|
||||||
|
<span />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -92,6 +92,8 @@ function useCurrentShifts(): { current: CurrentShift[]; tills: TillId[]; workabl
|
|||||||
subscriptionSalesMinor: x.subscriptionSalesMinor,
|
subscriptionSalesMinor: x.subscriptionSalesMinor,
|
||||||
subscriptionWindowMinor: x.subscriptionWindowMinor,
|
subscriptionWindowMinor: x.subscriptionWindowMinor,
|
||||||
chargesByModuleMinor: x.chargesByModuleMinor,
|
chargesByModuleMinor: x.chargesByModuleMinor,
|
||||||
|
forgoneTotalMinor: x.forgoneTotalMinor,
|
||||||
|
forgoneCount: x.forgoneCount,
|
||||||
openingFloatMinor: x.openingFloatMinor,
|
openingFloatMinor: x.openingFloatMinor,
|
||||||
cashAddedMinor: x.cashAddedMinor,
|
cashAddedMinor: x.cashAddedMinor,
|
||||||
cashRemovedMinor: x.cashRemovedMinor,
|
cashRemovedMinor: x.cashRemovedMinor,
|
||||||
@@ -409,6 +411,10 @@ function ShiftActivityLog({
|
|||||||
<Figure label={t("shifts.srcSubscriptions")} value={money(shift.subscriptionTotalMinor, cur)} />
|
<Figure label={t("shifts.srcSubscriptions")} value={money(shift.subscriptionTotalMinor, cur)} />
|
||||||
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
||||||
<Figure label={t("shifts.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
|
<Figure label={t("shifts.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
|
||||||
|
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
|
||||||
|
{(shift.forgoneCount ?? 0) > 0 && (
|
||||||
|
<Figure label={t("shifts.srcForgone", { count: shift.forgoneCount })} value={money(shift.forgoneTotalMinor ?? 0, cur)} />
|
||||||
|
)}
|
||||||
<ChargeFigures charges={shift.chargesByModuleMinor} cur={cur} />
|
<ChargeFigures charges={shift.chargesByModuleMinor} cur={cur} />
|
||||||
<Figure label={t("shifts.openingFloat")} value={money(shift.openingFloatMinor, cur)} />
|
<Figure label={t("shifts.openingFloat")} value={money(shift.openingFloatMinor, cur)} />
|
||||||
<Figure label={t("shifts.cashTaken")} value={money(shift.cashTotalMinor, cur)} />
|
<Figure label={t("shifts.cashTaken")} value={money(shift.cashTotalMinor, cur)} />
|
||||||
@@ -471,6 +477,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos
|
|||||||
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
||||||
<span />
|
<span />
|
||||||
<Figure label={t("shift.srcSubWindow")} value={money(report.subscriptionWindowMinor, report.currency)} sub />
|
<Figure label={t("shift.srcSubWindow")} value={money(report.subscriptionWindowMinor, report.currency)} sub />
|
||||||
|
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
|
||||||
|
{(report.forgoneCount ?? 0) > 0 && (
|
||||||
|
<Figure label={t("shift.srcForgone", { count: report.forgoneCount })} value={money(report.forgoneTotalMinor ?? 0, report.currency)} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
|
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
|
||||||
<Figure label={t("shift.cash")} value={money(report.cashTotalMinor, report.currency)} />
|
<Figure label={t("shift.cash")} value={money(report.cashTotalMinor, report.currency)} />
|
||||||
@@ -498,6 +508,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos
|
|||||||
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
||||||
<span />
|
<span />
|
||||||
<Figure label={t("shift.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
|
<Figure label={t("shift.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
|
||||||
|
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
|
||||||
|
{(shift.forgoneCount ?? 0) > 0 && (
|
||||||
|
<Figure label={t("shift.srcForgone", { count: shift.forgoneCount })} value={money(shift.forgoneTotalMinor ?? 0, cur)} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-2 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-2">
|
<div className="mt-2 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-2">
|
||||||
<Figure label={t("shift.cash")} value={money(shift.cashTotalMinor, cur)} />
|
<Figure label={t("shift.cash")} value={money(shift.cashTotalMinor, cur)} />
|
||||||
@@ -540,6 +554,10 @@ function TakingsModal({ till, onClose }: { till: TillId; onClose: () => void })
|
|||||||
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
|
||||||
<span />
|
<span />
|
||||||
<Figure label={t("shift.srcSubWindow")} value={money(x.subscriptionWindowMinor, x.currency)} sub />
|
<Figure label={t("shift.srcSubWindow")} value={money(x.subscriptionWindowMinor, x.currency)} sub />
|
||||||
|
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
|
||||||
|
{(x.forgoneCount ?? 0) > 0 && (
|
||||||
|
<Figure label={t("shift.srcForgone", { count: x.forgoneCount })} value={money(x.forgoneTotalMinor ?? 0, x.currency)} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
|
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
|
||||||
<Figure label={t("shift.cash")} value={money(x.cashTotalMinor, x.currency)} />
|
<Figure label={t("shift.cash")} value={money(x.cashTotalMinor, x.currency)} />
|
||||||
|
|||||||
@@ -94,6 +94,8 @@ export interface SessionUser {
|
|||||||
theme: Theme;
|
theme: Theme;
|
||||||
/** Preferred UI font scale, percent of base (100 = base; clamped 80–160). */
|
/** Preferred UI font scale, percent of base (100 = base; clamped 80–160). */
|
||||||
fontScale: number;
|
fontScale: number;
|
||||||
|
/** Booth camera tiles left open (camera device ids, opening order). */
|
||||||
|
openCameras: string[];
|
||||||
/** Optional display name (profile metadata); null if unset. */
|
/** Optional display name (profile metadata); null if unset. */
|
||||||
fullName: string | null;
|
fullName: string | null;
|
||||||
/** Optional contact email (profile metadata); null if unset. */
|
/** Optional contact email (profile metadata); null if unset. */
|
||||||
@@ -156,6 +158,45 @@ export function setFontScalePref(fontScale: number): Promise<{ fontScale: number
|
|||||||
return apiFetch("/api/auth/font-scale", { method: "PUT", body: JSON.stringify({ fontScale }) });
|
return apiFetch("/api/auth/font-scale", { method: "PUT", body: JSON.stringify({ fontScale }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Persist which booth camera tiles are open (restored on next login). */
|
||||||
|
export function setOpenCamerasPref(openCameras: string[]): Promise<{ openCameras: string[] }> {
|
||||||
|
return apiFetch("/api/auth/open-cameras", { method: "PUT", body: JSON.stringify({ openCameras }) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest entry/exit snapshot a camera captured (a camera tile's resting picture). */
|
||||||
|
export interface CameraSnapshotMeta {
|
||||||
|
id: string;
|
||||||
|
direction: "entry" | "exit";
|
||||||
|
capturedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Latest snapshot metadata for a camera, or null when it has none yet. */
|
||||||
|
export async function fetchLatestCameraSnapshot(deviceId: string): Promise<CameraSnapshotMeta | null> {
|
||||||
|
try {
|
||||||
|
return await apiFetch<CameraSnapshotMeta>(`/api/cameras/${encodeURIComponent(deviceId)}/latest-snapshot`);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError && err.status === 404) return null;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The next older / newer snapshot of the same camera (the large view's ‹ ›). */
|
||||||
|
export function fetchCameraSnapshotNeighbors(
|
||||||
|
deviceId: string,
|
||||||
|
snapshotId: string,
|
||||||
|
): Promise<{ older: CameraSnapshotMeta | null; newer: CameraSnapshotMeta | null }> {
|
||||||
|
return apiFetch(`/api/cameras/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(snapshotId)}/neighbors`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Snapshot bytes as an object URL. Fetched (not an <img src>) so it works in the
|
||||||
|
* desktop shell too, whose webview does not carry the session cookie. The caller
|
||||||
|
* revokes the URL. */
|
||||||
|
export async function fetchSnapshotObjectUrl(id: string): Promise<string> {
|
||||||
|
const res = await platformFetch(apiUrl(`/api/snapshots/${encodeURIComponent(id)}`), { credentials: "include" });
|
||||||
|
if (!res.ok) throw new ApiError(`/api/snapshots/${id}: ${res.status}`, res.status);
|
||||||
|
return URL.createObjectURL(await res.blob());
|
||||||
|
}
|
||||||
|
|
||||||
/** Edit MY own profile (display name / email). Returns the refreshed session.
|
/** Edit MY own profile (display name / email). Returns the refreshed session.
|
||||||
* Self-service — touches only the signed-in user; no `user:*` permission needed. */
|
* Self-service — touches only the signed-in user; no `user:*` permission needed. */
|
||||||
export function updateMyProfile(patch: {
|
export function updateMyProfile(patch: {
|
||||||
@@ -1102,6 +1143,10 @@ export interface ShiftSourceSplit {
|
|||||||
/** Module money that rode this till's tickets (a booth-paid wash), by module id.
|
/** Module money that rode this till's tickets (a booth-paid wash), by module id.
|
||||||
* Inside cash+card, OUTSIDE the ticket bucket. Absent on pre-2026-09 reports. */
|
* Inside cash+card, OUTSIDE the ticket bucket. Absent on pre-2026-09 reports. */
|
||||||
chargesByModuleMinor?: Partial<Record<string, number>>;
|
chargesByModuleMinor?: Partial<Record<string, number>>;
|
||||||
|
/** Forgiven exits (wiki/decisions/forgiven-exit.md): fees an operator waived, and how
|
||||||
|
* many. $0 payments — NOT inside cash/card. Absent on pre-2026-10 reports. */
|
||||||
|
forgoneTotalMinor?: number;
|
||||||
|
forgoneCount?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ShiftReport extends ShiftSourceSplit {
|
export interface ShiftReport extends ShiftSourceSplit {
|
||||||
@@ -1448,6 +1493,16 @@ export function reopenBarrier(identity: string): Promise<{ ok: true; opened: boo
|
|||||||
return apiFetch("/api/barrier/reopen", { method: "POST", body: JSON.stringify({ identity }) });
|
return apiFetch("/api/barrier/reopen", { method: "POST", body: JSON.stringify({ identity }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** FORGIVEN exit (barrier:create): open the exit with NO payment. With a ticket the fee
|
||||||
|
* owed is signed as forgone on a $0 payment; with `identity` null the car has no
|
||||||
|
* session (anomaly + snapshot + pulse). `note` is the mandatory reason. Prints nothing. */
|
||||||
|
export function forgiveExit(
|
||||||
|
identity: string | null,
|
||||||
|
note: string,
|
||||||
|
): Promise<{ ok: true; opened: boolean; reason?: string; forgoneMinor?: number; currency?: string }> {
|
||||||
|
return apiFetch("/api/barrier/forgive", { method: "POST", body: JSON.stringify({ ...(identity ? { identity } : {}), note }) });
|
||||||
|
}
|
||||||
|
|
||||||
/** Take payment for a session → signed payment event. `overrideMinor` sets an
|
/** Take payment for a session → signed payment event. `overrideMinor` sets an
|
||||||
* operator amount (lost ticket / dispute). */
|
* operator amount (lost ticket / dispute). */
|
||||||
export function paySession(
|
export function paySession(
|
||||||
|
|||||||
@@ -269,6 +269,22 @@ export const en: Catalog = {
|
|||||||
clickForIssues: "Click for details",
|
clickForIssues: "Click for details",
|
||||||
checkedAt: "checked {{time}}",
|
checkedAt: "checked {{time}}",
|
||||||
},
|
},
|
||||||
|
camera: {
|
||||||
|
expand: "Show larger",
|
||||||
|
snapshot: "Snapshot",
|
||||||
|
liveOnDemand: "Live on-demand",
|
||||||
|
live: "Live",
|
||||||
|
showTile: "Show this camera",
|
||||||
|
hideTile: "Hide this camera",
|
||||||
|
noSnapshot: "No snapshot yet",
|
||||||
|
idle: "Live view starts when a vehicle arrives",
|
||||||
|
connecting: "Connecting to live video…",
|
||||||
|
liveUnavailable: "Live video unavailable",
|
||||||
|
vehicleInView: "Vehicle in view",
|
||||||
|
older: "Older snapshot",
|
||||||
|
newer: "Newer snapshot",
|
||||||
|
snapshotUnavailable: "Snapshot unavailable",
|
||||||
|
},
|
||||||
booth: {
|
booth: {
|
||||||
processTicket: "Process ticket",
|
processTicket: "Process ticket",
|
||||||
scanPlaceholder: "Scan or type ticket number…",
|
scanPlaceholder: "Scan or type ticket number…",
|
||||||
@@ -317,6 +333,16 @@ export const en: Catalog = {
|
|||||||
issueEntryTitle: "Issue an entry ticket & open the barrier (physical button broken)",
|
issueEntryTitle: "Issue an entry ticket & open the barrier (physical button broken)",
|
||||||
issueEntryConfirm: "A vehicle is at the entry. Issue an entry ticket and open the barrier?",
|
issueEntryConfirm: "A vehicle is at the entry. Issue an entry ticket and open the barrier?",
|
||||||
issueEntryOk: "Entry ticket {{ticket}} issued.",
|
issueEntryOk: "Entry ticket {{ticket}} issued.",
|
||||||
|
forgiveExit: "Manual Exit",
|
||||||
|
forgiveExitTitle: "Open the exit barrier for a car with NO ticket — no money, signed and flagged",
|
||||||
|
forgiveExitOk: "Exit opened manually, no payment.",
|
||||||
|
forgiveExitNotOpened: "Recorded, but the barrier did not open: {{reason}}",
|
||||||
|
forgiveDialogTitle: "Manual exit",
|
||||||
|
forgiveDialogBody: "Opens the EXIT barrier for a car with no ticket. No money is taken and nothing is printed; the open is signed under your name with the exit camera's snapshot and shows on your shift report.",
|
||||||
|
forgiveDialogReason: "Reason (optional)",
|
||||||
|
forgiveDialogReasonPlaceholder: "e.g. came in while the barriers were up…",
|
||||||
|
forgiveDialogConfirm: "Open exit — no payment",
|
||||||
|
forgiveDialogWorking: "opening…",
|
||||||
exitedGrace: "exited · grace",
|
exitedGrace: "exited · grace",
|
||||||
exitedGraceLeft: "exited · {{time}}",
|
exitedGraceLeft: "exited · {{time}}",
|
||||||
exitedGraceTitle: "Paid and exited — barrier not confirmed; waiting out the grace period.",
|
exitedGraceTitle: "Paid and exited — barrier not confirmed; waiting out the grace period.",
|
||||||
@@ -419,6 +445,8 @@ export const en: Catalog = {
|
|||||||
"exit.open.failed": "Exit recorded, but the barrier did not open — open manually",
|
"exit.open.failed": "Exit recorded, but the barrier did not open — open manually",
|
||||||
"exit.freeGrace": "Free entry-grace (no charge)",
|
"exit.freeGrace": "Free entry-grace (no charge)",
|
||||||
"exit.manualOpen": "Manual barrier open (human intervention)",
|
"exit.manualOpen": "Manual barrier open (human intervention)",
|
||||||
|
"exit.forgiven": "Manual exit by {{operator}} — fee of {{forgone}} {{currency}}, no payment: {{note}}",
|
||||||
|
"exit.forgiven.noSession": "Manual exit by {{operator}} — no ticket / no session: {{note}}",
|
||||||
"exit.plateSwapSuspected": "Possible ticket swap — plate {{plate}} is already inside under ticket {{otherIdentity}}",
|
"exit.plateSwapSuspected": "Possible ticket swap — plate {{plate}} is already inside under ticket {{otherIdentity}}",
|
||||||
"exit.plateSwapOverride": "Operator {{operator}} released a suspected ticket-swap exit (plate {{plate}}, also open under {{otherIdentity}})",
|
"exit.plateSwapOverride": "Operator {{operator}} released a suspected ticket-swap exit (plate {{plate}}, also open under {{otherIdentity}})",
|
||||||
"sub.refused.notFound": "Subscription refused — not found",
|
"sub.refused.notFound": "Subscription refused — not found",
|
||||||
@@ -532,9 +560,9 @@ export const en: Catalog = {
|
|||||||
unbound: "unbound",
|
unbound: "unbound",
|
||||||
noDrivers: "No drivers registered.",
|
noDrivers: "No drivers registered.",
|
||||||
chooseDevice: "Choose a device…",
|
chooseDevice: "Choose a device…",
|
||||||
scan: "Scan for controllers",
|
scan: "Scan the LAN",
|
||||||
scanning: "Scanning…",
|
scanning: "Scanning…",
|
||||||
noControllersFound: "No controllers found on the LAN.",
|
noDevicesFound: "No devices found on the LAN (the booth and the device must share the device VLAN).",
|
||||||
usbNoneFound: "No USB printer found (/dev/usb/lpN) — check cable/power; the path can be typed manually.",
|
usbNoneFound: "No USB printer found (/dev/usb/lpN) — check cable/power; the path can be typed manually.",
|
||||||
usbSavedMissing: "saved — not present now",
|
usbSavedMissing: "saved — not present now",
|
||||||
use: "Use",
|
use: "Use",
|
||||||
@@ -553,7 +581,7 @@ export const en: Catalog = {
|
|||||||
chooseAddress: "Choose an address…",
|
chooseAddress: "Choose an address…",
|
||||||
onDeviceSubnet: "— on device subnet",
|
onDeviceSubnet: "— on device subnet",
|
||||||
noNicOnSubnet: "⚠ no NIC on the device's subnet — the device may not reach the backend",
|
noNicOnSubnet: "⚠ no NIC on the device's subnet — the device may not reach the backend",
|
||||||
backendIpHint: "The address this device will POST input events to.",
|
backendIpHint: "The address this device will push its events/scans to.",
|
||||||
relaysTitle: "Relays on this controller",
|
relaysTitle: "Relays on this controller",
|
||||||
relaysHint:
|
relaysHint:
|
||||||
"Each relay opens one barrier. Set its direction; for transient entry, set which input terminal the entry button is wired to.",
|
"Each relay opens one barrier. Set its direction; for transient entry, set which input terminal the entry button is wired to.",
|
||||||
@@ -598,6 +626,15 @@ export const en: Catalog = {
|
|||||||
anprHint:
|
anprHint:
|
||||||
"Read plates on this camera: the vision service reads the plate from each snapshot and records it (both entry and exit). Requires the vision service running.",
|
"Read plates on this camera: the vision service reads the plate from each snapshot and records it (both entry and exit). Requires the vision service running.",
|
||||||
anprAuto: "Auto open/close on subscriber plate",
|
anprAuto: "Auto open/close on subscriber plate",
|
||||||
|
crossingTitle: "Crossing line",
|
||||||
|
crossingHint:
|
||||||
|
"Drag across the picture to draw the line a vehicle must cross; drag an end to move it. Choose which crossing counts: A → B, B → A, or either.",
|
||||||
|
crossingDirection: "Direction",
|
||||||
|
crossingSwap: "Swap A/B",
|
||||||
|
crossingClear: "Clear",
|
||||||
|
crossingNone: "No line drawn.",
|
||||||
|
crossingWaiting: "Waiting for the camera…",
|
||||||
|
crossingSaveFirst: "Save the camera first to draw its crossing line.",
|
||||||
anprAutoHint:
|
anprAutoHint:
|
||||||
"Let THIS camera auto-open the barrier when it recognises a subscriber's plate. Turn OFF on a shared entry/exit lane's exit camera, so a car driving IN isn't auto-EXITed by its back plate (recognition still runs — only the auto-trigger is off).",
|
"Let THIS camera auto-open the barrier when it recognises a subscriber's plate. Turn OFF on a shared entry/exit lane's exit camera, so a car driving IN isn't auto-EXITed by its back plate (recognition still runs — only the auto-trigger is off).",
|
||||||
testAnpr: "Test ANPR",
|
testAnpr: "Test ANPR",
|
||||||
@@ -991,6 +1028,7 @@ export const en: Catalog = {
|
|||||||
srcSubscriptions: "Subscriptions:",
|
srcSubscriptions: "Subscriptions:",
|
||||||
srcOnTicket: "{{module}} (on ticket):",
|
srcOnTicket: "{{module}} (on ticket):",
|
||||||
srcSubWindow: "out-of-window",
|
srcSubWindow: "out-of-window",
|
||||||
|
srcForgone: "Manual exits ({{count}}):",
|
||||||
drawerSection: "— Drawer —",
|
drawerSection: "— Drawer —",
|
||||||
openingFloat: "Opening cash:",
|
openingFloat: "Opening cash:",
|
||||||
cashTaken: "Daily takings:",
|
cashTaken: "Daily takings:",
|
||||||
@@ -1039,6 +1077,7 @@ export const en: Catalog = {
|
|||||||
srcTickets: "Tickets",
|
srcTickets: "Tickets",
|
||||||
srcSubscriptions: "Subscriptions",
|
srcSubscriptions: "Subscriptions",
|
||||||
srcSubWindow: "out-of-window",
|
srcSubWindow: "out-of-window",
|
||||||
|
srcForgone: "Manual exits ({{count}})",
|
||||||
expectedDrawer: "Expected drawer",
|
expectedDrawer: "Expected drawer",
|
||||||
filterFrom: "From",
|
filterFrom: "From",
|
||||||
filterTo: "To",
|
filterTo: "To",
|
||||||
@@ -1246,6 +1285,14 @@ export const en: Catalog = {
|
|||||||
confirmCancelTicket: "Confirm cancellation",
|
confirmCancelTicket: "Confirm cancellation",
|
||||||
cancelling: "cancelling…",
|
cancelling: "cancelling…",
|
||||||
ticketCancelled: "Ticket cancelled.",
|
ticketCancelled: "Ticket cancelled.",
|
||||||
|
forgiveExit: "Open manually",
|
||||||
|
forgiveTitle: "Open this exit manually",
|
||||||
|
forgiveHint: "Lets the car out with NO payment. The fee owed ({{amount}}) is recorded as a manual exit on your shift report, not as money. A reason is optional; nothing is printed.",
|
||||||
|
forgiveReasonPlaceholder: "Reason (optional)…",
|
||||||
|
confirmForgive: "Confirm — open exit, no payment",
|
||||||
|
forgiving: "opening…",
|
||||||
|
exitForgiven: "Manual exit — {{amount}}, barrier opened.",
|
||||||
|
exitForgivenNotOpened: "Manual exit — {{amount}}, barrier did not open: {{reason}}",
|
||||||
noSnapshots: "no snapshots",
|
noSnapshots: "no snapshots",
|
||||||
loadingSnapshots: "loading snapshots…",
|
loadingSnapshots: "loading snapshots…",
|
||||||
snapEntry: "entry",
|
snapEntry: "entry",
|
||||||
|
|||||||
@@ -271,6 +271,22 @@ export const sq = {
|
|||||||
clickForIssues: "Kliko për detajet",
|
clickForIssues: "Kliko për detajet",
|
||||||
checkedAt: "kontrolluar {{time}}",
|
checkedAt: "kontrolluar {{time}}",
|
||||||
},
|
},
|
||||||
|
camera: {
|
||||||
|
expand: "Shfaq më të madhe",
|
||||||
|
snapshot: "Snapshot",
|
||||||
|
liveOnDemand: "Live on-demand",
|
||||||
|
live: "Live",
|
||||||
|
showTile: "Shfaq këtë kamerë",
|
||||||
|
hideTile: "Fshih këtë kamerë",
|
||||||
|
noSnapshot: "Ende pa snapshot",
|
||||||
|
idle: "Videoja live nis kur vjen një automjet",
|
||||||
|
connecting: "Po lidhet videoja live…",
|
||||||
|
liveUnavailable: "Videoja live nuk është e disponueshme",
|
||||||
|
vehicleInView: "Automjet në pamje",
|
||||||
|
older: "Foto më e vjetër",
|
||||||
|
newer: "Foto më e re",
|
||||||
|
snapshotUnavailable: "Fotoja nuk është e disponueshme",
|
||||||
|
},
|
||||||
booth: {
|
booth: {
|
||||||
processTicket: "Proceso biletën",
|
processTicket: "Proceso biletën",
|
||||||
scanPlaceholder: "Skano ose shkruaj numrin e biletës…",
|
scanPlaceholder: "Skano ose shkruaj numrin e biletës…",
|
||||||
@@ -319,6 +335,16 @@ export const sq = {
|
|||||||
issueEntryTitle: "Lësho një biletë hyrjeje & hap barrierën (butoni fizik i prishur)",
|
issueEntryTitle: "Lësho një biletë hyrjeje & hap barrierën (butoni fizik i prishur)",
|
||||||
issueEntryConfirm: "Një automjet është te hyrja. Të lëshohet një biletë hyrjeje dhe të hapet barriera?",
|
issueEntryConfirm: "Një automjet është te hyrja. Të lëshohet një biletë hyrjeje dhe të hapet barriera?",
|
||||||
issueEntryOk: "Bileta e hyrjes {{ticket}} u lëshua.",
|
issueEntryOk: "Bileta e hyrjes {{ticket}} u lëshua.",
|
||||||
|
forgiveExit: "Dalje Manuale",
|
||||||
|
forgiveExitTitle: "Hap barrierën e daljes manualisht — pa pagesë",
|
||||||
|
forgiveExitOk: "Dalja u hap manualisht, pa pagesë.",
|
||||||
|
forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}",
|
||||||
|
forgiveDialogTitle: "Hapje manuale",
|
||||||
|
forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me snapshot-in e kamerës së daljes dhe shfaqet në raportin e turnit tënd.",
|
||||||
|
forgiveDialogReason: "Arsyeja (opsionale)",
|
||||||
|
forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…",
|
||||||
|
forgiveDialogConfirm: "Hap daljen — pa pagesë",
|
||||||
|
forgiveDialogWorking: "duke hapur…",
|
||||||
exitedGrace: "doli · në afat",
|
exitedGrace: "doli · në afat",
|
||||||
exitedGraceLeft: "doli · {{time}}",
|
exitedGraceLeft: "doli · {{time}}",
|
||||||
exitedGraceTitle: "Paguar dhe dalur — barriera nuk u konfirmua; po pret afatin kohor.",
|
exitedGraceTitle: "Paguar dhe dalur — barriera nuk u konfirmua; po pret afatin kohor.",
|
||||||
@@ -374,7 +400,7 @@ export const sq = {
|
|||||||
edSource: "Burimi",
|
edSource: "Burimi",
|
||||||
edIdentity: "Identiteti",
|
edIdentity: "Identiteti",
|
||||||
edReason: "Arsyeja",
|
edReason: "Arsyeja",
|
||||||
edSnapshots: "Fotot",
|
edSnapshots: "Snapshot-et",
|
||||||
edPayload: "Të dhënat e nënshkruara",
|
edPayload: "Të dhënat e nënshkruara",
|
||||||
edChain: "Zinxhiri",
|
edChain: "Zinxhiri",
|
||||||
edSignature: "Nënshkrimi",
|
edSignature: "Nënshkrimi",
|
||||||
@@ -422,6 +448,8 @@ export const sq = {
|
|||||||
"exit.open.failed": "Dalja u regjistrua, por barriera nuk u hap — hape manualisht",
|
"exit.open.failed": "Dalja u regjistrua, por barriera nuk u hap — hape manualisht",
|
||||||
"exit.freeGrace": "Periudhë pa pagesë në hyrje (pa tarifë)",
|
"exit.freeGrace": "Periudhë pa pagesë në hyrje (pa tarifë)",
|
||||||
"exit.manualOpen": "Hapje manuale e barrierës (ndërhyrje njerëzore)",
|
"exit.manualOpen": "Hapje manuale e barrierës (ndërhyrje njerëzore)",
|
||||||
|
"exit.forgiven": "Dalje manuale nga {{operator}} — tarifa {{forgone}} {{currency}}: {{note}}",
|
||||||
|
"exit.forgiven.noSession": "Dalje manuale nga {{operator}} — pa biletë / pa seancë: {{note}}",
|
||||||
"exit.plateSwapSuspected": "Mundësi ndërrimi biletash — targa {{plate}} është tashmë brenda me biletën {{otherIdentity}}",
|
"exit.plateSwapSuspected": "Mundësi ndërrimi biletash — targa {{plate}} është tashmë brenda me biletën {{otherIdentity}}",
|
||||||
"exit.plateSwapOverride": "Operatori {{operator}} lëshoi një dalje me dyshim ndërrimi biletash (targa {{plate}}, edhe e hapur me {{otherIdentity}})",
|
"exit.plateSwapOverride": "Operatori {{operator}} lëshoi një dalje me dyshim ndërrimi biletash (targa {{plate}}, edhe e hapur me {{otherIdentity}})",
|
||||||
"sub.refused.notFound": "Abonimi u refuzua — nuk u gjet",
|
"sub.refused.notFound": "Abonimi u refuzua — nuk u gjet",
|
||||||
@@ -508,7 +536,7 @@ export const sq = {
|
|||||||
// Category titles + the singular noun used in buttons/modal titles.
|
// Category titles + the singular noun used in buttons/modal titles.
|
||||||
catControllers: "Kontrollerat (barrierat + butoni i hyrjes)",
|
catControllers: "Kontrollerat (barrierat + butoni i hyrjes)",
|
||||||
catReaders: "Lexuesit (QR / RFID)",
|
catReaders: "Lexuesit (QR / RFID)",
|
||||||
catCameras: "Kamerat (foto + targë)",
|
catCameras: "Kamerat (snapshot + targë)",
|
||||||
catPrinters: "Printerat (bileta / vouchera)",
|
catPrinters: "Printerat (bileta / vouchera)",
|
||||||
nounController: "kontroller",
|
nounController: "kontroller",
|
||||||
nounReader: "lexues",
|
nounReader: "lexues",
|
||||||
@@ -540,9 +568,9 @@ export const sq = {
|
|||||||
// Device form.
|
// Device form.
|
||||||
noDrivers: "Asnjë drejtues i regjistruar.",
|
noDrivers: "Asnjë drejtues i regjistruar.",
|
||||||
chooseDevice: "Zgjidh një pajisje…",
|
chooseDevice: "Zgjidh një pajisje…",
|
||||||
scan: "Skano për kontroller",
|
scan: "Skano LAN-in",
|
||||||
scanning: "Duke skanuar…",
|
scanning: "Duke skanuar…",
|
||||||
noControllersFound: "Asnjë kontroller në LAN.",
|
noDevicesFound: "Asnjë pajisje në LAN (kabina dhe pajisja duhet të jenë në të njëjtin VLAN).",
|
||||||
usbNoneFound: "Nuk u gjet asnjë printer USB (/dev/usb/lpN) — kontrollo kabllon/ushqimin; rruga mund të shkruhet me dorë.",
|
usbNoneFound: "Nuk u gjet asnjë printer USB (/dev/usb/lpN) — kontrollo kabllon/ushqimin; rruga mund të shkruhet me dorë.",
|
||||||
usbSavedMissing: "i ruajtur — jo i pranishëm tani",
|
usbSavedMissing: "i ruajtur — jo i pranishëm tani",
|
||||||
use: "Përdor",
|
use: "Përdor",
|
||||||
@@ -561,7 +589,7 @@ export const sq = {
|
|||||||
chooseAddress: "Zgjidh një adresë…",
|
chooseAddress: "Zgjidh një adresë…",
|
||||||
onDeviceSubnet: "— në subnetin e pajisjes",
|
onDeviceSubnet: "— në subnetin e pajisjes",
|
||||||
noNicOnSubnet: "⚠ asnjë NIC në subnetin e pajisjes — pajisja mund të mos arrijë backend-in",
|
noNicOnSubnet: "⚠ asnjë NIC në subnetin e pajisjes — pajisja mund të mos arrijë backend-in",
|
||||||
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet e hyrjes.",
|
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet/skanimet.",
|
||||||
// Relay editor.
|
// Relay editor.
|
||||||
relaysTitle: "Relet në këtë kontroller",
|
relaysTitle: "Relet në këtë kontroller",
|
||||||
relaysHint:
|
relaysHint:
|
||||||
@@ -608,6 +636,15 @@ export const sq = {
|
|||||||
anprHint:
|
anprHint:
|
||||||
"Lexo targat në këtë aparat: shërbimi i vizionit lexon targën nga çdo pamje dhe e regjistron (hyrje dhe dalje). Kërkon shërbimin e vizionit aktiv.",
|
"Lexo targat në këtë aparat: shërbimi i vizionit lexon targën nga çdo pamje dhe e regjistron (hyrje dhe dalje). Kërkon shërbimin e vizionit aktiv.",
|
||||||
anprAuto: "Hapje/mbyllje automatike me targën e abonentit",
|
anprAuto: "Hapje/mbyllje automatike me targën e abonentit",
|
||||||
|
crossingTitle: "Vija e kalimit",
|
||||||
|
crossingHint:
|
||||||
|
"Tërhiq mbi pamje për të vizatuar vijën që duhet të kalojë mjeti; tërhiq një skaj për ta lëvizur. Zgjidh cili kalim numërohet: A → B, B → A, ose të dyja.",
|
||||||
|
crossingDirection: "Drejtimi",
|
||||||
|
crossingSwap: "Ndërro A/B",
|
||||||
|
crossingClear: "Pastro",
|
||||||
|
crossingNone: "Nuk ka vijë të vizatuar.",
|
||||||
|
crossingWaiting: "Në pritje të kamerës…",
|
||||||
|
crossingSaveFirst: "Ruaje kamerën fillimisht për të vizatuar vijën e kalimit.",
|
||||||
anprAutoHint:
|
anprAutoHint:
|
||||||
"Lejo që KY aparat të hapë vetë barrierën kur njeh targën e një abonenti. ÇAKTIVIZOJE te aparati i daljes në një korsi të përbashkët hyrje/dalje, që një makinë që HYN të mos DALË automatikisht nga targa e pasme (njohja vazhdon — fiket vetëm hapja automatike).",
|
"Lejo që KY aparat të hapë vetë barrierën kur njeh targën e një abonenti. ÇAKTIVIZOJE te aparati i daljes në një korsi të përbashkët hyrje/dalje, që një makinë që HYN të mos DALË automatikisht nga targa e pasme (njohja vazhdon — fiket vetëm hapja automatike).",
|
||||||
testAnpr: "Testo ANPR",
|
testAnpr: "Testo ANPR",
|
||||||
@@ -849,7 +886,7 @@ export const sq = {
|
|||||||
reserveSubs: "Rezervo vendet e abonentëve",
|
reserveSubs: "Rezervo vendet e abonentëve",
|
||||||
reserveSubsHint: "Mban një vend për makinat e çdo abonenti aktiv edhe kur nuk janë të parkuar — kalimtarët e shohin 'plot' më shpejt. Joaktiv: numërohen vetëm makinat brenda (mbingarkesa menaxhohet me parkim manual).",
|
reserveSubsHint: "Mban një vend për makinat e çdo abonenti aktiv edhe kur nuk janë të parkuar — kalimtarët e shohin 'plot' më shpejt. Joaktiv: numërohen vetëm makinat brenda (mbingarkesa menaxhohet me parkim manual).",
|
||||||
anprEntry: "Hapje automatike për targat e abonentëve (ANPR)",
|
anprEntry: "Hapje automatike për targat e abonentëve (ANPR)",
|
||||||
anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Fotot e targave regjistrohen gjithsesi.",
|
anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Snapshot-et e targave regjistrohen gjithsesi.",
|
||||||
parkDetails: "Të dhënat e parkimit (opsionale — shfaqen në bileta/fatura)",
|
parkDetails: "Të dhënat e parkimit (opsionale — shfaqen në bileta/fatura)",
|
||||||
save: "Ruaj",
|
save: "Ruaj",
|
||||||
saved: "U ruajt.",
|
saved: "U ruajt.",
|
||||||
@@ -1004,6 +1041,7 @@ export const sq = {
|
|||||||
srcSubscriptions: "Abonime:",
|
srcSubscriptions: "Abonime:",
|
||||||
srcOnTicket: "{{module}} (në biletë):",
|
srcOnTicket: "{{module}} (në biletë):",
|
||||||
srcSubWindow: "jashtë orarit",
|
srcSubWindow: "jashtë orarit",
|
||||||
|
srcForgone: "Dalje manuale ({{count}}):",
|
||||||
drawerSection: "— Arka —",
|
drawerSection: "— Arka —",
|
||||||
openingFloat: "Arka fillestare:",
|
openingFloat: "Arka fillestare:",
|
||||||
cashTaken: "Xhiro ditore:",
|
cashTaken: "Xhiro ditore:",
|
||||||
@@ -1052,6 +1090,7 @@ export const sq = {
|
|||||||
srcTickets: "Bileta",
|
srcTickets: "Bileta",
|
||||||
srcSubscriptions: "Abonime",
|
srcSubscriptions: "Abonime",
|
||||||
srcSubWindow: "jashtë orarit",
|
srcSubWindow: "jashtë orarit",
|
||||||
|
srcForgone: "Dalje manuale ({{count}})",
|
||||||
expectedDrawer: "Gjëndje arke",
|
expectedDrawer: "Gjëndje arke",
|
||||||
// Filter (admin only).
|
// Filter (admin only).
|
||||||
filterFrom: "Nga",
|
filterFrom: "Nga",
|
||||||
@@ -1262,9 +1301,17 @@ export const sq = {
|
|||||||
confirmCancelTicket: "Konfirmo anulimin",
|
confirmCancelTicket: "Konfirmo anulimin",
|
||||||
cancelling: "duke anuluar…",
|
cancelling: "duke anuluar…",
|
||||||
ticketCancelled: "Bileta u anulua.",
|
ticketCancelled: "Bileta u anulua.",
|
||||||
|
forgiveExit: "Hap Manualisht",
|
||||||
|
forgiveTitle: "Hap manualisht këtë dalje",
|
||||||
|
forgiveHint: "E lë automjetin të dalë PA pagesë. Shuma e detyruar ({{amount}}) regjistrohet si dalje manuale në raportin e turnit, jo si para. Arsyeja është opsionale; nuk printohet asgjë.",
|
||||||
|
forgiveReasonPlaceholder: "Arsyeja (opsionale)…",
|
||||||
|
confirmForgive: "Konfirmo — hap daljen, pa pagesë",
|
||||||
|
forgiving: "duke hapur…",
|
||||||
|
exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.",
|
||||||
|
exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}",
|
||||||
// snapshots
|
// snapshots
|
||||||
noSnapshots: "asnjë foto",
|
noSnapshots: "asnjë snapshot",
|
||||||
loadingSnapshots: "duke ngarkuar fotot…",
|
loadingSnapshots: "duke ngarkuar snapshot-et…",
|
||||||
snapEntry: "hyrje",
|
snapEntry: "hyrje",
|
||||||
snapExit: "dalje",
|
snapExit: "dalje",
|
||||||
snapFailed: "kamera e paarritshme",
|
snapFailed: "kamera e paarritshme",
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ interface LiveState {
|
|||||||
lanes: LaneStatus | null;
|
lanes: LaneStatus | null;
|
||||||
/** Per-lane radar presence (advisory blink). Null until the first WS hello. */
|
/** Per-lane radar presence (advisory blink). Null until the first WS hello. */
|
||||||
radar: LanePresence | null;
|
radar: LanePresence | null;
|
||||||
|
/** Camera ids currently seeing a vehicle — their booth tiles show live video. */
|
||||||
|
activeCameras: Record<string, true>;
|
||||||
setStatus: (s: WsStatus) => void;
|
setStatus: (s: WsStatus) => void;
|
||||||
setOccupancy: (o: Occupancy) => void;
|
setOccupancy: (o: Occupancy) => void;
|
||||||
pushEvent: (e: LedgerEvent) => void;
|
pushEvent: (e: LedgerEvent) => void;
|
||||||
@@ -52,6 +54,10 @@ interface LiveState {
|
|||||||
setLanes: (l: LaneStatus) => void;
|
setLanes: (l: LaneStatus) => void;
|
||||||
/** Set lane radar presence (WS hello + each lane-presence push). */
|
/** Set lane radar presence (WS hello + each lane-presence push). */
|
||||||
setRadar: (r: LanePresence) => void;
|
setRadar: (r: LanePresence) => void;
|
||||||
|
/** Replace the active-camera set (WS hello). */
|
||||||
|
setActiveCameras: (ids: string[]) => void;
|
||||||
|
/** One camera started/stopped seeing a vehicle (WS camera-activity push). */
|
||||||
|
setCameraActive: (id: string, active: boolean) => void;
|
||||||
/** Backfill the enriched plate on every feed event matching `identity` (a late async
|
/** Backfill the enriched plate on every feed event matching `identity` (a late async
|
||||||
* recognition that landed after the event's own push). No-op if no row matches. */
|
* recognition that landed after the event's own push). No-op if no row matches. */
|
||||||
patchPlate: (identity: string, plate: string) => void;
|
patchPlate: (identity: string, plate: string) => void;
|
||||||
@@ -70,6 +76,7 @@ export const useLiveStore = create<LiveState>((set) => ({
|
|||||||
occupancy: null,
|
occupancy: null,
|
||||||
feed: [],
|
feed: [],
|
||||||
devices: {},
|
devices: {},
|
||||||
|
activeCameras: {},
|
||||||
lanes: null,
|
lanes: null,
|
||||||
radar: null,
|
radar: null,
|
||||||
setStatus: (status) => set({ status }),
|
setStatus: (status) => set({ status }),
|
||||||
@@ -83,10 +90,18 @@ export const useLiveStore = create<LiveState>((set) => ({
|
|||||||
upsertDevice: (d) => set((s) => ({ devices: { ...s.devices, [d.deviceId]: d } })),
|
upsertDevice: (d) => set((s) => ({ devices: { ...s.devices, [d.deviceId]: d } })),
|
||||||
setLanes: (lanes) => set({ lanes }),
|
setLanes: (lanes) => set({ lanes }),
|
||||||
setRadar: (radar) => set({ radar }),
|
setRadar: (radar) => set({ radar }),
|
||||||
|
setActiveCameras: (ids) => set({ activeCameras: Object.fromEntries(ids.map((id) => [id, true as const])) }),
|
||||||
|
setCameraActive: (id, active) =>
|
||||||
|
set((st) => {
|
||||||
|
const next = { ...st.activeCameras };
|
||||||
|
if (active) next[id] = true;
|
||||||
|
else delete next[id];
|
||||||
|
return { activeCameras: next };
|
||||||
|
}),
|
||||||
patchPlate: (identity, plate) =>
|
patchPlate: (identity, plate) =>
|
||||||
set((s) => {
|
set((s) => {
|
||||||
if (!s.feed.some((e) => e.identity === identity && !e.plate)) return s; // nothing to fill
|
if (!s.feed.some((e) => e.identity === identity && !e.plate)) return s; // nothing to fill
|
||||||
return { feed: s.feed.map((e) => (e.identity === identity && !e.plate ? { ...e, plate } : e)) };
|
return { feed: s.feed.map((e) => (e.identity === identity && !e.plate ? { ...e, plate } : e)) };
|
||||||
}),
|
}),
|
||||||
reset: () => set({ status: "connecting", occupancy: null, feed: [], devices: {}, lanes: null, radar: null }),
|
reset: () => set({ status: "connecting", occupancy: null, feed: [], devices: {}, lanes: null, radar: null, activeCameras: {} }),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -27,9 +27,12 @@ import { inTauri } from "./tauri-env.js";
|
|||||||
const CONNECT_FAIL_LOG_INTERVAL_MS = 60_000;
|
const CONNECT_FAIL_LOG_INTERVAL_MS = 60_000;
|
||||||
let lastConnectFailLogAt = 0;
|
let lastConnectFailLogAt = 0;
|
||||||
|
|
||||||
|
/** A text frame arrives as a string, a binary frame (camera JPEG) as an ArrayBuffer. */
|
||||||
|
export type PlatformMessage = { data: string | ArrayBuffer };
|
||||||
|
|
||||||
export interface PlatformSocket {
|
export interface PlatformSocket {
|
||||||
onopen: (() => void) | null;
|
onopen: (() => void) | null;
|
||||||
onmessage: ((ev: { data: string }) => void) | null;
|
onmessage: ((ev: PlatformMessage) => void) | null;
|
||||||
onclose: (() => void) | null;
|
onclose: (() => void) | null;
|
||||||
onerror: (() => void) | null;
|
onerror: (() => void) | null;
|
||||||
close(): void;
|
close(): void;
|
||||||
@@ -37,15 +40,16 @@ export interface PlatformSocket {
|
|||||||
|
|
||||||
class NativeSocketAdapter implements PlatformSocket {
|
class NativeSocketAdapter implements PlatformSocket {
|
||||||
onopen: (() => void) | null = null;
|
onopen: (() => void) | null = null;
|
||||||
onmessage: ((ev: { data: string }) => void) | null = null;
|
onmessage: ((ev: PlatformMessage) => void) | null = null;
|
||||||
onclose: (() => void) | null = null;
|
onclose: (() => void) | null = null;
|
||||||
onerror: (() => void) | null = null;
|
onerror: (() => void) | null = null;
|
||||||
#sock: WebSocket;
|
#sock: WebSocket;
|
||||||
|
|
||||||
constructor(url: string) {
|
constructor(url: string) {
|
||||||
this.#sock = new WebSocket(url);
|
this.#sock = new WebSocket(url);
|
||||||
|
this.#sock.binaryType = "arraybuffer";
|
||||||
this.#sock.onopen = () => this.onopen?.();
|
this.#sock.onopen = () => this.onopen?.();
|
||||||
this.#sock.onmessage = (ev) => this.onmessage?.({ data: ev.data as string });
|
this.#sock.onmessage = (ev) => this.onmessage?.({ data: ev.data as string | ArrayBuffer });
|
||||||
this.#sock.onclose = () => this.onclose?.();
|
this.#sock.onclose = () => this.onclose?.();
|
||||||
this.#sock.onerror = () => this.onerror?.();
|
this.#sock.onerror = () => this.onerror?.();
|
||||||
}
|
}
|
||||||
@@ -55,22 +59,49 @@ class NativeSocketAdapter implements PlatformSocket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type NativeMsg = { type: string; data: unknown };
|
||||||
|
|
||||||
class TauriSocketAdapter implements PlatformSocket {
|
class TauriSocketAdapter implements PlatformSocket {
|
||||||
onopen: (() => void) | null = null;
|
onopen: (() => void) | null = null;
|
||||||
onmessage: ((ev: { data: string }) => void) | null = null;
|
onmessage: ((ev: PlatformMessage) => void) | null = null;
|
||||||
onclose: (() => void) | null = null;
|
onclose: (() => void) | null = null;
|
||||||
onerror: (() => void) | null = null;
|
onerror: (() => void) | null = null;
|
||||||
#closed = false;
|
#closed = false;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
#id: number | null = null;
|
||||||
#conn: any = null;
|
// Frames that arrive before connect() resolves, delivered right after onopen.
|
||||||
|
#early: NativeMsg[] | null = [];
|
||||||
|
|
||||||
constructor(url: string) {
|
constructor(url: string) {
|
||||||
void this.#connect(url);
|
void this.#connect(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#deliver(msg: NativeMsg): void {
|
||||||
|
if (this.#closed) return;
|
||||||
|
if (this.#early) {
|
||||||
|
this.#early.push(msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.type === "Text") {
|
||||||
|
this.onmessage?.({ data: msg.data as string });
|
||||||
|
} else if (msg.type === "Binary") {
|
||||||
|
// Camera live view (routes/cameras.ts): one JPEG per binary message. The
|
||||||
|
// plugin hands bytes over IPC as a number array.
|
||||||
|
this.onmessage?.({ data: new Uint8Array(msg.data as number[]).buffer });
|
||||||
|
} else if (msg.type === "Close") {
|
||||||
|
this.onclose?.();
|
||||||
|
}
|
||||||
|
// Ping/Pong: nothing to do.
|
||||||
|
}
|
||||||
|
|
||||||
async #connect(url: string): Promise<void> {
|
async #connect(url: string): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const { default: TauriWebSocket } = await import("@tauri-apps/plugin-websocket");
|
// The plugin's own JS wrapper (@tauri-apps/plugin-websocket) only lets a listener
|
||||||
|
// be added AFTER connect() resolves, but the native side starts reading at the
|
||||||
|
// handshake — so a frame the server sends at once (the live feed's `hello`, with
|
||||||
|
// the full device list) could reach an empty listener set and be lost: the desktop
|
||||||
|
// footer then showed only the devices that happened to push later (2026-11-19).
|
||||||
|
// So call the plugin's commands directly, with our channel listening from the start.
|
||||||
|
const { Channel, invoke } = await import("@tauri-apps/api/core");
|
||||||
if (this.#closed) return; // close() called before connect resolved
|
if (this.#closed) return; // close() called before connect resolved
|
||||||
// The native WS plugin is a bare tungstenite client: no page context AND
|
// The native WS plugin is a bare tungstenite client: no page context AND
|
||||||
// no cookie jar. Two consequences, both handled via explicit headers:
|
// no cookie jar. Two consequences, both handled via explicit headers:
|
||||||
@@ -84,24 +115,22 @@ class TauriSocketAdapter implements PlatformSocket {
|
|||||||
// x-ws-ticket header (see routes/ws.ts).
|
// x-ws-ticket header (see routes/ws.ts).
|
||||||
const ticket = await fetchWsTicket();
|
const ticket = await fetchWsTicket();
|
||||||
if (this.#closed) return;
|
if (this.#closed) return;
|
||||||
const conn = await TauriWebSocket.connect(url, {
|
const onMessage = new Channel<NativeMsg>();
|
||||||
headers: { Origin: "tauri://localhost", "x-ws-ticket": ticket },
|
onMessage.onmessage = (msg) => this.#deliver(msg);
|
||||||
|
const id = await invoke<number>("plugin:websocket|connect", {
|
||||||
|
url,
|
||||||
|
onMessage,
|
||||||
|
config: { headers: [["Origin", "tauri://localhost"], ["x-ws-ticket", ticket]] },
|
||||||
});
|
});
|
||||||
|
this.#id = id;
|
||||||
if (this.#closed) {
|
if (this.#closed) {
|
||||||
void conn.disconnect();
|
this.#disconnect();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.#conn = conn;
|
|
||||||
conn.addListener((msg: { type: string; data: unknown }) => {
|
|
||||||
if (msg.type === "Text") {
|
|
||||||
this.onmessage?.({ data: msg.data as string });
|
|
||||||
} else if (msg.type === "Close") {
|
|
||||||
this.onclose?.();
|
|
||||||
}
|
|
||||||
// Binary/Ping/Pong: the server protocol here is text-JSON only (see
|
|
||||||
// routes/ws.ts) — nothing else is expected.
|
|
||||||
});
|
|
||||||
this.onopen?.();
|
this.onopen?.();
|
||||||
|
const early = this.#early ?? [];
|
||||||
|
this.#early = null;
|
||||||
|
for (const msg of early) this.#deliver(msg);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// logClient, not console.error: console output only reaches app_logs at
|
// logClient, not console.error: console output only reaches app_logs at
|
||||||
// debug/trace level, which is how the ticket-less 401 stayed invisible
|
// debug/trace level, which is how the ticket-less 401 stayed invisible
|
||||||
@@ -119,9 +148,23 @@ class TauriSocketAdapter implements PlatformSocket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#disconnect(): void {
|
||||||
|
if (this.#id == null) return;
|
||||||
|
void import("@tauri-apps/api/core")
|
||||||
|
.then(({ invoke }) =>
|
||||||
|
invoke("plugin:websocket|send", {
|
||||||
|
id: this.#id,
|
||||||
|
message: { type: "Close", data: { code: 1000, reason: "Disconnected by client" } },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.catch(() => {
|
||||||
|
/* already gone */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
close(): void {
|
close(): void {
|
||||||
this.#closed = true;
|
this.#closed = true;
|
||||||
void this.#conn?.disconnect();
|
this.#disconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,12 +16,13 @@ import { createPlatformSocket, type PlatformSocket } from "./platform-ws.js";
|
|||||||
/** Server → client message shapes (mirror routes/ws.ts OutMsg). */
|
/** Server → client message shapes (mirror routes/ws.ts OutMsg). */
|
||||||
type WsMessage =
|
type WsMessage =
|
||||||
// Parts a role may not see arrive as null (the server filters per role — ws.ts).
|
// Parts a role may not see arrive as null (the server filters per role — ws.ts).
|
||||||
| { kind: "hello"; occupancy: Occupancy | null; devices: DeviceStatus[] | null; lanes: LaneStatus | null; radar: LanePresence | null }
|
| { kind: "hello"; occupancy: Occupancy | null; devices: DeviceStatus[] | null; lanes: LaneStatus | null; radar: LanePresence | null; cameras: string[] | null }
|
||||||
| { kind: "ledger"; event: LedgerEvent; occupancy: Occupancy | null }
|
| { kind: "ledger"; event: LedgerEvent; occupancy: Occupancy | null }
|
||||||
| { kind: "printer-status"; event: unknown }
|
| { kind: "printer-status"; event: unknown }
|
||||||
| { kind: "device-status"; event: DeviceStatus }
|
| { kind: "device-status"; event: DeviceStatus }
|
||||||
| { kind: "lane-status"; lanes: LaneStatus }
|
| { kind: "lane-status"; lanes: LaneStatus }
|
||||||
| { kind: "lane-presence"; radar: LanePresence }
|
| { kind: "lane-presence"; radar: LanePresence }
|
||||||
|
| { kind: "camera-activity"; camera: { deviceId: string; active: boolean } }
|
||||||
| { kind: "plate-recognized"; plate: { identity: string; plate: string; direction: "entry" | "exit" } };
|
| { kind: "plate-recognized"; plate: { identity: string; plate: string; direction: "entry" | "exit" } };
|
||||||
|
|
||||||
|
|
||||||
@@ -34,8 +35,18 @@ type WsMessage =
|
|||||||
*/
|
*/
|
||||||
export function useLiveFeed(enabled: boolean = true): void {
|
export function useLiveFeed(enabled: boolean = true): void {
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const { setStatus, setOccupancy, pushEvent, setDevices, upsertDevice, setLanes, setRadar, patchPlate } =
|
const {
|
||||||
useLiveStore();
|
setStatus,
|
||||||
|
setOccupancy,
|
||||||
|
pushEvent,
|
||||||
|
setDevices,
|
||||||
|
upsertDevice,
|
||||||
|
setLanes,
|
||||||
|
setRadar,
|
||||||
|
patchPlate,
|
||||||
|
setActiveCameras,
|
||||||
|
setCameraActive,
|
||||||
|
} = useLiveStore();
|
||||||
// Hold the socket + reconnect timer across renders; guard against StrictMode
|
// Hold the socket + reconnect timer across renders; guard against StrictMode
|
||||||
// double-invoke and unmount.
|
// double-invoke and unmount.
|
||||||
const sockRef = useRef<PlatformSocket | null>(null);
|
const sockRef = useRef<PlatformSocket | null>(null);
|
||||||
@@ -73,6 +84,12 @@ export function useLiveFeed(enabled: boolean = true): void {
|
|||||||
if (Array.isArray(msg.devices)) setDevices(msg.devices);
|
if (Array.isArray(msg.devices)) setDevices(msg.devices);
|
||||||
if (msg.lanes) setLanes(msg.lanes);
|
if (msg.lanes) setLanes(msg.lanes);
|
||||||
if (msg.radar) setRadar(msg.radar);
|
if (msg.radar) setRadar(msg.radar);
|
||||||
|
if (Array.isArray(msg.cameras)) setActiveCameras(msg.cameras);
|
||||||
|
} else if (msg.kind === "camera-activity") {
|
||||||
|
setCameraActive(msg.camera.deviceId, msg.camera.active);
|
||||||
|
// Live ended → the tile falls back to the newest snapshot, which this car
|
||||||
|
// may just have produced.
|
||||||
|
if (!msg.camera.active) void qc.invalidateQueries({ queryKey: ["camera-latest", msg.camera.deviceId] });
|
||||||
} else if (msg.kind === "device-status") {
|
} else if (msg.kind === "device-status") {
|
||||||
upsertDevice(msg.event);
|
upsertDevice(msg.event);
|
||||||
} else if (msg.kind === "lane-status") {
|
} else if (msg.kind === "lane-status") {
|
||||||
@@ -93,6 +110,12 @@ export function useLiveFeed(enabled: boolean = true): void {
|
|||||||
void qc.invalidateQueries({ queryKey: qk.events });
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
void qc.invalidateQueries({ queryKey: qk.occupancy });
|
void qc.invalidateQueries({ queryKey: qk.occupancy });
|
||||||
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
||||||
|
// An entry/exit is followed by a fresh camera snapshot → the camera tiles'
|
||||||
|
// picture. The snapshot is stored AFTER the signed event (entry-flow.ts), so
|
||||||
|
// refetch a moment later; the idle edge (camera-activity) refetches again.
|
||||||
|
if (msg.event.type === "vehicle_entry" || msg.event.type === "vehicle_exit") {
|
||||||
|
window.setTimeout(() => void qc.invalidateQueries({ queryKey: ["camera-latest"] }), 4000);
|
||||||
|
}
|
||||||
// A shift open/close (or a drawer movement) changes the header control
|
// A shift open/close (or a drawer movement) changes the header control
|
||||||
// state and the per-shift log window — refresh the shift status too.
|
// state and the per-shift log window — refresh the shift status too.
|
||||||
if (
|
if (
|
||||||
@@ -113,6 +136,10 @@ export function useLiveFeed(enabled: boolean = true): void {
|
|||||||
const scheduleReconnect = () => {
|
const scheduleReconnect = () => {
|
||||||
if (closedRef.current) return;
|
if (closedRef.current) return;
|
||||||
setStatus("closed");
|
setStatus("closed");
|
||||||
|
// Camera activity is only known while the feed is up: without this a tile would
|
||||||
|
// stay "live" and re-dial its camera for the whole outage. The hello on reconnect
|
||||||
|
// restores the real set.
|
||||||
|
setActiveCameras([]);
|
||||||
// Capped exponential backoff: 0.5s, 1s, 2s, … up to 10s.
|
// Capped exponential backoff: 0.5s, 1s, 2s, … up to 10s.
|
||||||
const delay = Math.min(500 * 2 ** retryRef.current, 10_000);
|
const delay = Math.min(500 * 2 ** retryRef.current, 10_000);
|
||||||
retryRef.current += 1;
|
retryRef.current += 1;
|
||||||
|
|||||||
+19
-1
@@ -17,6 +17,7 @@ import {
|
|||||||
setLanguagePref,
|
setLanguagePref,
|
||||||
setThemePref,
|
setThemePref,
|
||||||
setFontScalePref,
|
setFontScalePref,
|
||||||
|
setOpenCamerasPref,
|
||||||
FONT_SCALE_MIN,
|
FONT_SCALE_MIN,
|
||||||
FONT_SCALE_MAX,
|
FONT_SCALE_MAX,
|
||||||
FONT_SCALE_STEP,
|
FONT_SCALE_STEP,
|
||||||
@@ -384,6 +385,17 @@ function RootLayout() {
|
|||||||
const canWatch = canWatchFeed(user);
|
const canWatch = canWatchFeed(user);
|
||||||
useLiveFeed(canWatch);
|
useLiveFeed(canWatch);
|
||||||
|
|
||||||
|
// Booth camera tiles: a footer camera chip opens/closes its tile. The open set is a
|
||||||
|
// per-user preference (users.open_cameras), restored on login from any booth; saved
|
||||||
|
// optimistically — a failed save only means it is not remembered next time.
|
||||||
|
const toggleCamera = (deviceId: string) => {
|
||||||
|
if (!user) return;
|
||||||
|
const current: string[] = user.openCameras ?? [];
|
||||||
|
const next = current.includes(deviceId) ? current.filter((id) => id !== deviceId) : [...current, deviceId];
|
||||||
|
setUser({ ...user, openCameras: next });
|
||||||
|
void setOpenCamerasPref(next).catch(() => undefined);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen flex-col bg-term-bg text-term-text">
|
<div className="flex h-screen flex-col bg-term-bg text-term-text">
|
||||||
<header className="flex items-center gap-4 border-b border-term-border bg-term-panel px-4 py-2">
|
<header className="flex items-center gap-4 border-b border-term-border bg-term-panel px-4 py-2">
|
||||||
@@ -459,7 +471,13 @@ function RootLayout() {
|
|||||||
{/* Fixed device-status footer — relays, readers, cameras, printers. Its REST
|
{/* Fixed device-status footer — relays, readers, cameras, printers. Its REST
|
||||||
seed needs device:read (and its live updates ride the report:read WS), so
|
seed needs device:read (and its live updates ride the report:read WS), so
|
||||||
it's hidden for roles without device visibility (e.g. merchant validators). */}
|
it's hidden for roles without device visibility (e.g. merchant validators). */}
|
||||||
{user && show("device:read") && <DeviceFooter />}
|
{user && show("device:read") && (
|
||||||
|
<DeviceFooter
|
||||||
|
openCameras={user.openCameras ?? []}
|
||||||
|
onToggleCamera={toggleCamera}
|
||||||
|
canSeeSnapshots={show("session:read")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,489 @@
|
|||||||
|
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
fetchCameraSnapshotNeighbors,
|
||||||
|
fetchLatestCameraSnapshot,
|
||||||
|
fetchSnapshotObjectUrl,
|
||||||
|
type CameraSnapshotMeta,
|
||||||
|
type DeviceStatus,
|
||||||
|
} from "../api.js";
|
||||||
|
import { formatClock, formatRelativeDateTime } from "../lib/format.js";
|
||||||
|
import { useLiveStore } from "../lib/live-store.js";
|
||||||
|
import { wsUrl } from "../lib/origin.js";
|
||||||
|
import { createPlatformSocket } from "../lib/platform-ws.js";
|
||||||
|
|
||||||
|
// Booth camera tiles (wiki/decisions/camera-live-view.md). Opened from the camera
|
||||||
|
// chips in the device footer; docked bottom-right, the first opened rightmost and each
|
||||||
|
// next one to its left. A tile rests on the camera's newest entry/exit snapshot and
|
||||||
|
// switches to live video while that camera is seeing a vehicle (the server's per-camera
|
||||||
|
// activity, pushed over /api/ws). Clicking the picture opens a large view in the
|
||||||
|
// tile's state (live if the tile is live, else the snapshot), with a Live / Snapshot
|
||||||
|
// switch that streams LIVE ON DEMAND, car or no car; closing it returns the tile to
|
||||||
|
// automatic — a stream the user started stops, one the camera started carries on. On
|
||||||
|
// the Snapshot side, ‹ › step through this camera's older / newer snapshots (the tile
|
||||||
|
// itself always rests on the newest; the large view reopens on it). Live frames come over their own socket as JPEG binaries; only the newest frame is
|
||||||
|
// shown, and the tile and the large view share that one socket. Advisory viewing —
|
||||||
|
// nothing here gates anything.
|
||||||
|
|
||||||
|
type LiveState =
|
||||||
|
| { state: "connecting" }
|
||||||
|
| { state: "live" }
|
||||||
|
| { state: "retrying"; reason: string }
|
||||||
|
| { state: "unavailable"; reason: string };
|
||||||
|
|
||||||
|
/** Delay before re-opening a live socket that dropped while the camera is still active. */
|
||||||
|
const RECONNECT_MS = 2000;
|
||||||
|
|
||||||
|
export function CameraDock({
|
||||||
|
openIds,
|
||||||
|
cameras,
|
||||||
|
label,
|
||||||
|
canSeeSnapshots,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
openIds: string[];
|
||||||
|
/** Configured cameras (for labels, and to skip a tile whose camera was removed). */
|
||||||
|
cameras: DeviceStatus[];
|
||||||
|
label: (d: DeviceStatus) => string;
|
||||||
|
canSeeSnapshots: boolean;
|
||||||
|
onClose: (deviceId: string) => void;
|
||||||
|
}) {
|
||||||
|
const byId = new Map(cameras.map((c) => [c.deviceId, c]));
|
||||||
|
const shown = openIds.filter((id) => byId.has(id));
|
||||||
|
if (shown.length === 0) return null;
|
||||||
|
return (
|
||||||
|
// Above the footer; first opened rightmost (row-reverse), the next to its left.
|
||||||
|
<div className="pointer-events-none fixed bottom-9 right-2 z-40 flex flex-row-reverse items-end gap-2">
|
||||||
|
{shown.map((id) => (
|
||||||
|
<CameraTile
|
||||||
|
key={id}
|
||||||
|
deviceId={id}
|
||||||
|
title={label(byId.get(id)!)}
|
||||||
|
canSeeSnapshots={canSeeSnapshots}
|
||||||
|
onClose={() => onClose(id)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CameraTile({
|
||||||
|
deviceId,
|
||||||
|
title,
|
||||||
|
canSeeSnapshots,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
deviceId: string;
|
||||||
|
title: string;
|
||||||
|
canSeeSnapshots: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
/** The camera is reporting a vehicle (server-side activity, 30 s after its last push). */
|
||||||
|
const active = useLiveStore((s) => s.activeCameras[deviceId] === true);
|
||||||
|
/** Large view open, and what it shows (opens in the tile's state, then the user's pick). */
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
const [modalMode, setModalMode] = useState<"live" | "snapshot">("live");
|
||||||
|
// Modal open → the user's choice rules; closed → automatic (live while a vehicle is in view).
|
||||||
|
const wantLive = expanded ? modalMode === "live" : active;
|
||||||
|
const live = useLiveFrames(deviceId, wantLive);
|
||||||
|
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
|
||||||
|
const showLive = wantLive && live.hasFrame;
|
||||||
|
/** The snapshot the large view shows when the user has stepped away from the newest. */
|
||||||
|
const [browsed, setBrowsed] = useState<CameraSnapshotMeta | null>(null);
|
||||||
|
const browsedPic = useSnapshotPicture(browsed);
|
||||||
|
/** What the ‹ › step from: the snapshot asked for (its picture may still be loading). */
|
||||||
|
const modalShot = browsed ?? snapshot.meta;
|
||||||
|
const browsing = expanded && modalMode === "snapshot" && canSeeSnapshots && modalShot !== null;
|
||||||
|
const neighbors = useQuery({
|
||||||
|
// Under "camera-latest" so a new snapshot's invalidation refreshes "newer" too.
|
||||||
|
queryKey: ["camera-latest", deviceId, "neighbors", modalShot?.id],
|
||||||
|
queryFn: () => fetchCameraSnapshotNeighbors(deviceId, modalShot!.id),
|
||||||
|
enabled: browsing,
|
||||||
|
});
|
||||||
|
const nav = browsing
|
||||||
|
? { older: neighbors.data?.older ?? null, newer: neighbors.data?.newer ?? null, go: setBrowsed }
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const caption = wantLive
|
||||||
|
? showLive
|
||||||
|
? active
|
||||||
|
? t("camera.vehicleInView")
|
||||||
|
: t("camera.liveOnDemand")
|
||||||
|
: live.status.state === "unavailable" || live.status.state === "retrying"
|
||||||
|
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
|
||||||
|
: t("camera.connecting")
|
||||||
|
: snapshot.pic.meta
|
||||||
|
? `${snapshot.pic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.pic.meta.capturedAt)}`
|
||||||
|
: "";
|
||||||
|
// The large view's picture: a stepped-to snapshot once its bytes are in, the previous
|
||||||
|
// picture until then. The caption always names the picture SHOWN (these are evidence
|
||||||
|
// stills — a date must never sit under another snapshot's picture).
|
||||||
|
const modalPic = browsed ? (browsedPic.meta ? browsedPic : snapshot.pic) : snapshot.pic;
|
||||||
|
const modalCaption = wantLive
|
||||||
|
? caption
|
||||||
|
: browsed && browsedPic.failed
|
||||||
|
? t("camera.snapshotUnavailable")
|
||||||
|
: modalPic.meta
|
||||||
|
? `${modalPic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatRelativeDateTime(modalPic.meta.capturedAt, t, { seconds: true })}`
|
||||||
|
: caption;
|
||||||
|
const view = (slot: "tile" | "modal") => (
|
||||||
|
<CameraView
|
||||||
|
imgRef={live.imgRefs[slot]}
|
||||||
|
showLive={showLive}
|
||||||
|
snapshotUrl={slot === "modal" ? (browsed && browsedPic.failed ? null : modalPic.url) : snapshot.pic.url}
|
||||||
|
placeholder={
|
||||||
|
slot === "modal" && browsed && browsedPic.failed
|
||||||
|
? t("camera.snapshotUnavailable")
|
||||||
|
: canSeeSnapshots
|
||||||
|
? t("camera.noSnapshot")
|
||||||
|
: t("camera.idle")
|
||||||
|
}
|
||||||
|
caption={slot === "modal" ? modalCaption : caption}
|
||||||
|
large={slot === "modal"}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pointer-events-auto flex w-[15vw] min-w-[200px] flex-col overflow-hidden rounded-term border border-term-border bg-term-panel shadow-2xl">
|
||||||
|
<div className="flex items-center gap-2 border-b border-term-border bg-term-panel-2 px-2 py-1 text-[0.6875rem]">
|
||||||
|
<span className="min-w-0 flex-1 truncate font-semibold text-term-text">{title}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="shrink-0 text-term-muted hover:text-term-text"
|
||||||
|
aria-label={t("common.close")}
|
||||||
|
title={t("common.close")}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/* The picture is the expand control: the large view opens showing what the tile
|
||||||
|
shows. Seeded from `active`, not from "a frame has arrived", so a camera-started
|
||||||
|
stream that is still connecting is not torn down by the click. */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setModalMode(active ? "live" : "snapshot");
|
||||||
|
setExpanded(true);
|
||||||
|
}}
|
||||||
|
className="block w-full cursor-zoom-in"
|
||||||
|
title={t("camera.expand")}
|
||||||
|
aria-label={t("camera.expand")}
|
||||||
|
>
|
||||||
|
{view("tile")}
|
||||||
|
</button>
|
||||||
|
{expanded && (
|
||||||
|
<CameraModal
|
||||||
|
title={title}
|
||||||
|
mode={modalMode}
|
||||||
|
onMode={setModalMode}
|
||||||
|
nav={nav}
|
||||||
|
onClose={() => {
|
||||||
|
setExpanded(false);
|
||||||
|
setBrowsed(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{view("modal")}
|
||||||
|
</CameraModal>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The picture area shared by the tile and the large view: live frames (painted
|
||||||
|
* straight into the <img>, no re-render per frame) or the resting snapshot. */
|
||||||
|
function CameraView({
|
||||||
|
imgRef,
|
||||||
|
showLive,
|
||||||
|
snapshotUrl,
|
||||||
|
placeholder,
|
||||||
|
caption,
|
||||||
|
large,
|
||||||
|
}: {
|
||||||
|
imgRef: (el: HTMLImageElement | null) => void;
|
||||||
|
showLive: boolean;
|
||||||
|
snapshotUrl: string | null;
|
||||||
|
placeholder: string;
|
||||||
|
caption: string;
|
||||||
|
large: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="relative aspect-video w-full bg-black">
|
||||||
|
<img ref={imgRef} alt="" className={`absolute inset-0 h-full w-full object-contain ${showLive ? "" : "hidden"}`} />
|
||||||
|
{!showLive && snapshotUrl && (
|
||||||
|
<img src={snapshotUrl} alt="" className="absolute inset-0 h-full w-full object-contain" />
|
||||||
|
)}
|
||||||
|
{!showLive && !snapshotUrl && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center px-2 text-center text-[0.6875rem] text-term-muted">
|
||||||
|
{placeholder}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{showLive && <LiveBadge large={large} />}
|
||||||
|
{caption && (
|
||||||
|
<div
|
||||||
|
className={`absolute bottom-0 left-0 right-0 truncate bg-black/60 text-left text-term-muted ${
|
||||||
|
large ? "px-3 py-1 text-[0.8125rem]" : "px-1.5 py-0.5 text-[0.625rem]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{caption}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "● LIVE" with a pulsing green dot, over the video's top-left corner. */
|
||||||
|
function LiveBadge({ large }: { large: boolean }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={`absolute left-1.5 top-1.5 flex items-center gap-1.5 rounded-full bg-black/70 font-semibold uppercase tracking-wider text-term-green ${
|
||||||
|
large ? "px-2.5 py-1 text-[0.8125rem]" : "px-1.5 py-0.5 text-[0.625rem]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="relative flex h-2 w-2">
|
||||||
|
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-term-green opacity-75" />
|
||||||
|
<span className="relative inline-flex h-2 w-2 rounded-full bg-term-green" />
|
||||||
|
</span>
|
||||||
|
{t("camera.live")}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnapshotNav = {
|
||||||
|
older: CameraSnapshotMeta | null;
|
||||||
|
newer: CameraSnapshotMeta | null;
|
||||||
|
go: (shot: CameraSnapshotMeta) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Large view of one camera with a Live / Snapshot switch and, on the Snapshot side,
|
||||||
|
* ‹ › (also ← →) to step through older / newer snapshots — muted at either end.
|
||||||
|
* Closes on ✕, Escape or a backdrop click. */
|
||||||
|
function CameraModal({
|
||||||
|
title,
|
||||||
|
mode,
|
||||||
|
onMode,
|
||||||
|
nav,
|
||||||
|
onClose,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
mode: "live" | "snapshot";
|
||||||
|
onMode: (m: "live" | "snapshot") => void;
|
||||||
|
nav: SnapshotNav | null;
|
||||||
|
onClose: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "Escape") onClose();
|
||||||
|
else if (e.key === "ArrowLeft" && nav?.older) nav.go(nav.older);
|
||||||
|
else if (e.key === "ArrowRight" && nav?.newer) nav.go(nav.newer);
|
||||||
|
};
|
||||||
|
document.addEventListener("keydown", onKey);
|
||||||
|
return () => document.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose, nav]);
|
||||||
|
const chevron = (side: "left" | "right") => {
|
||||||
|
const target = side === "left" ? nav?.older : nav?.newer;
|
||||||
|
const label = t(side === "left" ? "camera.older" : "camera.newer");
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!target}
|
||||||
|
onClick={() => target && nav?.go(target)}
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
className={`absolute top-1/2 ${side === "left" ? "left-2" : "right-2"} flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-black/60 text-3xl leading-none text-term-text transition-opacity hover:bg-black/80 disabled:cursor-default disabled:opacity-25 disabled:hover:bg-black/60`}
|
||||||
|
>
|
||||||
|
{side === "left" ? "‹" : "›"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const seg = (m: "live" | "snapshot", label: string) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onMode(m)}
|
||||||
|
aria-pressed={mode === m}
|
||||||
|
className={`px-3 py-0.5 text-[0.75rem] font-semibold uppercase tracking-wider ${
|
||||||
|
mode === m ? "bg-term-amber text-term-bg" : "text-term-muted hover:text-term-text"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
// Portalled to <body>: the dock is a fixed, z-indexed, pointer-events-none layer that
|
||||||
|
// would otherwise trap the modal inside its stacking context.
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-6"
|
||||||
|
onClick={onClose}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label={title}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="flex w-[min(90vw,calc((100vh-7rem)*16/9))] flex-col overflow-hidden rounded-term border border-term-border bg-term-panel shadow-2xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 border-b border-term-border bg-term-panel-2 px-3 py-1.5 text-[0.8125rem]">
|
||||||
|
<span className="min-w-0 flex-1 truncate font-semibold text-term-text">{title}</span>
|
||||||
|
<div className="flex shrink-0 overflow-hidden rounded-term border border-term-border" role="group">
|
||||||
|
{seg("live", t("camera.live"))}
|
||||||
|
{seg("snapshot", t("camera.snapshot"))}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="shrink-0 text-term-muted hover:text-term-text"
|
||||||
|
aria-label={t("common.close")}
|
||||||
|
title={t("common.close")}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="relative">
|
||||||
|
{children}
|
||||||
|
{nav && chevron("left")}
|
||||||
|
{nav && chevron("right")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Newest snapshot for the tile's resting picture: `meta` is the newest known, `pic` what
|
||||||
|
* is on screen (the previous picture until the newest has loaded). */
|
||||||
|
function useLatestSnapshot(deviceId: string, enabled: boolean) {
|
||||||
|
const meta = useQuery({
|
||||||
|
queryKey: ["camera-latest", deviceId],
|
||||||
|
queryFn: () => fetchLatestCameraSnapshot(deviceId),
|
||||||
|
enabled,
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
const pic = useSnapshotPicture(meta.data ?? null);
|
||||||
|
return { meta: meta.data ?? null, pic };
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnapshotPicture = { meta: CameraSnapshotMeta | null; url: string | null; failed: boolean };
|
||||||
|
|
||||||
|
/** A snapshot's bytes as an object URL, paired with the meta it belongs to. On a change
|
||||||
|
* the previous picture (and its meta) stays until the next has loaded — no blank flash
|
||||||
|
* while stepping — then is revoked; `failed` when the last request failed (e.g. pruned
|
||||||
|
* by retention). Everything is revoked on unmount. */
|
||||||
|
function useSnapshotPicture(want: CameraSnapshotMeta | null): SnapshotPicture {
|
||||||
|
const [pic, setPic] = useState<SnapshotPicture>({ meta: null, url: null, failed: false });
|
||||||
|
const current = useRef<string | null>(null);
|
||||||
|
const replace = (next: SnapshotPicture) => {
|
||||||
|
if (current.current && current.current !== next.url) URL.revokeObjectURL(current.current);
|
||||||
|
current.current = next.url;
|
||||||
|
setPic(next);
|
||||||
|
};
|
||||||
|
const id = want?.id ?? null;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!want) {
|
||||||
|
replace({ meta: null, url: null, failed: false });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
setPic((p) => ({ ...p, failed: false }));
|
||||||
|
fetchSnapshotObjectUrl(want.id)
|
||||||
|
.then((u) => (cancelled ? URL.revokeObjectURL(u) : replace({ meta: want, url: u, failed: false })))
|
||||||
|
.catch(() => !cancelled && setPic((p) => ({ ...p, failed: true })));
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
// Keyed by id only: a new `want` object for the same snapshot must not refetch.
|
||||||
|
}, [id]);
|
||||||
|
useEffect(() => () => replace({ meta: null, url: null, failed: false }), []);
|
||||||
|
return pic;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* While `active` (wanted: camera activity, or the user's choice in the large view), hold a live socket to the camera and paint each JPEG into `imgRef`.
|
||||||
|
* Closed (and the last frame dropped) as soon as the camera goes idle or the tile
|
||||||
|
* unmounts; reconnects after a drop while still active. The server shares one camera
|
||||||
|
* session between every viewer and skips frames for a slow one.
|
||||||
|
*/
|
||||||
|
export function useLiveFrames(deviceId: string, active: boolean) {
|
||||||
|
// Every <img> showing this camera (the tile, and the large view while open) gets each
|
||||||
|
// frame; a view that mounts between frames is given the newest one at once.
|
||||||
|
const imgs = useRef(new Map<string, HTMLImageElement>());
|
||||||
|
const latest = useRef<string | null>(null);
|
||||||
|
const imgRefs = useMemo(() => {
|
||||||
|
const slot = (name: string) => (el: HTMLImageElement | null) => {
|
||||||
|
if (el) {
|
||||||
|
imgs.current.set(name, el);
|
||||||
|
if (latest.current) el.src = latest.current;
|
||||||
|
} else {
|
||||||
|
imgs.current.delete(name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return { tile: slot("tile"), modal: slot("modal"), editor: slot("editor") };
|
||||||
|
}, []);
|
||||||
|
const [status, setStatus] = useState<LiveState>({ state: "connecting" });
|
||||||
|
const [hasFrame, setHasFrame] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) {
|
||||||
|
setHasFrame(false);
|
||||||
|
setStatus({ state: "connecting" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let closed = false;
|
||||||
|
let currentUrl: string | null = null;
|
||||||
|
let retry: number | undefined;
|
||||||
|
let sock: ReturnType<typeof createPlatformSocket> | null = null;
|
||||||
|
|
||||||
|
const paint = (buf: ArrayBuffer) => {
|
||||||
|
if (closed) return; // a frame landing after cleanup must not resurrect the view
|
||||||
|
const next = URL.createObjectURL(new Blob([buf], { type: "image/jpeg" }));
|
||||||
|
const prev = currentUrl;
|
||||||
|
currentUrl = next;
|
||||||
|
latest.current = next;
|
||||||
|
for (const img of imgs.current.values()) img.src = next;
|
||||||
|
if (prev) URL.revokeObjectURL(prev);
|
||||||
|
setHasFrame(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const connect = () => {
|
||||||
|
if (closed) return;
|
||||||
|
setStatus({ state: "connecting" });
|
||||||
|
sock = createPlatformSocket(wsUrl(`/api/cameras/${encodeURIComponent(deviceId)}/live`));
|
||||||
|
sock.onmessage = (ev) => {
|
||||||
|
if (closed) return;
|
||||||
|
if (typeof ev.data === "string") {
|
||||||
|
try {
|
||||||
|
const msg = JSON.parse(ev.data) as { kind: string } & LiveState;
|
||||||
|
if (msg.kind === "status") setStatus(msg);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
paint(ev.data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
sock.onclose = () => {
|
||||||
|
if (closed) return;
|
||||||
|
retry = window.setTimeout(connect, RECONNECT_MS);
|
||||||
|
};
|
||||||
|
sock.onerror = () => sock?.close();
|
||||||
|
};
|
||||||
|
connect();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
closed = true;
|
||||||
|
if (retry) window.clearTimeout(retry);
|
||||||
|
sock?.close();
|
||||||
|
if (currentUrl) URL.revokeObjectURL(currentUrl);
|
||||||
|
latest.current = null;
|
||||||
|
for (const img of imgs.current.values()) img.removeAttribute("src");
|
||||||
|
};
|
||||||
|
}, [deviceId, active]);
|
||||||
|
|
||||||
|
return { imgRefs, status, hasFrame };
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
CROSSING_MIN_LENGTH,
|
||||||
|
type CrossingDirection,
|
||||||
|
type CrossingLine,
|
||||||
|
type FramePoint,
|
||||||
|
} from "@parking/shared";
|
||||||
|
import { useLiveFrames } from "./CameraDock.js";
|
||||||
|
|
||||||
|
// Draws a camera's crossing line over its live picture — our own version of a Hikvision
|
||||||
|
// Line Crossing rule, for cameras that have none: a segment, sides A and B, and which
|
||||||
|
// crossing counts (A→B, B→A, A↔B). Points are normalised to the frame, so the line holds
|
||||||
|
// at any display size. Side A is the screen-left of p1→p2 (see crossingSide in shared).
|
||||||
|
|
||||||
|
type Drag = { end: "p1" | "p2" } | null;
|
||||||
|
|
||||||
|
const HANDLE_PX = 14; // grab radius around an end point
|
||||||
|
|
||||||
|
export function CrossingLineEditor({
|
||||||
|
deviceId,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
deviceId: string;
|
||||||
|
value: CrossingLine | null;
|
||||||
|
onChange: (next: CrossingLine | null) => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const live = useLiveFrames(deviceId, true);
|
||||||
|
const surface = useRef<SVGSVGElement | null>(null);
|
||||||
|
const [size, setSize] = useState({ w: 0, h: 0 });
|
||||||
|
const [drag, setDrag] = useState<Drag>(null);
|
||||||
|
// While drawing a new line it lives here, so a click-length line never reaches the form.
|
||||||
|
const [draft, setDraft] = useState<CrossingLine | null>(null);
|
||||||
|
const line = draft ?? value;
|
||||||
|
|
||||||
|
// The overlay sits exactly on the picture (the wrapper is sized by the <img>), so its
|
||||||
|
// rectangle IS the frame: no letterbox offset to correct for.
|
||||||
|
useEffect(() => {
|
||||||
|
const el = surface.current;
|
||||||
|
if (!el) return;
|
||||||
|
const ro = new ResizeObserver(([e]) => e && setSize({ w: e.contentRect.width, h: e.contentRect.height }));
|
||||||
|
ro.observe(el);
|
||||||
|
return () => ro.disconnect();
|
||||||
|
}, [live.hasFrame]);
|
||||||
|
|
||||||
|
const toFrame = (ev: React.PointerEvent): FramePoint => {
|
||||||
|
const r = surface.current!.getBoundingClientRect();
|
||||||
|
const clamp = (v: number) => Math.min(1, Math.max(0, v));
|
||||||
|
return { x: clamp((ev.clientX - r.left) / r.width), y: clamp((ev.clientY - r.top) / r.height) };
|
||||||
|
};
|
||||||
|
const px = (p: FramePoint) => ({ x: p.x * size.w, y: p.y * size.h });
|
||||||
|
|
||||||
|
function onDown(ev: React.PointerEvent<SVGSVGElement>) {
|
||||||
|
if (!live.hasFrame) return;
|
||||||
|
ev.currentTarget.setPointerCapture(ev.pointerId);
|
||||||
|
const at = toFrame(ev);
|
||||||
|
if (value) {
|
||||||
|
for (const end of ["p1", "p2"] as const) {
|
||||||
|
const e = px(value[end]);
|
||||||
|
const a = px(at);
|
||||||
|
if (Math.hypot(e.x - a.x, e.y - a.y) <= HANDLE_PX) {
|
||||||
|
setDrag({ end });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Anywhere else: draw a new line from here, keeping the chosen direction.
|
||||||
|
setDraft({ p1: at, p2: at, direction: value?.direction ?? "a-to-b" });
|
||||||
|
setDrag({ end: "p2" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMove(ev: React.PointerEvent<SVGSVGElement>) {
|
||||||
|
if (!drag) return;
|
||||||
|
const at = toFrame(ev);
|
||||||
|
if (draft) setDraft({ ...draft, [drag.end]: at });
|
||||||
|
else if (value) onChange({ ...value, [drag.end]: at });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onUp() {
|
||||||
|
if (draft && Math.hypot(draft.p2.x - draft.p1.x, draft.p2.y - draft.p1.y) >= CROSSING_MIN_LENGTH) {
|
||||||
|
onChange(draft);
|
||||||
|
}
|
||||||
|
setDraft(null);
|
||||||
|
setDrag(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
const directions: [CrossingDirection, string][] = [
|
||||||
|
["a-to-b", "A → B"],
|
||||||
|
["b-to-a", "B → A"],
|
||||||
|
["both", "A ↔ B"],
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="my-2 rounded-term border border-term-border bg-term-bg p-2 text-[0.75rem]">
|
||||||
|
<div className="font-semibold text-term-text">{t("setup.crossingTitle")}</div>
|
||||||
|
<p className="hint mt-0.5">{t("setup.crossingHint")}</p>
|
||||||
|
|
||||||
|
<div className="relative mt-2 inline-block w-full select-none">
|
||||||
|
<img
|
||||||
|
ref={live.imgRefs.editor}
|
||||||
|
alt=""
|
||||||
|
draggable={false}
|
||||||
|
className={live.hasFrame ? "block h-auto w-full" : "hidden"}
|
||||||
|
/>
|
||||||
|
{!live.hasFrame && (
|
||||||
|
<div className="flex aspect-video w-full items-center justify-center rounded bg-term-panel text-term-muted">
|
||||||
|
{live.status.state === "unavailable" || live.status.state === "retrying"
|
||||||
|
? live.status.reason
|
||||||
|
: t("setup.crossingWaiting")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{live.hasFrame && (
|
||||||
|
<svg
|
||||||
|
ref={surface}
|
||||||
|
className="absolute inset-0 h-full w-full cursor-crosshair touch-none"
|
||||||
|
onPointerDown={onDown}
|
||||||
|
onPointerMove={onMove}
|
||||||
|
onPointerUp={onUp}
|
||||||
|
onPointerCancel={onUp}
|
||||||
|
>
|
||||||
|
{line && size.w > 0 && <LineOverlay line={line} p1={px(line.p1)} p2={px(line.p2)} />}
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||||
|
<div className="flex gap-1" role="radiogroup" aria-label={t("setup.crossingDirection")}>
|
||||||
|
{directions.map(([d, label]) => (
|
||||||
|
<button
|
||||||
|
key={d}
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={value?.direction === d}
|
||||||
|
disabled={!value}
|
||||||
|
className={`btn btn-sm ${value?.direction === d ? "btn-primary" : ""}`}
|
||||||
|
onClick={() => value && onChange({ ...value, direction: d })}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-sm"
|
||||||
|
disabled={!value}
|
||||||
|
onClick={() => value && onChange({ ...value, p1: value.p2, p2: value.p1 })}
|
||||||
|
>
|
||||||
|
{t("setup.crossingSwap")}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-sm" disabled={!value} onClick={() => onChange(null)}>
|
||||||
|
{t("setup.crossingClear")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{!value && <p className="hint mt-1">{t("setup.crossingNone")}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The segment, its end handles, the A/B labels either side, and an arrow across the
|
||||||
|
* middle pointing the way that counts (double-headed for A↔B). Pixel space. */
|
||||||
|
function LineOverlay({ line, p1, p2 }: { line: CrossingLine; p1: FramePoint; p2: FramePoint }) {
|
||||||
|
const dx = p2.x - p1.x;
|
||||||
|
const dy = p2.y - p1.y;
|
||||||
|
const len = Math.hypot(dx, dy) || 1;
|
||||||
|
// Unit normal toward side A: the screen-left of p1→p2 (y down) is (dy, -dx).
|
||||||
|
const nA = { x: dy / len, y: -dx / len };
|
||||||
|
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
|
||||||
|
const at = (k: number) => ({ x: mid.x + nA.x * k, y: mid.y + nA.y * k });
|
||||||
|
const aSide = at(22);
|
||||||
|
const bSide = at(-22);
|
||||||
|
const labelA = at(40);
|
||||||
|
const labelB = at(-40);
|
||||||
|
// Arrow runs from the side crossings start on to the side they end on.
|
||||||
|
const [from, to] = line.direction === "b-to-a" ? [bSide, aSide] : [aSide, bSide];
|
||||||
|
const both = line.direction === "both";
|
||||||
|
const stroke = "rgb(250 204 21)"; // amber, readable over daylight and night pictures
|
||||||
|
return (
|
||||||
|
<g>
|
||||||
|
<defs>
|
||||||
|
<marker id="crossing-head" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
|
||||||
|
<path d="M0,0 L10,5 L0,10 z" fill={stroke} />
|
||||||
|
</marker>
|
||||||
|
</defs>
|
||||||
|
<line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke="black" strokeOpacity={0.5} strokeWidth={5} />
|
||||||
|
<line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke={stroke} strokeWidth={3} />
|
||||||
|
<line
|
||||||
|
x1={from.x}
|
||||||
|
y1={from.y}
|
||||||
|
x2={to.x}
|
||||||
|
y2={to.y}
|
||||||
|
stroke={stroke}
|
||||||
|
strokeWidth={3}
|
||||||
|
markerEnd="url(#crossing-head)"
|
||||||
|
markerStart={both ? "url(#crossing-head)" : undefined}
|
||||||
|
/>
|
||||||
|
{[p1, p2].map((p, i) => (
|
||||||
|
<circle key={i} cx={p.x} cy={p.y} r={6} fill={stroke} stroke="black" strokeWidth={1.5} />
|
||||||
|
))}
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
["A", labelA],
|
||||||
|
["B", labelB],
|
||||||
|
] as const
|
||||||
|
).map(([txt, p]) => (
|
||||||
|
<text
|
||||||
|
key={txt}
|
||||||
|
x={p.x}
|
||||||
|
y={p.y}
|
||||||
|
textAnchor="middle"
|
||||||
|
dominantBaseline="central"
|
||||||
|
fontSize={16}
|
||||||
|
fontWeight={700}
|
||||||
|
fill={stroke}
|
||||||
|
stroke="black"
|
||||||
|
strokeWidth={3}
|
||||||
|
paintOrder="stroke"
|
||||||
|
>
|
||||||
|
{txt}
|
||||||
|
</text>
|
||||||
|
))}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { fetchDeviceStatus, type DeviceStatus } from "../api.js";
|
|||||||
import { formatClock } from "../lib/format.js";
|
import { formatClock } from "../lib/format.js";
|
||||||
import { qk } from "../lib/query.js";
|
import { qk } from "../lib/query.js";
|
||||||
import { useLiveStore } from "../lib/live-store.js";
|
import { useLiveStore } from "../lib/live-store.js";
|
||||||
|
import { CameraDock } from "./CameraDock.js";
|
||||||
|
|
||||||
// Fixed device-status footer for the booth chrome. One compact chip per configured
|
// Fixed device-status footer for the booth chrome. One compact chip per configured
|
||||||
// device — relays, readers, cameras, printers — labelled by ROLE, never vendor
|
// device — relays, readers, cameras, printers — labelled by ROLE, never vendor
|
||||||
@@ -66,7 +67,18 @@ function sortDevices(list: DeviceStatus[]): DeviceStatus[] {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DeviceFooter() {
|
export function DeviceFooter({
|
||||||
|
openCameras,
|
||||||
|
onToggleCamera,
|
||||||
|
canSeeSnapshots,
|
||||||
|
}: {
|
||||||
|
/** Camera tiles open (device ids, opening order) — the user's saved preference. */
|
||||||
|
openCameras: string[];
|
||||||
|
/** Open/close a camera's tile (a camera chip click). */
|
||||||
|
onToggleCamera: (deviceId: string) => void;
|
||||||
|
/** May the user see evidence snapshots (session:read) — the tiles' resting picture. */
|
||||||
|
canSeeSnapshots: boolean;
|
||||||
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const label = useLabel();
|
const label = useLabel();
|
||||||
// Seed/fallback from REST; the WS keeps the live store authoritative thereafter.
|
// Seed/fallback from REST; the WS keeps the live store authoritative thereafter.
|
||||||
@@ -111,17 +123,33 @@ export function DeviceFooter() {
|
|||||||
) : (
|
) : (
|
||||||
devices.map((d) => {
|
devices.map((d) => {
|
||||||
const isProblem = d.state !== "ready";
|
const isProblem = d.state !== "ready";
|
||||||
|
// A CAMERA chip opens/closes that camera's tile (its issues stay reachable
|
||||||
|
// from the roll-up on the right); any other chip is interactive only when
|
||||||
|
// it has a problem (opens the issues panel).
|
||||||
|
const isCamera = d.category === "camera";
|
||||||
|
const isOpen = isCamera && openCameras.includes(d.deviceId);
|
||||||
|
const onClick = isCamera
|
||||||
|
? () => onToggleCamera(d.deviceId)
|
||||||
|
: isProblem
|
||||||
|
? () => setOpen((v) => !v)
|
||||||
|
: undefined;
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={d.deviceId}
|
key={d.deviceId}
|
||||||
type="button"
|
type="button"
|
||||||
// Only a problem chip is interactive (opens the issues panel).
|
onClick={onClick}
|
||||||
onClick={isProblem ? () => setOpen((v) => !v) : undefined}
|
aria-disabled={!onClick}
|
||||||
aria-disabled={!isProblem}
|
aria-pressed={isCamera ? isOpen : undefined}
|
||||||
title={isProblem ? t("devices.clickForIssues") : undefined}
|
title={
|
||||||
className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-term border border-term-border bg-term-panel-2 px-2 py-0.5 ${
|
isCamera
|
||||||
isProblem ? "cursor-pointer hover:border-term-amber" : "cursor-default"
|
? t(isOpen ? "camera.hideTile" : "camera.showTile")
|
||||||
}`}
|
: isProblem
|
||||||
|
? t("devices.clickForIssues")
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-term border bg-term-panel-2 px-2 py-0.5 ${
|
||||||
|
isOpen ? "border-term-amber" : "border-term-border"
|
||||||
|
} ${onClick ? "cursor-pointer hover:border-term-amber" : "cursor-default"}`}
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT[d.state]} ${
|
className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT[d.state]} ${
|
||||||
@@ -153,6 +181,15 @@ export function DeviceFooter() {
|
|||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{/* Camera tiles, docked bottom-right above this footer. */}
|
||||||
|
<CameraDock
|
||||||
|
openIds={openCameras}
|
||||||
|
cameras={devices.filter((d) => d.category === "camera")}
|
||||||
|
label={label}
|
||||||
|
canSeeSnapshots={canSeeSnapshots}
|
||||||
|
onClose={onToggleCamera}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Issues panel — anchored above the footer, lists only problem devices. */}
|
{/* Issues panel — anchored above the footer, lists only problem devices. */}
|
||||||
{open && problems.length > 0 && (
|
{open && problems.length > 0 && (
|
||||||
<div className="absolute bottom-full right-2 z-50 mb-1 w-[360px] max-w-[95vw] rounded-term border border-term-border bg-term-panel shadow-2xl">
|
<div className="absolute bottom-full right-2 z-50 mb-1 w-[360px] max-w-[95vw] rounded-term border border-term-border bg-term-panel shadow-2xl">
|
||||||
|
|||||||
@@ -22,29 +22,30 @@ services:
|
|||||||
COLLECTOR_REVIEWER_USER: ${COLLECTOR_REVIEWER_USER:-reviewer}
|
COLLECTOR_REVIEWER_USER: ${COLLECTOR_REVIEWER_USER:-reviewer}
|
||||||
COLLECTOR_REVIEWER_PASS: ${COLLECTOR_REVIEWER_PASS:?set COLLECTOR_REVIEWER_PASS in the stack env}
|
COLLECTOR_REVIEWER_PASS: ${COLLECTOR_REVIEWER_PASS:?set COLLECTOR_REVIEWER_PASS in the stack env}
|
||||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||||
|
# The trainer's job API (sibling service above). Unset = no Training section.
|
||||||
|
COLLECTOR_TRAINER_URL: ${COLLECTOR_TRAINER_URL-http://trainer:8091}
|
||||||
volumes:
|
volumes:
|
||||||
- collector-data:/data
|
- collector-data:/data
|
||||||
|
|
||||||
# Phase B trainer — a ONE-OFF JOB on this host's CPU, not a service (profile "train": it
|
# Phase B trainer — a small always-on job service beside the collector (CPU-only torch;
|
||||||
# only runs when asked). Reads the collector's SQLite + crops straight off the same volume
|
# idle it is a tiny Python HTTP server, torch loads only when a job runs). It reads the
|
||||||
# (read-only), writes a versioned model folder under TRAINER_OUT on the host. CPU-only
|
# collector's SQLite + crops off the same volume (read-only) and keeps models, reports and
|
||||||
# PyTorch: the Xeon E3-1225 v5 trains a few thousand crops in minutes (features mode) to an
|
# job logs in its own volume. NOT published: only the collector reaches it, on this compose
|
||||||
# hour (full fine-tune) — see wiki/decisions/bodytype-classifier-training.md. If a modern GPU
|
# network, and the reviewer's login on the collector is the gate. The Training section of
|
||||||
# ever lands in the host, add an nvidia device reservation here; the trainer picks up CUDA.
|
# /review is its UI (readiness, Train / Evaluate / Publish, reports, logs).
|
||||||
#
|
# See wiki/decisions/bodytype-classifier-training.md.
|
||||||
# docker compose -f docker-compose.collector.yml --profile train run --rm trainer inspect
|
|
||||||
# docker compose -f docker-compose.collector.yml --profile train run --rm trainer train --min-accuracy 0.85
|
|
||||||
# docker compose -f docker-compose.collector.yml --profile train run --rm trainer evaluate --model /out/<version>/bodytype.onnx
|
|
||||||
# docker compose -f docker-compose.collector.yml --profile train run --rm trainer publish /out/<version> --url <gitea generic package url>
|
|
||||||
trainer:
|
trainer:
|
||||||
image: ${REGISTRY:-git.infra.msai.al/mca/parking_solution}/parking-trainer:${TAG:-dev}
|
image: ${REGISTRY:-git.infra.msai.al/mca/parking_solution}/parking-trainer:${TAG:-dev}
|
||||||
profiles: ["train"]
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
# Only `publish` needs it: a Gitea token with package:write for the model's generic package.
|
# Where `publish` PUTs a passing model (a Gitea generic package) and the token it uses
|
||||||
|
# (package:write). Only publishing needs the token; training runs without it.
|
||||||
|
TRAINER_PUBLISH_URL: ${TRAINER_PUBLISH_URL:-https://git.infra.msai.al/api/packages/mca/generic/parking-bodytype}
|
||||||
TRAINER_PUBLISH_TOKEN: ${TRAINER_PUBLISH_TOKEN:-}
|
TRAINER_PUBLISH_TOKEN: ${TRAINER_PUBLISH_TOKEN:-}
|
||||||
volumes:
|
volumes:
|
||||||
- collector-data:/data:ro
|
- collector-data:/data:ro
|
||||||
- ${TRAINER_OUT:-./models}:/out
|
- trainer-out:/out
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
collector-data:
|
collector-data:
|
||||||
|
trainer-out:
|
||||||
|
|||||||
+13
-3
@@ -18,6 +18,13 @@ services:
|
|||||||
# Host network: Caddy listens on the host's :80 and proxies the host-net server on
|
# Host network: Caddy listens on the host's :80 and proxies the host-net server on
|
||||||
# 127.0.0.1:3000. (No `ports:` mapping — host mode publishes directly.)
|
# 127.0.0.1:3000. (No `ports:` mapping — host mode publishes directly.)
|
||||||
network_mode: host
|
network_mode: host
|
||||||
|
# PORTS (2026-10-08). On a booth nothing is set and the defaults apply (:80 → :3000). On a
|
||||||
|
# SHARED host — the lab stack runs on art-docker-station, whose :80 is another service's —
|
||||||
|
# the stack env sets HTTP_PORT / SERVER_PORT / VISION_HOST_PORT and every binding follows.
|
||||||
|
# The Caddyfile reads these two as {$HTTP_PORT:80} / {$SERVER_PORT:3000}.
|
||||||
|
environment:
|
||||||
|
HTTP_PORT: ${HTTP_PORT:-80}
|
||||||
|
SERVER_PORT: ${SERVER_PORT:-3000}
|
||||||
# host mode is mutually exclusive with a named network; the base file doesn't attach proxy,
|
# host mode is mutually exclusive with a named network; the base file doesn't attach proxy,
|
||||||
# so nothing to null here (server does — see below).
|
# so nothing to null here (server does — see below).
|
||||||
volumes:
|
volumes:
|
||||||
@@ -45,9 +52,12 @@ services:
|
|||||||
# host mode is mutually exclusive with a named network — detach the base file's `parking`
|
# host mode is mutually exclusive with a named network — detach the base file's `parking`
|
||||||
# attachment (compose errors otherwise: "network_mode and networks cannot both be set").
|
# attachment (compose errors otherwise: "network_mode and networks cannot both be set").
|
||||||
networks: !reset []
|
networks: !reset []
|
||||||
# Listens on :3000 directly on the host (Caddy proxies it). Loopback to vision:
|
# Listens on SERVER_PORT (default 3000) directly on the host (Caddy proxies it); the same
|
||||||
|
# value is what net.ts advertises as the device push port. Loopback to vision on the host
|
||||||
|
# port vision publishes (VISION_HOST_PORT, default 8089):
|
||||||
environment:
|
environment:
|
||||||
VISION_URL: http://127.0.0.1:8089
|
PORT: ${SERVER_PORT:-3000}
|
||||||
|
VISION_URL: http://127.0.0.1:${VISION_HOST_PORT:-8089}
|
||||||
# NB: NO `sysctls:` here. net.ipv4.ping_group_range is a per-netns sysctl; under host net
|
# NB: NO `sysctls:` here. net.ipv4.ping_group_range is a per-netns sysctl; under host net
|
||||||
# there is no separate namespace, and runc REFUSES it ("not allowed in host network
|
# there is no separate namespace, and runc REFUSES it ("not allowed in host network
|
||||||
# namespace"). Reader liveness ping uses the HOST's setting instead — the booth host must
|
# namespace"). Reader liveness ping uses the HOST's setting instead — the booth host must
|
||||||
@@ -95,7 +105,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
VISION_RECOGNIZER: fast_alpr
|
VISION_RECOGNIZER: fast_alpr
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8089:8089"
|
- "127.0.0.1:${VISION_HOST_PORT:-8089}:8089"
|
||||||
# ≈2 months (see the server note): vision logs less — 20 MB × 10 = 200 MB ceiling.
|
# ≈2 months (see the server note): vision logs less — 20 MB × 10 = 200 MB ceiling.
|
||||||
logging:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# relay-proxy — Dingtian emulator + cloud proxy/watchdog (PoC)
|
||||||
|
|
||||||
|
A NodeMCU v3 (ESP8266) that **is a Dingtian DT-R004 to the booth server** and, on top, a
|
||||||
|
**proxy and watchdog toward a cloud service**. The booth's existing `dingtian` driver talks to
|
||||||
|
it unchanged. It is the seed of the custom firmware for the real Dingtian board (ESP32); the IO
|
||||||
|
layer is the only board-specific file.
|
||||||
|
|
||||||
|
Why: park-2's booth PC died twice unnoticed. The device that already owns the barrier relay and
|
||||||
|
the button inputs becomes the resilient core: it reports to the cloud independently of the PC,
|
||||||
|
can power-cycle the PC, and keeps accepting commands from the cloud when the PC is dead.
|
||||||
|
See `wiki/entities/dingtian-relay.md` and `wiki/decisions/cloud-service-saas.md`.
|
||||||
|
|
||||||
|
## What it emulates (the booth sees a DT-R004)
|
||||||
|
|
||||||
|
| Surface | Behaviour |
|
||||||
|
| --- | --- |
|
||||||
|
| UDP 60000 binary | `FF AA s cmd pwLo pwHi …`: `00` status, `01` write (mask,set), `03` jog. Reply `FF AA s cmd relayByte inputByte`. Wrong `relay_pw` → dropped silently. |
|
||||||
|
| UDP 60001 string | `00`, `1N`, `2N`, `1N*`. Password-less. Enabled at factory; `harden()` turns it off (`udp2.p=255`). |
|
||||||
|
| `GET /api/v2/config.cgi` | The config JSON (relay_connect, input_link_relay, input_link_url). |
|
||||||
|
| `POST /api/v2/config_set.cgi` | Applies + persists (LittleFS). Requires `"command":"setconfig"` like the real device. |
|
||||||
|
| `GET /userset.cgi?u&old&u&new&` | Web-login rotation, `&0&` ok / `&2&` wrong old password. |
|
||||||
|
| Input push | On input change, Digest-authenticated GET to the booth's `on_path`/`off_path`. |
|
||||||
|
| `input_link_relay` | Factory ON (input auto-fires its relay) until the booth's precondition fix clears it. |
|
||||||
|
|
||||||
|
Extra, PoC-only: `GET /` status text, `POST /poc/factory_reset`.
|
||||||
|
|
||||||
|
## Proxy / watchdog (toward `CLOUD_URL`)
|
||||||
|
|
||||||
|
- Heartbeat every 10 s: IP, booth health, relay/input state, config flags.
|
||||||
|
- Every input change is mirrored to the cloud (`/event`) with the booth push result.
|
||||||
|
- Command poll every 2 s: `{"pulse":ch,"ms":500}`, `{"watchdog":false}`, `{"reboot_pc":true}`.
|
||||||
|
- Watchdog: probes `BOOTH_HEALTH_URL` every 5 s; after 6 failures in a row it pulses relay 2
|
||||||
|
for 3 s (meant for an NC contact in series with the PC's mains, with BIOS AC Recovery = On),
|
||||||
|
then backs off 10 min. The cloud can disable it.
|
||||||
|
|
||||||
|
## Pins (NodeMCU v3) — no wiring needed to start
|
||||||
|
|
||||||
|
| Function | Pin |
|
||||||
|
| --- | --- |
|
||||||
|
| Relay 1 (barrier) | D1 / GPIO5, mirrored on the on-board LED |
|
||||||
|
| Relay 2 (PC power) | D2 / GPIO4 |
|
||||||
|
| Relay 3, 4 | D5 / GPIO14, D6 / GPIO12 |
|
||||||
|
| Input 1 (button) | the on-board **FLASH** button (GPIO0), active LOW |
|
||||||
|
| Input 2 | D7 / GPIO13, short to GND |
|
||||||
|
|
||||||
|
## Build / flash
|
||||||
|
|
||||||
|
```
|
||||||
|
cd firmware/relay-proxy
|
||||||
|
copy include\secrets.h.example include\secrets.h # fill in; gitignored
|
||||||
|
..\.venv\Scripts\pio run -t upload
|
||||||
|
..\.venv\Scripts\pio device monitor
|
||||||
|
```
|
||||||
|
|
||||||
|
Cloud stand-in (throwaway): `node poc/cloud-standin.mjs` on a host the device can reach.
|
||||||
|
|
||||||
|
## Register it in the booth
|
||||||
|
|
||||||
|
Devices → add **Dingtian relay controller**: host = the NodeMCU's IP (give it a DHCP
|
||||||
|
reservation or set `STATIC_IP`; the booth only accepts pushes from the registered IP),
|
||||||
|
channels 4, binary port 60000, string port 60001, HTTP port 80. On save the booth runs the
|
||||||
|
normal flow: precondition fix (clears `input_link_relay`), `harden()` (random `relay_pw`,
|
||||||
|
disables udp2, rotates the web login), and `configureInputPush()` (Digest creds + URLs).
|
||||||
|
The serial log shows each step land.
|
||||||
|
|
||||||
|
## Limits of the PoC
|
||||||
|
|
||||||
|
- Wi-Fi only; the real target has Ethernet.
|
||||||
|
- HTTP calls block the loop briefly (~100 ms); fine for a demo, not for production.
|
||||||
|
- The config JSON mirrors the keys the booth driver uses, not the full device schema.
|
||||||
|
- Plain HTTP to the cloud stand-in; the real cloud link needs TLS.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
|
// The Dingtian-shaped config served by /api/v2/config.cgi, persisted to LittleFS.
|
||||||
|
// Holds exactly the keys the booth driver reads/writes (relay_connect, input_link_relay,
|
||||||
|
// input_link_url) — a faithful-enough subset, not a byte copy of the real device.
|
||||||
|
class ConfigStore {
|
||||||
|
public:
|
||||||
|
JsonDocument cfg;
|
||||||
|
String webUser, webPass; // web-UI login (userset.cgi), kept out of config.cgi
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
bool save();
|
||||||
|
bool saveWeb();
|
||||||
|
void makeDefaults();
|
||||||
|
|
||||||
|
uint16_t relayPw() const;
|
||||||
|
bool stringProtoEnabled() const; // udp2.p != 255
|
||||||
|
bool linkRelayEnabled() const; // input_link_relay flag (factory: on)
|
||||||
|
};
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
// HTTP GET with RFC 2617 Digest (MD5, qop=auth) — what the booth's push route
|
||||||
|
// requires. First GET takes the 401 challenge, second carries the response.
|
||||||
|
// With an empty user it is a plain GET. Returns the final HTTP status (<0 = no connection).
|
||||||
|
int digestGet(const String& host, uint16_t port, const String& path, const String& user, const String& pass);
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
constexpr int CHANNELS = 4;
|
||||||
|
|
||||||
|
// Relay/input IO behind one tiny interface. Business code never touches pins, so
|
||||||
|
// porting to the real Dingtian board (74HC595 relays / 74HC165 inputs) swaps only
|
||||||
|
// the Io implementation file.
|
||||||
|
class Io {
|
||||||
|
public:
|
||||||
|
void begin();
|
||||||
|
void setRelay(int ch, bool on); // 1-based
|
||||||
|
bool relay(int ch) const; // 1-based
|
||||||
|
bool inputHigh(int ch); // raw line level, 1-based
|
||||||
|
uint8_t relayMask() const; // bit0 = relay 1
|
||||||
|
uint8_t inputMask(); // bit0 = input 1, bit set = line HIGH
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool relays_[CHANNELS] = {};
|
||||||
|
};
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Copy to include/secrets.h (gitignored) and fill in.
|
||||||
|
#pragma once
|
||||||
|
#define WIFI_SSID "your-ssid"
|
||||||
|
#define WIFI_PASS "your-password"
|
||||||
|
// Ephemeral cloud stand-in (poc/cloud-standin.mjs), plain HTTP for the PoC.
|
||||||
|
#define CLOUD_URL "http://10.0.10.203:9099"
|
||||||
|
// Booth server health endpoint the watchdog probes.
|
||||||
|
#define BOOTH_HEALTH_URL "http://10.0.10.198/health"
|
||||||
|
// Optional fixed address (the booth only accepts pushes from the registered host IP).
|
||||||
|
// #define STATIC_IP "10.0.10.240"
|
||||||
|
// #define STATIC_GW "10.0.10.1"
|
||||||
|
// #define STATIC_MASK "255.255.255.0"
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
; relay-proxy — Dingtian DT-R004 emulator + cloud proxy/watchdog PoC.
|
||||||
|
; NodeMCU v3 (ESP8266) now; an esp32 env is the port target for the real Dingtian board.
|
||||||
|
[platformio]
|
||||||
|
default_envs = nodemcuv2
|
||||||
|
|
||||||
|
[env:nodemcuv2]
|
||||||
|
platform = espressif8266
|
||||||
|
board = nodemcuv2
|
||||||
|
framework = arduino
|
||||||
|
board_build.filesystem = littlefs
|
||||||
|
monitor_speed = 115200
|
||||||
|
upload_speed = 460800
|
||||||
|
upload_port = COM35
|
||||||
|
monitor_port = COM35
|
||||||
|
lib_deps = bblanchon/ArduinoJson@^7.3.0
|
||||||
|
build_flags = -Wall
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// EPHEMERAL cloud stand-in for the relay-proxy PoC. Not a product component.
|
||||||
|
// Logs heartbeats/events from the device and lets you queue commands with curl.
|
||||||
|
//
|
||||||
|
// node poc/cloud-standin.mjs (listens on 0.0.0.0:9099)
|
||||||
|
// curl http://localhost:9099/ -> last heartbeat per device
|
||||||
|
// curl -X POST http://localhost:9099/fire/1 -> pulse relay 1 (500 ms)
|
||||||
|
// curl -X POST "http://localhost:9099/fire/1?ms=1000"
|
||||||
|
// curl -X POST http://localhost:9099/watchdog/off -> disable the PC watchdog
|
||||||
|
// curl -X POST http://localhost:9099/reboot-pc -> power-cycle the PC relay
|
||||||
|
import { createServer } from "node:http";
|
||||||
|
|
||||||
|
const PORT = Number(process.env.PORT ?? 9099);
|
||||||
|
const last = new Map(); // dev -> last heartbeat
|
||||||
|
const queue = []; // commands, oldest first (dev field optional)
|
||||||
|
const stamp = () => new Date().toISOString().slice(11, 19);
|
||||||
|
|
||||||
|
function body(req) {
|
||||||
|
return new Promise((res) => {
|
||||||
|
let s = "";
|
||||||
|
req.on("data", (c) => (s += c));
|
||||||
|
req.on("end", () => {
|
||||||
|
try { res(s ? JSON.parse(s) : {}); } catch { res({ raw: s }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = (res, code, obj) => {
|
||||||
|
res.writeHead(code, { "content-type": "application/json" });
|
||||||
|
res.end(JSON.stringify(obj));
|
||||||
|
};
|
||||||
|
|
||||||
|
createServer(async (req, res) => {
|
||||||
|
const url = new URL(req.url, "http://x");
|
||||||
|
const p = url.pathname;
|
||||||
|
|
||||||
|
if (req.method === "POST" && p === "/heartbeat") {
|
||||||
|
const hb = await body(req);
|
||||||
|
const prev = last.get(hb.dev);
|
||||||
|
last.set(hb.dev, { ...hb, at: new Date().toISOString() });
|
||||||
|
const flip = prev && prev.booth_ok !== hb.booth_ok ? ` <-- booth ${hb.booth_ok ? "RECOVERED" : "DOWN"}` : "";
|
||||||
|
console.log(`${stamp()} hb ${hb.dev} ip=${hb.ip} booth=${hb.booth_ok ? "up" : "DOWN"}(${hb.booth_code}) fails=${hb.booth_fails} wd=${hb.watchdog} resets=${hb.pc_resets} relays=${hb.relays} inputs=${hb.inputs} pw=${hb.relay_pw_set} push=${hb.push_en} link=${hb.link_relay} udp2=${hb.string_proto} heap=${hb.heap}${flip}`);
|
||||||
|
return json(res, 200, { ok: true });
|
||||||
|
}
|
||||||
|
if (req.method === "POST" && p === "/event") {
|
||||||
|
const ev = await body(req);
|
||||||
|
console.log(`${stamp()} EVENT ${ev.dev} ${ev.type} input=${ev.input} active=${ev.active} booth_status=${ev.booth_status}`);
|
||||||
|
return json(res, 200, { ok: true });
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && p === "/command") {
|
||||||
|
const dev = url.searchParams.get("dev");
|
||||||
|
const i = queue.findIndex((c) => !c.dev || c.dev === dev);
|
||||||
|
if (i < 0) return json(res, 200, {});
|
||||||
|
const [cmd] = queue.splice(i, 1);
|
||||||
|
console.log(`${stamp()} -> ${dev} command ${JSON.stringify(cmd)}`);
|
||||||
|
return json(res, 200, cmd);
|
||||||
|
}
|
||||||
|
if (req.method === "POST" && p.startsWith("/fire/")) {
|
||||||
|
const ch = Number(p.split("/")[2]);
|
||||||
|
const ms = Number(url.searchParams.get("ms") ?? 500);
|
||||||
|
queue.push({ pulse: ch, ms });
|
||||||
|
console.log(`${stamp()} queued pulse relay ${ch} ${ms} ms`);
|
||||||
|
return json(res, 200, { queued: true });
|
||||||
|
}
|
||||||
|
if (req.method === "POST" && p.startsWith("/watchdog/")) {
|
||||||
|
const on = p.endsWith("/on");
|
||||||
|
queue.push({ watchdog: on });
|
||||||
|
console.log(`${stamp()} queued watchdog ${on ? "on" : "off"}`);
|
||||||
|
return json(res, 200, { queued: true });
|
||||||
|
}
|
||||||
|
if (req.method === "POST" && p === "/reboot-pc") {
|
||||||
|
queue.push({ reboot_pc: true });
|
||||||
|
console.log(`${stamp()} queued PC power-cycle`);
|
||||||
|
return json(res, 200, { queued: true });
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && p === "/") {
|
||||||
|
return json(res, 200, { devices: Object.fromEntries(last), queued: queue });
|
||||||
|
}
|
||||||
|
json(res, 404, { error: "not found" });
|
||||||
|
}).listen(PORT, "0.0.0.0", () => console.log(`cloud stand-in on :${PORT} (PoC only)`));
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#include "config_store.h"
|
||||||
|
#include <LittleFS.h>
|
||||||
|
#include "io.h"
|
||||||
|
|
||||||
|
static const char* CFG_PATH = "/config.json";
|
||||||
|
static const char* WEB_PATH = "/web.json";
|
||||||
|
|
||||||
|
void ConfigStore::makeDefaults() {
|
||||||
|
cfg.clear();
|
||||||
|
cfg["status"] = 0;
|
||||||
|
JsonObject rc = cfg["relay_connect"].to<JsonObject>();
|
||||||
|
rc["relay_pw"] = 0;
|
||||||
|
// Factory: udp1 = binary, udp2 = string (password-less!), everything else off.
|
||||||
|
rc["udp1"]["p"] = 1; rc["udp1"]["port"] = 60000;
|
||||||
|
rc["udp2"]["p"] = 0; rc["udp2"]["port"] = 60001;
|
||||||
|
rc["rs485"]["p"] = 255; rc["can"]["p"] = 255;
|
||||||
|
rc["tcpc"]["p"] = 255; rc["tcps"]["p"] = 255;
|
||||||
|
rc["mqtt"]["p"] = 255;
|
||||||
|
// Factory: every input auto-fires its matching relay (the UHPPOTE-style gotcha
|
||||||
|
// the booth's precondition fix turns off).
|
||||||
|
JsonObject ilr = cfg["input_link_relay"].to<JsonObject>();
|
||||||
|
ilr["input_link_relay"] = 1;
|
||||||
|
JsonArray oa = ilr["on_action_on"].to<JsonArray>();
|
||||||
|
for (int i = 0; i < CHANNELS; i++) oa.add<JsonArray>().add(i);
|
||||||
|
JsonObject ilu = cfg["input_link_url"].to<JsonObject>();
|
||||||
|
ilu["cnt"] = CHANNELS;
|
||||||
|
ilu["en"] = 0;
|
||||||
|
const char* intKeys[] = {"active_level", "tls", "auth", "on_method", "off_method"};
|
||||||
|
for (const char* k : intKeys) {
|
||||||
|
JsonArray a = ilu[k].to<JsonArray>();
|
||||||
|
for (int i = 0; i < CHANNELS; i++) a.add(0);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
JsonArray a = ilu["port"].to<JsonArray>();
|
||||||
|
for (int i = 0; i < CHANNELS; i++) a.add(80);
|
||||||
|
}
|
||||||
|
const char* strKeys[] = {"server", "user", "pass", "on_path", "off_path", "on_body", "off_body"};
|
||||||
|
for (const char* k : strKeys) {
|
||||||
|
JsonArray a = ilu[k].to<JsonArray>();
|
||||||
|
for (int i = 0; i < CHANNELS; i++) a.add("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConfigStore::begin() {
|
||||||
|
LittleFS.begin();
|
||||||
|
bool ok = false;
|
||||||
|
File f = LittleFS.open(CFG_PATH, "r");
|
||||||
|
if (f) {
|
||||||
|
ok = deserializeJson(cfg, f) == DeserializationError::Ok;
|
||||||
|
f.close();
|
||||||
|
}
|
||||||
|
if (!ok || !cfg["relay_connect"].is<JsonObject>()) {
|
||||||
|
makeDefaults();
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
webUser = "admin";
|
||||||
|
webPass = "admin";
|
||||||
|
File w = LittleFS.open(WEB_PATH, "r");
|
||||||
|
if (w) {
|
||||||
|
JsonDocument d;
|
||||||
|
if (deserializeJson(d, w) == DeserializationError::Ok) {
|
||||||
|
webUser = d["user"] | "admin";
|
||||||
|
webPass = d["pass"] | "admin";
|
||||||
|
}
|
||||||
|
w.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigStore::save() {
|
||||||
|
File f = LittleFS.open(CFG_PATH, "w");
|
||||||
|
if (!f) return false;
|
||||||
|
serializeJson(cfg, f);
|
||||||
|
f.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigStore::saveWeb() {
|
||||||
|
JsonDocument d;
|
||||||
|
d["user"] = webUser;
|
||||||
|
d["pass"] = webPass;
|
||||||
|
File f = LittleFS.open(WEB_PATH, "w");
|
||||||
|
if (!f) return false;
|
||||||
|
serializeJson(d, f);
|
||||||
|
f.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t ConfigStore::relayPw() const { return cfg["relay_connect"]["relay_pw"] | 0; }
|
||||||
|
bool ConfigStore::stringProtoEnabled() const { return (cfg["relay_connect"]["udp2"]["p"] | 255) != 255; }
|
||||||
|
bool ConfigStore::linkRelayEnabled() const { return (cfg["input_link_relay"]["input_link_relay"] | 0) == 1; }
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
#include "digest.h"
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
#include <ESP8266HTTPClient.h>
|
||||||
|
#include <MD5Builder.h>
|
||||||
|
|
||||||
|
static String md5(const String& s) {
|
||||||
|
MD5Builder m;
|
||||||
|
m.begin();
|
||||||
|
m.add(s);
|
||||||
|
m.calculate();
|
||||||
|
return m.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pull key="value" or key=value out of a challenge header.
|
||||||
|
static String param(const String& h, const char* key) {
|
||||||
|
String k = String(key) + "=";
|
||||||
|
int i = h.indexOf(k);
|
||||||
|
if (i < 0) return "";
|
||||||
|
i += k.length();
|
||||||
|
if (h[i] == '"') {
|
||||||
|
int j = h.indexOf('"', i + 1);
|
||||||
|
return j < 0 ? "" : h.substring(i + 1, j);
|
||||||
|
}
|
||||||
|
int j = h.indexOf(',', i);
|
||||||
|
return j < 0 ? h.substring(i) : h.substring(i, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
int digestGet(const String& host, uint16_t port, const String& path, const String& user, const String& pass) {
|
||||||
|
WiFiClient client;
|
||||||
|
HTTPClient http;
|
||||||
|
http.setTimeout(2000);
|
||||||
|
if (!http.begin(client, host, port, path)) return -1;
|
||||||
|
const char* keys[] = {"WWW-Authenticate"};
|
||||||
|
http.collectHeaders(keys, 1);
|
||||||
|
int code = http.GET();
|
||||||
|
if (code != 401 || user.isEmpty()) {
|
||||||
|
http.end();
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
String ch = http.header("WWW-Authenticate");
|
||||||
|
http.end();
|
||||||
|
if (!ch.startsWith("Digest")) return 401;
|
||||||
|
|
||||||
|
String realm = param(ch, "realm"), nonce = param(ch, "nonce"), qop = param(ch, "qop");
|
||||||
|
String nc = "00000001";
|
||||||
|
String cnonce = String(ESP.random(), HEX);
|
||||||
|
String ha1 = md5(user + ":" + realm + ":" + pass);
|
||||||
|
String ha2 = md5("GET:" + path);
|
||||||
|
String resp = qop.length() ? md5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2)
|
||||||
|
: md5(ha1 + ":" + nonce + ":" + ha2);
|
||||||
|
String auth = "Digest username=\"" + user + "\", realm=\"" + realm + "\", nonce=\"" + nonce +
|
||||||
|
"\", uri=\"" + path + "\", algorithm=MD5, response=\"" + resp + "\"";
|
||||||
|
if (qop.length()) auth += ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\"";
|
||||||
|
|
||||||
|
HTTPClient h2;
|
||||||
|
h2.setTimeout(2000);
|
||||||
|
if (!h2.begin(client, host, port, path)) return -1;
|
||||||
|
h2.addHeader("Authorization", auth);
|
||||||
|
code = h2.GET();
|
||||||
|
h2.end();
|
||||||
|
return code;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// NodeMCU v3 pin map. Zero external wiring needed for the PoC:
|
||||||
|
// relay 1 -> D1 (GPIO5) + mirrored on the on-board LED (GPIO2, active LOW)
|
||||||
|
// relay 2 -> D2 (GPIO4) (the watchdog's "PC power" relay)
|
||||||
|
// relay 3 -> D5 (GPIO14)
|
||||||
|
// relay 4 -> D6 (GPIO12)
|
||||||
|
// input 1 -> the on-board FLASH button (GPIO0, pulled up, LOW when pressed)
|
||||||
|
// input 2 -> D7 (GPIO13), INPUT_PULLUP: short to GND to "press"
|
||||||
|
// inputs 3-4 are virtual and idle HIGH.
|
||||||
|
#include "io.h"
|
||||||
|
|
||||||
|
static const int8_t RELAY_PIN[CHANNELS] = {5, 4, 14, 12};
|
||||||
|
static const int8_t INPUT_PIN[CHANNELS] = {0, 13, -1, -1};
|
||||||
|
static const uint8_t LED_PIN = 2;
|
||||||
|
|
||||||
|
void Io::begin() {
|
||||||
|
for (int i = 0; i < CHANNELS; i++) {
|
||||||
|
pinMode(RELAY_PIN[i], OUTPUT);
|
||||||
|
digitalWrite(RELAY_PIN[i], LOW);
|
||||||
|
if (INPUT_PIN[i] >= 0) pinMode(INPUT_PIN[i], INPUT_PULLUP);
|
||||||
|
}
|
||||||
|
pinMode(LED_PIN, OUTPUT);
|
||||||
|
digitalWrite(LED_PIN, HIGH); // LED off
|
||||||
|
}
|
||||||
|
|
||||||
|
void Io::setRelay(int ch, bool on) {
|
||||||
|
if (ch < 1 || ch > CHANNELS) return;
|
||||||
|
relays_[ch - 1] = on;
|
||||||
|
digitalWrite(RELAY_PIN[ch - 1], on ? HIGH : LOW);
|
||||||
|
if (ch == 1) digitalWrite(LED_PIN, on ? LOW : HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Io::relay(int ch) const { return ch >= 1 && ch <= CHANNELS && relays_[ch - 1]; }
|
||||||
|
|
||||||
|
bool Io::inputHigh(int ch) {
|
||||||
|
if (ch < 1 || ch > CHANNELS) return true;
|
||||||
|
int8_t pin = INPUT_PIN[ch - 1];
|
||||||
|
return pin < 0 ? true : digitalRead(pin) == HIGH;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t Io::relayMask() const {
|
||||||
|
uint8_t m = 0;
|
||||||
|
for (int i = 0; i < CHANNELS; i++) if (relays_[i]) m |= 1 << i;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t Io::inputMask() {
|
||||||
|
uint8_t m = 0;
|
||||||
|
for (int i = 0; i < CHANNELS; i++) if (inputHigh(i + 1)) m |= 1 << i;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
// relay-proxy — a NodeMCU (ESP8266) that IS a Dingtian DT-R004 to the booth server
|
||||||
|
// (same wire protocol: binary UDP 60000 with relay_pw, string UDP 60001, config CGI,
|
||||||
|
// userset.cgi, Digest input push), plus a proxy/watchdog toward an ephemeral cloud
|
||||||
|
// stand-in. The booth's existing `dingtian` driver needs no change. See README.md.
|
||||||
|
//
|
||||||
|
// SAFETY (barrier-not-a-door): a jog turns a relay ON and releases it after the
|
||||||
|
// requested time — the device never times a *close* against a vehicle. The booth
|
||||||
|
// expresses intent only; physical safety belongs to the barrier operator.
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
#include <ESP8266WebServer.h>
|
||||||
|
#include <ESP8266HTTPClient.h>
|
||||||
|
#include <WiFiUdp.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include "secrets.h"
|
||||||
|
#include "io.h"
|
||||||
|
#include "config_store.h"
|
||||||
|
#include "digest.h"
|
||||||
|
|
||||||
|
// --- tunables --------------------------------------------------------------
|
||||||
|
static const uint32_t HEARTBEAT_MS = 10000; // cloud heartbeat period
|
||||||
|
static const uint32_t COMMAND_POLL_MS = 2000; // cloud command poll period
|
||||||
|
static const uint32_t WD_PROBE_MS = 5000; // booth /health probe period
|
||||||
|
static const int WD_FAIL_THRESHOLD = 6; // probes failed in a row before acting (~30 s)
|
||||||
|
static const int WD_RELAY = 2; // relay wired to the PC's mains (NC contact)
|
||||||
|
static const uint16_t WD_PULSE_MS = 3000; // mains cut duration (AC Recovery=On reboots the PC)
|
||||||
|
static const uint32_t WD_BACKOFF_MS = 600000; // 10 min between power-cycles
|
||||||
|
static const uint32_t DEBOUNCE_MS = 30;
|
||||||
|
|
||||||
|
// --- state -----------------------------------------------------------------
|
||||||
|
static Io io;
|
||||||
|
static ConfigStore store;
|
||||||
|
static ESP8266WebServer http(80);
|
||||||
|
static WiFiUDP udpBin; // Dingtian binary protocol (udp1), authenticated by relay_pw
|
||||||
|
static WiFiUDP udpStr; // Dingtian string protocol (udp2), password-less — harden() disables it
|
||||||
|
static bool udpStrOpen = false;
|
||||||
|
static String devId; // MAC-derived id reported to the cloud
|
||||||
|
|
||||||
|
static uint32_t jogOff[CHANNELS + 1] = {}; // millis() at which a jogged relay releases (0 = none)
|
||||||
|
|
||||||
|
static bool wdEnabled = true;
|
||||||
|
static int wdFails = 0;
|
||||||
|
static bool boothOk = false;
|
||||||
|
static int boothCode = 0;
|
||||||
|
static uint32_t wdResets = 0;
|
||||||
|
static uint32_t wdNextProbe = 0, wdBackoffUntil = 0;
|
||||||
|
static uint32_t nextHeartbeat = 0, nextCommandPoll = 0;
|
||||||
|
static bool cloudOk = false;
|
||||||
|
|
||||||
|
static uint8_t lastStable = 0xFF, lastRaw = 0xFF;
|
||||||
|
static uint32_t rawSince = 0;
|
||||||
|
|
||||||
|
static void logf(const char* fmt, ...) {
|
||||||
|
char buf[200];
|
||||||
|
va_list ap;
|
||||||
|
va_start(ap, fmt);
|
||||||
|
vsnprintf(buf, sizeof buf, fmt, ap);
|
||||||
|
va_end(ap);
|
||||||
|
Serial.printf("[%8lu] %s\n", (unsigned long)millis(), buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline bool due(uint32_t at) { return (int32_t)(millis() - at) >= 0; }
|
||||||
|
|
||||||
|
// --- relays ----------------------------------------------------------------
|
||||||
|
static void jog(int ch, uint16_t ms) {
|
||||||
|
if (ch < 1 || ch > CHANNELS) return;
|
||||||
|
io.setRelay(ch, true);
|
||||||
|
uint32_t t = millis() + ms;
|
||||||
|
jogOff[ch] = t ? t : 1;
|
||||||
|
logf("relay %d jog %u ms", ch, ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void releaseJogs() {
|
||||||
|
for (int ch = 1; ch <= CHANNELS; ch++) {
|
||||||
|
if (jogOff[ch] && due(jogOff[ch])) {
|
||||||
|
jogOff[ch] = 0;
|
||||||
|
io.setRelay(ch, false);
|
||||||
|
logf("relay %d released", ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- cloud (ephemeral stand-in, plain HTTP) --------------------------------
|
||||||
|
static int cloudPost(const char* path, const String& body) {
|
||||||
|
WiFiClient c;
|
||||||
|
HTTPClient h;
|
||||||
|
h.setTimeout(1500);
|
||||||
|
if (!h.begin(c, String(CLOUD_URL) + path)) return -1;
|
||||||
|
h.addHeader("Content-Type", "application/json");
|
||||||
|
int code = h.POST(body);
|
||||||
|
h.end();
|
||||||
|
cloudOk = code == 200;
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void cloudEvent(const char* type, int ch, bool active, int boothStatus) {
|
||||||
|
JsonDocument d;
|
||||||
|
d["dev"] = devId;
|
||||||
|
d["type"] = type;
|
||||||
|
d["input"] = ch;
|
||||||
|
d["active"] = active;
|
||||||
|
d["booth_status"] = boothStatus;
|
||||||
|
d["uptime_s"] = millis() / 1000;
|
||||||
|
String body;
|
||||||
|
serializeJson(d, body);
|
||||||
|
int code = cloudPost("/event", body);
|
||||||
|
logf("cloud event %s -> %d", type, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void heartbeat() {
|
||||||
|
JsonDocument d;
|
||||||
|
d["dev"] = devId;
|
||||||
|
d["ip"] = WiFi.localIP().toString();
|
||||||
|
d["rssi"] = WiFi.RSSI();
|
||||||
|
d["uptime_s"] = millis() / 1000;
|
||||||
|
d["heap"] = ESP.getFreeHeap();
|
||||||
|
d["booth_ok"] = boothOk;
|
||||||
|
d["booth_code"] = boothCode;
|
||||||
|
d["booth_fails"] = wdFails;
|
||||||
|
d["watchdog"] = wdEnabled;
|
||||||
|
d["pc_resets"] = wdResets;
|
||||||
|
d["relays"] = io.relayMask();
|
||||||
|
d["inputs"] = io.inputMask();
|
||||||
|
d["relay_pw_set"] = store.relayPw() != 0;
|
||||||
|
d["push_en"] = (store.cfg["input_link_url"]["en"] | 0) == 1;
|
||||||
|
d["link_relay"] = store.linkRelayEnabled();
|
||||||
|
d["string_proto"] = udpStrOpen;
|
||||||
|
String body;
|
||||||
|
serializeJson(d, body);
|
||||||
|
int code = cloudPost("/heartbeat", body);
|
||||||
|
logf("heartbeat -> %d (booth %s, fails %d)", code, boothOk ? "ok" : "DOWN", wdFails);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void pollCommand() {
|
||||||
|
WiFiClient c;
|
||||||
|
HTTPClient h;
|
||||||
|
h.setTimeout(1500);
|
||||||
|
if (!h.begin(c, String(CLOUD_URL) + "/command?dev=" + devId)) return;
|
||||||
|
int code = h.GET();
|
||||||
|
if (code != 200) { h.end(); return; }
|
||||||
|
String body = h.getString();
|
||||||
|
h.end();
|
||||||
|
JsonDocument d;
|
||||||
|
if (deserializeJson(d, body) != DeserializationError::Ok) return;
|
||||||
|
if (d["pulse"].is<int>()) {
|
||||||
|
int ch = d["pulse"];
|
||||||
|
uint16_t ms = d["ms"] | 500;
|
||||||
|
logf("CLOUD command: pulse relay %d", ch);
|
||||||
|
jog(ch, ms);
|
||||||
|
}
|
||||||
|
if (d["watchdog"].is<bool>()) {
|
||||||
|
wdEnabled = d["watchdog"];
|
||||||
|
logf("CLOUD command: watchdog %s", wdEnabled ? "enabled" : "disabled");
|
||||||
|
}
|
||||||
|
if (d["reboot_pc"] | false) {
|
||||||
|
logf("CLOUD command: power-cycle PC");
|
||||||
|
jog(WD_RELAY, WD_PULSE_MS);
|
||||||
|
wdResets++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- watchdog --------------------------------------------------------------
|
||||||
|
static void watchdogTick() {
|
||||||
|
if (!due(wdNextProbe)) return;
|
||||||
|
wdNextProbe = millis() + WD_PROBE_MS;
|
||||||
|
WiFiClient c;
|
||||||
|
HTTPClient h;
|
||||||
|
h.setTimeout(1500);
|
||||||
|
int code = -1;
|
||||||
|
if (h.begin(c, BOOTH_HEALTH_URL)) {
|
||||||
|
code = h.GET();
|
||||||
|
h.end();
|
||||||
|
}
|
||||||
|
boothCode = code;
|
||||||
|
bool ok = code == 200;
|
||||||
|
if (ok != boothOk) logf("booth is now %s (HTTP %d)", ok ? "UP" : "DOWN", code);
|
||||||
|
boothOk = ok;
|
||||||
|
wdFails = ok ? 0 : wdFails + 1;
|
||||||
|
if (!ok && wdEnabled && wdFails >= WD_FAIL_THRESHOLD && due(wdBackoffUntil)) {
|
||||||
|
logf("WATCHDOG: booth down for %d probes -> power-cycling via relay %d", wdFails, WD_RELAY);
|
||||||
|
jog(WD_RELAY, WD_PULSE_MS);
|
||||||
|
wdResets++;
|
||||||
|
wdBackoffUntil = millis() + WD_BACKOFF_MS;
|
||||||
|
cloudEvent("pc_reset", 0, false, code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- inputs ----------------------------------------------------------------
|
||||||
|
static bool inputActive(int ch, bool high) {
|
||||||
|
// Dingtian semantics: input_link_url.active_level[i] 0 = active LOW.
|
||||||
|
int level = store.cfg["input_link_url"]["active_level"][ch - 1] | 0;
|
||||||
|
return level == 0 ? !high : high;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the booth HTTP status, or 0 when push is not configured.
|
||||||
|
static int pushInput(int ch, bool active) {
|
||||||
|
JsonObjectConst ilu = store.cfg["input_link_url"].as<JsonObjectConst>();
|
||||||
|
if (ilu.isNull() || (ilu["en"] | 0) != 1) return 0;
|
||||||
|
String host = ilu["server"][ch - 1] | "";
|
||||||
|
if (host.isEmpty()) return 0;
|
||||||
|
uint16_t port = ilu["port"][ch - 1] | 80;
|
||||||
|
String path = active ? (ilu["on_path"][ch - 1] | "") : (ilu["off_path"][ch - 1] | "");
|
||||||
|
if (path.isEmpty()) return 0;
|
||||||
|
int auth = ilu["auth"][ch - 1] | 0;
|
||||||
|
String user = auth ? (ilu["user"][ch - 1] | "") : "";
|
||||||
|
String pass = ilu["pass"][ch - 1] | "";
|
||||||
|
int code = digestGet(host, port, path, user, pass);
|
||||||
|
logf("push input %d %s -> %s:%u%s -> %d", ch, active ? "on" : "off", host.c_str(), port, path.c_str(), code);
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void onInputChange(int ch, bool high) {
|
||||||
|
bool active = inputActive(ch, high);
|
||||||
|
logf("input %d %s (%s)", ch, high ? "HIGH" : "LOW", active ? "active" : "idle");
|
||||||
|
// Factory behaviour the booth's precondition fix turns off: input auto-fires its relays.
|
||||||
|
if (store.linkRelayEnabled()) {
|
||||||
|
JsonArrayConst acts = store.cfg["input_link_relay"]["on_action_on"][ch - 1].as<JsonArrayConst>();
|
||||||
|
for (JsonVariantConst v : acts) {
|
||||||
|
int r = v.as<int>() + 1;
|
||||||
|
io.setRelay(r, active);
|
||||||
|
logf("input_link_relay: input %d -> relay %d %s", ch, r, active ? "ON" : "off");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Booth first (the normal path), then the cloud mirror — always, so the cloud
|
||||||
|
// still sees the button when the booth is dead or not yet configured.
|
||||||
|
int boothStatus = pushInput(ch, active);
|
||||||
|
cloudEvent(active ? "input_on" : "input_off", ch, active, boothStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void inputTick() {
|
||||||
|
uint8_t raw = io.inputMask();
|
||||||
|
if (raw != lastRaw) {
|
||||||
|
lastRaw = raw;
|
||||||
|
rawSince = millis();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (millis() - rawSince < DEBOUNCE_MS || raw == lastStable) return;
|
||||||
|
uint8_t changed = raw ^ lastStable;
|
||||||
|
lastStable = raw;
|
||||||
|
for (int ch = 1; ch <= CHANNELS; ch++) {
|
||||||
|
if (changed & (1 << (ch - 1))) onInputChange(ch, raw & (1 << (ch - 1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Dingtian binary protocol (UDP 60000) ----------------------------------
|
||||||
|
// Request: FF AA <session> <cmd> <pwLo> <pwHi> [data...]
|
||||||
|
// Reply: FF AA <session> <cmd> <relayByte> <inputByte> (4ch: one byte each)
|
||||||
|
// cmd 0x00 read status; 0x01 write (mask,set); 0x03 jog (relayByte, units of 100 ms).
|
||||||
|
// Wrong password -> silently dropped, exactly like the hardware.
|
||||||
|
static void handleBinary() {
|
||||||
|
int n = udpBin.parsePacket();
|
||||||
|
if (!n) return;
|
||||||
|
uint8_t b[32];
|
||||||
|
int len = udpBin.read(b, sizeof b);
|
||||||
|
if (len < 6 || b[0] != 0xFF || b[1] != 0xAA) return;
|
||||||
|
uint16_t pw = b[4] | (b[5] << 8);
|
||||||
|
uint16_t want = store.relayPw();
|
||||||
|
if (want != 0 && pw != want) {
|
||||||
|
logf("binary: bad relay_pw %u from %s — dropped", pw, udpBin.remoteIP().toString().c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t session = b[2], cmd = b[3];
|
||||||
|
switch (cmd) {
|
||||||
|
case 0x00:
|
||||||
|
break;
|
||||||
|
case 0x01:
|
||||||
|
if (len >= 8) {
|
||||||
|
uint8_t mask = b[6], set = b[7];
|
||||||
|
for (int ch = 1; ch <= CHANNELS; ch++) {
|
||||||
|
uint8_t bit = 1 << (ch - 1);
|
||||||
|
if (mask & bit) { jogOff[ch] = 0; io.setRelay(ch, set & bit); }
|
||||||
|
}
|
||||||
|
logf("binary: write mask %02x set %02x", mask, set);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 0x03:
|
||||||
|
if (len >= 9) {
|
||||||
|
uint8_t rb = b[6];
|
||||||
|
int ch = (rb >> 1) + 1;
|
||||||
|
uint16_t units = b[7] | (b[8] << 8);
|
||||||
|
if (rb & 1) jog(ch, units * 100);
|
||||||
|
else { jogOff[ch] = 0; io.setRelay(ch, false); }
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
logf("binary: unsupported cmd %02x", cmd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t r[6] = {0xFF, 0xAA, session, cmd, io.relayMask(), io.inputMask()};
|
||||||
|
udpBin.beginPacket(udpBin.remoteIP(), udpBin.remotePort());
|
||||||
|
udpBin.write(r, sizeof r);
|
||||||
|
udpBin.endPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Dingtian string protocol (UDP 60001) — the password-less hole ----------
|
||||||
|
// "00" status -> "RRRR:IIII:4"; "1N" relay N on; "2N" off; "1N*" jog 500 ms.
|
||||||
|
static void handleString() {
|
||||||
|
if (!udpStrOpen) return;
|
||||||
|
int n = udpStr.parsePacket();
|
||||||
|
if (!n) return;
|
||||||
|
char b[16];
|
||||||
|
int len = udpStr.read(b, sizeof b - 1);
|
||||||
|
b[len < 0 ? 0 : len] = 0;
|
||||||
|
String cmd(b);
|
||||||
|
cmd.trim();
|
||||||
|
if (cmd == "00") {
|
||||||
|
// status only
|
||||||
|
} else if (cmd.length() >= 2 && (cmd[0] == '1' || cmd[0] == '2') && isDigit(cmd[1])) {
|
||||||
|
int ch = cmd[1] - '0';
|
||||||
|
if (ch < 1 || ch > CHANNELS) return;
|
||||||
|
logf("string: UNAUTHENTICATED '%s' from %s", cmd.c_str(), udpStr.remoteIP().toString().c_str());
|
||||||
|
if (cmd.endsWith("*")) jog(ch, 500);
|
||||||
|
else { jogOff[ch] = 0; io.setRelay(ch, cmd[0] == '1'); }
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String r;
|
||||||
|
for (int ch = 1; ch <= CHANNELS; ch++) r += io.relay(ch) ? '1' : '0';
|
||||||
|
r += ':';
|
||||||
|
for (int ch = 1; ch <= CHANNELS; ch++) r += io.inputHigh(ch) ? '1' : '0';
|
||||||
|
r += ":" + String(CHANNELS);
|
||||||
|
udpStr.beginPacket(udpStr.remoteIP(), udpStr.remotePort());
|
||||||
|
udpStr.print(r);
|
||||||
|
udpStr.endPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void applyProtocolConfig() {
|
||||||
|
bool want = store.stringProtoEnabled();
|
||||||
|
if (want && !udpStrOpen) { udpStr.begin(60001); udpStrOpen = true; logf("string protocol (udp2) ENABLED on 60001"); }
|
||||||
|
if (!want && udpStrOpen) { udpStr.stop(); udpStrOpen = false; logf("string protocol (udp2) disabled"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Dingtian config CGI (HTTP 80) ------------------------------------------
|
||||||
|
static void onConfigGet() {
|
||||||
|
String out;
|
||||||
|
serializeJson(store.cfg, out);
|
||||||
|
http.send(200, "application/json", out);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void onConfigSet() {
|
||||||
|
String body = http.arg("plain");
|
||||||
|
JsonDocument doc;
|
||||||
|
if (deserializeJson(doc, body) != DeserializationError::Ok) {
|
||||||
|
http.send(400, "application/json", "{\"status\":1}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Faithful to the hardware gotcha: without "command":"setconfig" the device
|
||||||
|
// answers OK and silently does nothing.
|
||||||
|
if (strcmp(doc["command"] | "", "setconfig") != 0) {
|
||||||
|
logf("config_set without command=setconfig — ignored (as the real device does)");
|
||||||
|
http.send(200, "application/json", "{\"status\":0}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doc.remove("command");
|
||||||
|
store.cfg = doc;
|
||||||
|
store.save();
|
||||||
|
applyProtocolConfig();
|
||||||
|
logf("config applied: relay_pw=%u link_relay=%d push_en=%d udp2=%s", store.relayPw(), store.linkRelayEnabled(),
|
||||||
|
(int)(store.cfg["input_link_url"]["en"] | 0), udpStrOpen ? "on" : "off");
|
||||||
|
http.send(200, "application/json", "{\"status\":0}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /userset.cgi?<user>&<old>&<user>&<new>& -> "&0&/&" ok, "&2&/&" wrong old cred
|
||||||
|
static void onUserSet() {
|
||||||
|
if (http.args() < 4) { http.send(200, "text/plain", "&1&/&"); return; }
|
||||||
|
String u = http.argName(0), oldP = http.argName(1), newU = http.argName(2), newP = http.argName(3);
|
||||||
|
if (u != store.webUser || oldP != store.webPass) {
|
||||||
|
logf("userset: rejected (wrong current credentials)");
|
||||||
|
http.send(200, "text/plain", "&2&/&");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
store.webUser = newU;
|
||||||
|
store.webPass = newP;
|
||||||
|
store.saveWeb();
|
||||||
|
logf("userset: web login rotated");
|
||||||
|
http.send(200, "text/plain", "&0&/&");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void onRoot() {
|
||||||
|
String s = "relay-proxy (Dingtian DT-R004 emulator)\n";
|
||||||
|
s += "id " + devId + " ip " + WiFi.localIP().toString() + "\n";
|
||||||
|
s += "relays " + String(io.relayMask(), BIN) + " inputs " + String(io.inputMask(), BIN) + "\n";
|
||||||
|
s += "relay_pw " + String(store.relayPw() ? "set" : "none") + " link_relay " + String(store.linkRelayEnabled()) +
|
||||||
|
" push_en " + String((int)(store.cfg["input_link_url"]["en"] | 0)) + " udp2 " + String(udpStrOpen) + "\n";
|
||||||
|
s += "booth " + String(boothOk ? "UP" : "DOWN") + " (HTTP " + String(boothCode) + ", fails " + String(wdFails) + ") watchdog " +
|
||||||
|
String(wdEnabled) + " pc_resets " + String(wdResets) + "\n";
|
||||||
|
s += "cloud " + String(cloudOk ? "ok" : "unreachable") + " heap " + String(ESP.getFreeHeap()) + "\n";
|
||||||
|
http.send(200, "text/plain", s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// PoC-only helper: back to factory state so the booth's assign flow can be re-run.
|
||||||
|
static void onFactoryReset() {
|
||||||
|
store.makeDefaults();
|
||||||
|
store.save();
|
||||||
|
store.webUser = "admin";
|
||||||
|
store.webPass = "admin";
|
||||||
|
store.saveWeb();
|
||||||
|
applyProtocolConfig();
|
||||||
|
logf("FACTORY RESET");
|
||||||
|
http.send(200, "application/json", "{\"status\":0}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- wifi ------------------------------------------------------------------
|
||||||
|
static void connectWifi() {
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
WiFi.setAutoReconnect(true);
|
||||||
|
WiFi.hostname("relay-proxy");
|
||||||
|
#ifdef STATIC_IP
|
||||||
|
IPAddress ip, gw, mask;
|
||||||
|
ip.fromString(STATIC_IP);
|
||||||
|
gw.fromString(STATIC_GW);
|
||||||
|
mask.fromString(STATIC_MASK);
|
||||||
|
WiFi.config(ip, gw, mask, gw);
|
||||||
|
#endif
|
||||||
|
WiFi.begin(WIFI_SSID, WIFI_PASS);
|
||||||
|
logf("wifi: connecting to %s", WIFI_SSID);
|
||||||
|
uint32_t t0 = millis();
|
||||||
|
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(200);
|
||||||
|
if (WiFi.status() == WL_CONNECTED) logf("wifi: %s rssi %d", WiFi.localIP().toString().c_str(), WiFi.RSSI());
|
||||||
|
else logf("wifi: not connected yet (status %d) — will keep retrying", WiFi.status());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- setup / loop ----------------------------------------------------------
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(100);
|
||||||
|
Serial.println();
|
||||||
|
io.begin();
|
||||||
|
store.begin();
|
||||||
|
devId = WiFi.macAddress();
|
||||||
|
devId.replace(":", "");
|
||||||
|
devId.toLowerCase();
|
||||||
|
logf("relay-proxy starting, id %s, relay_pw %s, link_relay %d", devId.c_str(), store.relayPw() ? "set" : "none",
|
||||||
|
store.linkRelayEnabled());
|
||||||
|
|
||||||
|
connectWifi();
|
||||||
|
|
||||||
|
udpBin.begin(60000);
|
||||||
|
applyProtocolConfig();
|
||||||
|
|
||||||
|
http.on("/", HTTP_GET, onRoot);
|
||||||
|
http.on("/api/v2/config.cgi", HTTP_GET, onConfigGet);
|
||||||
|
http.on("/api/v2/config_set.cgi", HTTP_POST, onConfigSet);
|
||||||
|
http.on("/userset.cgi", HTTP_GET, onUserSet);
|
||||||
|
http.on("/poc/factory_reset", HTTP_POST, onFactoryReset);
|
||||||
|
http.onNotFound([] { http.send(404, "text/plain", "not found"); });
|
||||||
|
http.begin();
|
||||||
|
|
||||||
|
lastStable = lastRaw = io.inputMask(); // baseline, no boot events
|
||||||
|
rawSince = millis();
|
||||||
|
wdNextProbe = millis() + 2000;
|
||||||
|
nextHeartbeat = millis() + 3000;
|
||||||
|
nextCommandPoll = millis() + 4000;
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
http.handleClient();
|
||||||
|
handleBinary();
|
||||||
|
handleString();
|
||||||
|
releaseJogs();
|
||||||
|
inputTick();
|
||||||
|
if (WiFi.status() == WL_CONNECTED) {
|
||||||
|
watchdogTick();
|
||||||
|
if (due(nextHeartbeat)) { nextHeartbeat = millis() + HEARTBEAT_MS; heartbeat(); }
|
||||||
|
if (due(nextCommandPoll)) { nextCommandPoll = millis() + COMMAND_POLL_MS; pollCommand(); }
|
||||||
|
}
|
||||||
|
delay(2);
|
||||||
|
}
|
||||||
+1
-1
@@ -172,7 +172,7 @@ Keys with an automated note are tagged **⚑ NOTE**.
|
|||||||
## 27. `anprEntryHint`
|
## 27. `anprEntryHint`
|
||||||
|
|
||||||
- **EN** (en.ts:584, 195 ch): When on, a subscriber's plate read by a lane camera opens the barrier through the normal subscription gate. Off: subscribers must use their card/QR. Plate snapshots are still recorded either way.
|
- **EN** (en.ts:584, 195 ch): When on, a subscriber's plate read by a lane camera opens the barrier through the normal subscription gate. Off: subscribers must use their card/QR. Plate snapshots are still recorded either way.
|
||||||
- **SQ** (sq.ts:595, 207 ch): Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Fotot e targave regjistrohen gjithsesi.
|
- **SQ** (sq.ts:595, 207 ch): Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Snapshot-et e targave regjistrohen gjithsesi.
|
||||||
- **Verdict:**
|
- **Verdict:**
|
||||||
|
|
||||||
## 28. `voucherHint`
|
## 28. `voucherHint`
|
||||||
|
|||||||
+70
-8
@@ -49,11 +49,20 @@ REGISTRY=git.infra.msai.al/mca/parking_solution
|
|||||||
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
|
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
|
||||||
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
|
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
|
||||||
# exists as the pointer; we deploy the sha, not the mover.
|
# exists as the pointer; we deploy the sha, not the mover.
|
||||||
TAG=stage-8fa66c9
|
TAG=stage-32b4d9e
|
||||||
COOKIE_SECURE=0
|
COOKIE_SECURE=0
|
||||||
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
|
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
|
||||||
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
|
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
|
||||||
MODULES_ENTITLED=parking,validation
|
MODULES_ENTITLED=parking,validation
|
||||||
|
# Car Wash review outbox (wiki/concepts/vision-review-outbox.md): the collector's ingest URL
|
||||||
|
# on the Netbird overlay, this booth's PSEUDONYMOUS id (never the site name — the crops leave
|
||||||
|
# the site), and its token — the SAME secret the wash-collector stack lists under that id.
|
||||||
|
CARWASH_REVIEW_URL=http://docker-station.nb.infra:8090/ingest
|
||||||
|
CARWASH_REVIEW_BOOTH_ID=booth-1
|
||||||
|
CARWASH_REVIEW_TOKEN=[[wash_review_token_booth_buzi]]
|
||||||
|
# Also send ENTRY reads as training material (gate view, no wash): 1 = every entry (storage
|
||||||
|
# and bandwidth are not the limit; review what you have time for). N = one in N. 0 = off.
|
||||||
|
CARWASH_REVIEW_ENTRY_SAMPLE=1
|
||||||
VISION_ENABLED=1
|
VISION_ENABLED=1
|
||||||
# Desktop app WS handshake: Origin is tauri://localhost (set explicitly by
|
# Desktop app WS handshake: Origin is tauri://localhost (set explicitly by
|
||||||
# platform-ws.ts, since the native WS plugin has no page context to auto-attach
|
# platform-ws.ts, since the native WS plugin has no page context to auto-attach
|
||||||
@@ -85,7 +94,7 @@ REGISTRY=git.infra.msai.al/mca/parking_solution
|
|||||||
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
|
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
|
||||||
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
|
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
|
||||||
# exists as the pointer; we deploy the sha, not the mover.
|
# exists as the pointer; we deploy the sha, not the mover.
|
||||||
TAG=stage-dbbb051
|
TAG=stage-73ada89
|
||||||
COOKIE_SECURE=0
|
COOKIE_SECURE=0
|
||||||
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
|
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
|
||||||
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
|
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
|
||||||
@@ -110,6 +119,60 @@ EVENT_SIGNING_KEY=[[park_2_event_signing_key]]
|
|||||||
BACKUP_KEY=[[park_2_backup_key]]
|
BACKUP_KEY=[[park_2_backup_key]]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
# Stack — the LAB BENCH (not a booth): a dedicated OptiPlex 7070 provisioned like a booth
|
||||||
|
# (LUKS + TPM, Secure Boot, GRUB edit-lock, Periphery `park-lab`, 2026-10-20) with the
|
||||||
|
# field printer and whatever device is under investigation, so a booth bug can be
|
||||||
|
# reproduced on the booth's exact image before touching a real site. Same compose files +
|
||||||
|
# pinned TAG as the staging booths; the ONLY member entitled to EVERY module, so each
|
||||||
|
# feature the solution offers can be exercised here. Review outbox under its OWN id
|
||||||
|
# (booth-lab) — never a booth's identity, so bench crops stay separable on the collector.
|
||||||
|
# Its own secrets. (2026-10-08 → 2026-10-20 it ran on the shared art-docker-station with
|
||||||
|
# HTTP_PORT/SERVER_PORT/VISION_HOST_PORT remapped; a dedicated host needs none of that.)
|
||||||
|
# See wiki/decisions/fleet-deployment-komodo.md.
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
[[stack]]
|
||||||
|
name = "park-lab"
|
||||||
|
[stack.config]
|
||||||
|
server = "park-lab"
|
||||||
|
git_provider = "git.infra.msai.al"
|
||||||
|
git_account = "komodo"
|
||||||
|
repo = "mca/parking_solution"
|
||||||
|
branch = "stage"
|
||||||
|
file_paths = [
|
||||||
|
"docker-compose.yml",
|
||||||
|
"docker-compose.prod.yml"
|
||||||
|
]
|
||||||
|
registry_provider = "git.infra.msai.al"
|
||||||
|
registry_account = "komodo"
|
||||||
|
environment = """
|
||||||
|
REGISTRY=git.infra.msai.al/mca/parking_solution
|
||||||
|
# Lab: pinned to the SAME stage-<sha> as the booth whose bug is being reproduced (bump
|
||||||
|
# alongside it). A lab may float, but a reproduction must run the booth's exact image.
|
||||||
|
TAG=stage-cb43ad7
|
||||||
|
COOKIE_SECURE=0
|
||||||
|
# EVERY registered module (apps/server/src/modules + @parking/shared MODULES): parking,
|
||||||
|
# validation (the Bar), carwash. The compose default is only parking,validation, so the full
|
||||||
|
# set must be spelled out. The site admin still activates within this set in Setup → Site.
|
||||||
|
MODULES_ENTITLED=parking #,validation,carwash
|
||||||
|
# Review outbox ON for the bench too, under its OWN pseudonymous id (booth-lab) and its own
|
||||||
|
# secret — never a real booth's — so lab crops are separable on the collector (per-booth stats,
|
||||||
|
# the export's booth column) and the reviewer can label bench junk "unusable".
|
||||||
|
CARWASH_REVIEW_URL=http://docker-station.nb.infra:8090/ingest
|
||||||
|
CARWASH_REVIEW_BOOTH_ID=booth-lab
|
||||||
|
CARWASH_REVIEW_TOKEN=[[wash_review_token_booth_lab]]
|
||||||
|
CARWASH_REVIEW_ENTRY_SAMPLE=1
|
||||||
|
VISION_ENABLED=1
|
||||||
|
# Desktop app WS handshake: Origin is tauri://localhost (set explicitly by
|
||||||
|
# platform-ws.ts, since the native WS plugin has no page context to auto-attach
|
||||||
|
# one). Linux may also send http://tauri.localhost. See routes/ws.ts anti-CSWSH check.
|
||||||
|
WS_ALLOWED_ORIGINS=tauri://localhost,http://tauri.localhost
|
||||||
|
JWT_SECRET=[[park_lab_jwt_secret]]
|
||||||
|
EVENT_SIGNING_KEY=[[park_lab_event_signing_key]]
|
||||||
|
BACKUP_KEY=[[park_lab_backup_key]]
|
||||||
|
"""
|
||||||
|
|
||||||
##############################################################################
|
##############################################################################
|
||||||
# Stack — the Car Wash REVIEW COLLECTOR on the reviewer's host (art-docker-station),
|
# Stack — the Car Wash REVIEW COLLECTOR on the reviewer's host (art-docker-station),
|
||||||
# NOT a booth. Same repo/branch/TAG promotion as the booths, but its file_paths name
|
# NOT a booth. Same repo/branch/TAG promotion as the booths, but its file_paths name
|
||||||
@@ -134,7 +197,7 @@ registry_account = "komodo"
|
|||||||
environment = """
|
environment = """
|
||||||
REGISTRY=git.infra.msai.al/mca/parking_solution
|
REGISTRY=git.infra.msai.al/mca/parking_solution
|
||||||
# Pinned like the booths: bump to the stage-<sha> that carries the collector.
|
# Pinned like the booths: bump to the stage-<sha> that carries the collector.
|
||||||
TAG=stage-f7a262a
|
TAG=stage-32b4d9e
|
||||||
# The host's NETBIRD address (an IP: Docker port bindings take no hostname) — the ingest port
|
# The host's NETBIRD address (an IP: Docker port bindings take no hostname) — the ingest port
|
||||||
# is published on the overlay only. Booths reach it by its Netbird DNS name.
|
# is published on the overlay only. Booths reach it by its Netbird DNS name.
|
||||||
COLLECTOR_BIND=100.75.184.156
|
COLLECTOR_BIND=100.75.184.156
|
||||||
@@ -142,11 +205,10 @@ COLLECTOR_BIND=100.75.184.156
|
|||||||
# that booth's own stack as its CARWASH_REVIEW_TOKEN — one value, two consumers, nothing
|
# that booth's own stack as its CARWASH_REVIEW_TOKEN — one value, two consumers, nothing
|
||||||
# to keep in sync, and rotating a booth touches one secret. The booth id is the booth's
|
# to keep in sync, and rotating a booth touches one secret. The booth id is the booth's
|
||||||
# pseudonymous CARWASH_REVIEW_BOOTH_ID, never a site name. Add a pair per booth.
|
# pseudonymous CARWASH_REVIEW_BOOTH_ID, never a site name. Add a pair per booth.
|
||||||
COLLECTOR_BOOTH_TOKENS=booth-2:[[wash_review_token_booth_2]]
|
COLLECTOR_BOOTH_TOKENS=booth-2:[[wash_review_token_booth_2]],booth-1:[[wash_review_token_booth_buzi]],booth-lab:[[wash_review_token_booth_lab]]
|
||||||
# Phase-B trainer (profile "train", a one-off job on this host — never started by the deploy).
|
# Phase-B trainer (the `trainer` service beside the collector; the Training section of /review
|
||||||
# Its output folder on the host, and the Gitea token `publish` uses to upload a passing model to
|
# is its UI). Only `publish` needs this: a Gitea token with package:write for the model's generic
|
||||||
# the generic package registry (package:write). Uncomment when the first model is to be published.
|
# package. Uncomment when the first model is to be published.
|
||||||
#TRAINER_OUT=/opt/parking/models
|
|
||||||
#TRAINER_PUBLISH_TOKEN=[[gitea_package_write_token]]
|
#TRAINER_PUBLISH_TOKEN=[[gitea_package_write_token]]
|
||||||
COLLECTOR_REVIEWER_USER=reviewer
|
COLLECTOR_REVIEWER_USER=reviewer
|
||||||
COLLECTOR_REVIEWER_PASS=[[wash_collector_reviewer_pass]]
|
COLLECTOR_REVIEWER_PASS=[[wash_collector_reviewer_pass]]
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- Hot-path indexes (park-2, 2026-10-24). Every per-session read of the ledger was a full
|
||||||
|
-- scan (no index on identity), and the camera/relay telemetry queries scanned
|
||||||
|
-- device_events (no index beyond the PK). Both tables grow with the operator's traffic,
|
||||||
|
-- so request time grew with it: the booth's active-sessions call reached ~2 s and froze
|
||||||
|
-- the event loop, which surfaced as relay "timeouts". The handler was also rewritten to
|
||||||
|
-- avoid per-row reads; these indexes make the remaining identity/telemetry lookups O(log n)
|
||||||
|
-- whatever the data volume. All additive; the previous image ignores them on rollback.
|
||||||
|
CREATE INDEX IF NOT EXISTS `ledger_events_identity_idx` ON `ledger_events` (`identity`,`index`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `device_events_cat_kind_time_idx` ON `device_events` (`category`,`kind`,`occurred_at`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `device_events_kind_time_idx` ON `device_events` (`kind`,`occurred_at`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `snapshots_identity_idx` ON `snapshots` (`identity`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `sessions_state_idx` ON `sessions` (`state`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `sessions_subscription_idx` ON `sessions` (`subscription_id`,`state`);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Booth camera tiles (wiki/decisions/camera-live-view.md). Two additive changes:
|
||||||
|
-- * users.open_cameras: the camera tiles a user left open (JSON array of device ids),
|
||||||
|
-- restored on the next login from any booth, like language/theme/font_scale.
|
||||||
|
-- * an index for "the latest snapshot this camera took" — the tile's default picture.
|
||||||
|
-- Without it the lookup scans every stored image row (the bounded-request-cost rule,
|
||||||
|
-- park-2 2026-10-24). The previous image ignores both on rollback.
|
||||||
|
ALTER TABLE `users` ADD `open_cameras` text DEFAULT '[]' NOT NULL;
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX IF NOT EXISTS `snapshots_device_time_idx` ON `snapshots` (`device_id`,`captured_at`);
|
||||||
@@ -225,6 +225,20 @@
|
|||||||
"when": 1788710000000,
|
"when": 1788710000000,
|
||||||
"tag": "0031_carwash_review_outbox",
|
"tag": "0031_carwash_review_outbox",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 32,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1788720000000,
|
||||||
|
"tag": "0032_hot_path_indexes",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 33,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1788730000000,
|
||||||
|
"tag": "0033_camera_live_view",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,10 @@ const CATEGORIES = {
|
|||||||
"subscription_credentials",
|
"subscription_credentials",
|
||||||
"subscriptions",
|
"subscriptions",
|
||||||
"blocklist",
|
"blocklist",
|
||||||
|
// Car Wash (venue module): orders are money history (settled against ledger events);
|
||||||
|
// the review outbox is a delivery queue of crops + choices — both go with the ledger.
|
||||||
|
"carwash_review_outbox",
|
||||||
|
"carwash_orders",
|
||||||
],
|
],
|
||||||
config: [
|
config: [
|
||||||
"site_config",
|
"site_config",
|
||||||
@@ -65,8 +69,15 @@ const CATEGORIES = {
|
|||||||
// whose user is gone grants nothing.
|
// whose user is gone grants nothing.
|
||||||
"validation_program_users",
|
"validation_program_users",
|
||||||
"validation_programs",
|
"validation_programs",
|
||||||
|
// Car Wash master data: prices reference categories + services (child first); the
|
||||||
|
// module's site-level config (pay-at, vision threshold) is config like site_config.
|
||||||
|
"carwash_prices",
|
||||||
|
"carwash_categories",
|
||||||
|
"carwash_services",
|
||||||
|
"carwash_config",
|
||||||
],
|
],
|
||||||
users: ["sessions", "role_permissions", "users", "roles"],
|
// role_jobs = which jobs a role follows (child of roles).
|
||||||
|
users: ["sessions", "role_permissions", "role_jobs", "users", "roles"],
|
||||||
diagnostics: ["app_logs"],
|
diagnostics: ["app_logs"],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -96,6 +96,10 @@ export const users = sqliteTable("users", {
|
|||||||
// avoids float drift; the client clamps to 80–160 in steps of 10. Printed tickets are
|
// avoids float drift; the client clamps to 80–160 in steps of 10. Printed tickets are
|
||||||
// unaffected (server-rendered).
|
// unaffected (server-rendered).
|
||||||
fontScale: integer("font_scale").notNull().default(100),
|
fontScale: integer("font_scale").notNull().default(100),
|
||||||
|
// Camera tiles this user left open on the booth screen (JSON array of camera device
|
||||||
|
// ids, in the order opened). Persisted like `theme`; restored on login from any booth.
|
||||||
|
// See wiki/decisions/camera-live-view.md.
|
||||||
|
openCameras: text("open_cameras").notNull().default("[]"),
|
||||||
// Optional operator profile metadata — display name + contact details. All
|
// Optional operator profile metadata — display name + contact details. All
|
||||||
// nullable; only username/password/role are required to create a user. fullName
|
// nullable; only username/password/role are required to create a user. fullName
|
||||||
// (when set) is the human label for audit/Z-report display.
|
// (when set) is the human label for audit/Z-report display.
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -77,7 +77,13 @@ function binaryUdp(
|
|||||||
sock.close();
|
sock.close();
|
||||||
err ? reject(err) : resolve(val!);
|
err ? reject(err) : resolve(val!);
|
||||||
};
|
};
|
||||||
const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs);
|
// On expiry, defer the rejection by one loop turn. Node runs expired timers BEFORE
|
||||||
|
// it drains pending socket I/O, so if the event loop was blocked (a long synchronous
|
||||||
|
// handler) while the device's reply sat in the kernel buffer, the timer would win
|
||||||
|
// and report "timeout" for a relay that answered. The setImmediate lands in the
|
||||||
|
// check phase, after the poll phase has delivered that datagram to `message`.
|
||||||
|
// (park-2, 2026-10-24: ~2 s handler stalls produced exactly these phantom timeouts.)
|
||||||
|
const timer = setTimeout(() => setImmediate(() => done(new Error("timeout"), null)), timeoutMs);
|
||||||
sock.on("error", (e) => done(e, null));
|
sock.on("error", (e) => done(e, null));
|
||||||
sock.on("message", (m) => done(null, m));
|
sock.on("message", (m) => done(null, m));
|
||||||
// Bind to a specific local address (the device-facing NIC) on multi-homed
|
// Bind to a specific local address (the device-facing NIC) on multi-homed
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
|
|||||||
const timeXml = (localTime: string) =>
|
const timeXml = (localTime: string) =>
|
||||||
reply(
|
reply(
|
||||||
200,
|
200,
|
||||||
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00DST01:00:00</timeZone></Time>`,
|
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00</timeZone></Time>`,
|
||||||
);
|
);
|
||||||
const HOST_NOW = "2026-07-07T12:00:00+02:00";
|
const HOST_NOW = "2026-07-07T12:00:00+02:00";
|
||||||
|
|
||||||
@@ -166,11 +166,11 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
|
|||||||
it("in-sync camera: reads, does NOT set", async () => {
|
it("in-sync camera: reads, does NOT set", async () => {
|
||||||
digestRequest.mockResolvedValueOnce(timeXml("2026-07-07T12:00:10+02:00"));
|
digestRequest.mockResolvedValueOnce(timeXml("2026-07-07T12:00:10+02:00"));
|
||||||
const r = await cam().syncClock(HOST_NOW, 60);
|
const r = await cam().syncClock(HOST_NOW, 60);
|
||||||
expect(r).toEqual({ driftSeconds: 10, synced: false });
|
expect(r).toEqual({ driftSeconds: 10, synced: false, zoneChanged: false, timeZone: "CST-2:00:00" });
|
||||||
expect(digestRequest).toHaveBeenCalledTimes(1); // GET only
|
expect(digestRequest).toHaveBeenCalledTimes(1); // GET only
|
||||||
});
|
});
|
||||||
|
|
||||||
it("1970 camera: PUTs manual time with the host instant, echoing the camera's timeZone", async () => {
|
it("1970 camera: PUTs manual time with the host instant and the site's fixed-offset zone", async () => {
|
||||||
digestRequest
|
digestRequest
|
||||||
.mockResolvedValueOnce(timeXml("1970-01-01T03:12:44+01:00"))
|
.mockResolvedValueOnce(timeXml("1970-01-01T03:12:44+01:00"))
|
||||||
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
|
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
|
||||||
@@ -182,7 +182,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
|
|||||||
expect(put.path).toBe("/ISAPI/System/time");
|
expect(put.path).toBe("/ISAPI/System/time");
|
||||||
expect(put.body).toContain("<timeMode>manual</timeMode>");
|
expect(put.body).toContain("<timeMode>manual</timeMode>");
|
||||||
expect(put.body).toContain(`<localTime>${HOST_NOW}</localTime>`);
|
expect(put.body).toContain(`<localTime>${HOST_NOW}</localTime>`);
|
||||||
expect(put.body).toContain("<timeZone>CST-2:00:00DST01:00:00</timeZone>"); // echoed, never invented
|
expect(put.body).toContain("<timeZone>CST-2:00:00</timeZone>"); // the host's current offset, never the camera's DST rule
|
||||||
});
|
});
|
||||||
|
|
||||||
it("unparseable camera time = infinite drift → syncs", async () => {
|
it("unparseable camera time = infinite drift → syncs", async () => {
|
||||||
@@ -190,7 +190,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
|
|||||||
.mockResolvedValueOnce(reply(200, "<Time><localTime>garbage</localTime></Time>"))
|
.mockResolvedValueOnce(reply(200, "<Time><localTime>garbage</localTime></Time>"))
|
||||||
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
|
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
|
||||||
const r = await cam().syncClock(HOST_NOW, 60);
|
const r = await cam().syncClock(HOST_NOW, 60);
|
||||||
expect(r).toEqual({ driftSeconds: null, synced: true });
|
expect(r).toMatchObject({ driftSeconds: null, synced: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("a failed set surfaces as an error (monitor logs it, backstop retries)", async () => {
|
it("a failed set surfaces as an error (monitor logs it, backstop retries)", async () => {
|
||||||
@@ -200,12 +200,167 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
|
|||||||
await expect(cam().syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 403");
|
await expect(cam().syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 403");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("the dahua driver does NOT claim the capability (no ISAPI time endpoint)", async () => {
|
it("both camera drivers claim the capability (Dahua via global.cgi since 2026-09-17)", async () => {
|
||||||
const { dahuaDriver, hikvisionDriver } = await import("./camera.js");
|
const { dahuaDriver, hikvisionDriver } = await import("./camera.js");
|
||||||
const { isClockSyncable } = await import("../interfaces.js");
|
const { isClockSyncable } = await import("../interfaces.js");
|
||||||
const mk = (d: typeof dahuaDriver) =>
|
const mk = (d: typeof dahuaDriver) =>
|
||||||
d.create({ host: "10.0.10.12", port: 80, username: "admin", password: "x", channel: 1 });
|
d.create({ host: "10.0.10.12", port: 80, username: "admin", password: "x", channel: 1 });
|
||||||
expect(isClockSyncable(mk(dahuaDriver))).toBe(false);
|
expect(isClockSyncable(mk(dahuaDriver))).toBe(true);
|
||||||
expect(isClockSyncable(mk(hikvisionDriver))).toBe(true);
|
expect(isClockSyncable(mk(hikvisionDriver))).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Dahua — verified against an IPC-HFW2549T-AS-IL (fw 2.880) on 2026-09-17. The CGI
|
||||||
|
// numbers snapshot channels from 1 (channel=0 → HTTP 400), ignores any stream
|
||||||
|
// selector, and speaks NAIVE local wall time on global.cgi. See camera.ts and
|
||||||
|
// wiki/entities/dahua-ipc-hfw2549t.md.
|
||||||
|
describe("dahua snapshot URL — channel is 1-BASED, no stream selector", () => {
|
||||||
|
async function pathFor(config: Record<string, unknown>): Promise<string> {
|
||||||
|
const { dahuaDriver } = await import("./camera.js");
|
||||||
|
digestGet.mockReset();
|
||||||
|
digestGet.mockResolvedValue(reply(200));
|
||||||
|
dahuaDriver.create(config as never).captureSnapshot({ direction: "entry" });
|
||||||
|
return String((digestGet.mock.calls[0]![0] as { path: string }).path);
|
||||||
|
}
|
||||||
|
|
||||||
|
it("channel 1 as entered → channel=1 (the old `ch - 1` sent 0 → HTTP 400 on hardware)", async () => {
|
||||||
|
expect(await pathFor({ host: "1.2.3.4", channel: 1 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults to channel 1 when none is configured", async () => {
|
||||||
|
expect(await pathFor({ host: "1.2.3.4" })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("channel 2 passes through; a stream setting is ignored", async () => {
|
||||||
|
expect(await pathFor({ host: "1.2.3.4", channel: 2, stream: 2 })).toBe("/cgi-bin/snapshot.cgi?channel=2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a zero/negative channel is clamped to 1 rather than sent as-is", async () => {
|
||||||
|
expect(await pathFor({ host: "1.2.3.4", channel: 0 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wall time", () => {
|
||||||
|
const HOST_NOW = "2026-09-17T10:35:49+02:00";
|
||||||
|
const timeReply = (naive: string) => reply(200, `result=${naive}\r\n`);
|
||||||
|
|
||||||
|
async function cam() {
|
||||||
|
const { dahuaDriver } = await import("./camera.js");
|
||||||
|
return dahuaDriver.create({ host: "10.0.10.11", port: 80, username: "admin", password: "x", channel: 1 }) as unknown as {
|
||||||
|
syncClock(localIso: string, maxDriftSec: number): Promise<{ driftSeconds: number | null; synced: boolean }>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
it("in-sync camera: reads, does NOT set", async () => {
|
||||||
|
digestRequest.mockResolvedValueOnce(timeReply("2026-09-17 10:35:40"));
|
||||||
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
||||||
|
expect(r).toEqual({ driftSeconds: 9, synced: false });
|
||||||
|
expect(digestRequest).toHaveBeenCalledTimes(1);
|
||||||
|
const get = digestRequest.mock.calls[0]![0] as { method: string; path: string };
|
||||||
|
expect(get.method).toBe("GET");
|
||||||
|
expect(get.path).toBe("/cgi-bin/global.cgi?action=getCurrentTime");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("an hour behind (the bench unit: DST off, NTP off) → sets the HOST wall time, no offset", async () => {
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(timeReply("2026-09-17 09:35:51"))
|
||||||
|
.mockResolvedValueOnce(reply(200, "OK\r\n"));
|
||||||
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
||||||
|
expect(r).toEqual({ driftSeconds: 3598, synced: true });
|
||||||
|
const set = digestRequest.mock.calls[1]![0] as { method: string; path: string };
|
||||||
|
expect(set.method).toBe("GET");
|
||||||
|
expect(set.path).toBe("/cgi-bin/global.cgi?action=setCurrentTime&time=2026-09-17%2010%3A35%3A49");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unparseable camera reply = infinite drift → syncs", async () => {
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(reply(200, "Error\r\nBad Request!"))
|
||||||
|
.mockResolvedValueOnce(reply(200, "OK"));
|
||||||
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
||||||
|
expect(r).toMatchObject({ driftSeconds: null, synced: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a 200 whose body is not OK is still a failed set (Dahua's 'Error' convention)", async () => {
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
|
||||||
|
.mockResolvedValueOnce(reply(200, "Error\r\nInvalid Argument!"));
|
||||||
|
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 200 Error");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a non-200 set surfaces as an error", async () => {
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
|
||||||
|
.mockResolvedValueOnce(reply(401, "denied"));
|
||||||
|
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 401");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Hikvision clock sync: the zone is the host's FIXED current offset -------------
|
||||||
|
// park-2 2026-10-09: both cameras sat on the factory CST-8 (Beijing) — instant right,
|
||||||
|
// OSD six hours off — and this firmware ignores the DST rule in a POSIX zone string. So
|
||||||
|
// the sync rewrites the zone to the site's current fixed offset and re-sends the clock
|
||||||
|
// with it; a camera already on the right zone with small drift is left alone.
|
||||||
|
|
||||||
|
const { hikvisionFixedZone } = await import("./camera.js");
|
||||||
|
|
||||||
|
function timeXml(localTime: string, timeZone: string) {
|
||||||
|
return (
|
||||||
|
`<?xml version="1.0" encoding="UTF-8"?><Time version="2.0"><timeMode>manual</timeMode>` +
|
||||||
|
`<localTime>${localTime}</localTime><timeZone>${timeZone}</timeZone></Time>`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function xmlReply(status: number, body: string): DigestGetResult {
|
||||||
|
return { status, contentType: "application/xml", body: Buffer.from(body) };
|
||||||
|
}
|
||||||
|
function putCalls() {
|
||||||
|
return digestRequest.mock.calls
|
||||||
|
.map((c) => c[0] as { method: string; path: string; body?: string })
|
||||||
|
.filter((c) => c.method === "PUT");
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("hikvisionFixedZone", () => {
|
||||||
|
it("inverts the sign the POSIX way and keeps minutes", () => {
|
||||||
|
expect(hikvisionFixedZone("2026-10-09T19:01:08+02:00")).toBe("CST-2:00:00");
|
||||||
|
expect(hikvisionFixedZone("2026-12-09T18:01:08+01:00")).toBe("CST-1:00:00");
|
||||||
|
expect(hikvisionFixedZone("2026-10-09T09:01:08-05:30")).toBe("CST+5:30:00");
|
||||||
|
expect(hikvisionFixedZone("2026-10-09T17:01:08+00:00")).toBe("CST0:00:00");
|
||||||
|
});
|
||||||
|
it("refuses a host time without an offset", () => {
|
||||||
|
expect(() => hikvisionFixedZone("2026-10-09T19:01:08")).toThrow(/utc offset/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("hikvision syncClock — zone", () => {
|
||||||
|
it("rewrites a factory CST-8 zone even when the instant is right", async () => {
|
||||||
|
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean; timeZone?: string; driftSeconds: number | null }> };
|
||||||
|
// Same instant as the host (17:01:08Z), shown in Beijing time.
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-10T01:01:08+08:00", "CST-8:00:00")))
|
||||||
|
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
|
||||||
|
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
|
||||||
|
expect(r).toMatchObject({ synced: true, zoneChanged: true, timeZone: "CST-2:00:00", driftSeconds: 0 });
|
||||||
|
const puts = putCalls();
|
||||||
|
expect(puts).toHaveLength(1);
|
||||||
|
expect(puts[0].path).toBe("/ISAPI/System/time");
|
||||||
|
expect(puts[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
|
||||||
|
expect(puts[0].body).toContain("<localTime>2026-10-09T19:01:08+02:00</localTime>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves a camera on the right zone with small drift alone", async () => {
|
||||||
|
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
|
||||||
|
digestRequest.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-09T19:01:20+02:00", "CST-2:00:00")));
|
||||||
|
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
|
||||||
|
expect(r).toMatchObject({ synced: false, zoneChanged: false });
|
||||||
|
expect(putCalls()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-sets the clock (same zone) when drift exceeds the threshold", async () => {
|
||||||
|
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
|
||||||
|
digestRequest
|
||||||
|
.mockResolvedValueOnce(xmlReply(200, timeXml("1970-01-01T08:00:00+02:00", "CST-2:00:00")))
|
||||||
|
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
|
||||||
|
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
|
||||||
|
expect(r).toMatchObject({ synced: true, zoneChanged: false });
|
||||||
|
expect(putCalls()[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
CameraDevice,
|
CameraDevice,
|
||||||
|
LiveStreamDevice,
|
||||||
|
LiveVideoSource,
|
||||||
ClockSyncResult,
|
ClockSyncResult,
|
||||||
DeviceHealth,
|
DeviceHealth,
|
||||||
Snapshot,
|
Snapshot,
|
||||||
@@ -14,12 +16,17 @@ import {
|
|||||||
stubLog,
|
stubLog,
|
||||||
} from "./common.js";
|
} from "./common.js";
|
||||||
import { digestGet, digestRequest } from "./http-digest.js";
|
import { digestGet, digestRequest } from "./http-digest.js";
|
||||||
|
import { RtspMjpegStream } from "./rtsp-mjpeg.js";
|
||||||
|
|
||||||
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
|
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
|
||||||
// HTTP when an event fires; the bytes are stored and referenced from the signed
|
// HTTP when an event fires; the bytes are stored and referenced from the signed
|
||||||
// event as an independent fraud-control record (the camera PULLS, it never pushes
|
// event as an independent fraud-control record (the camera PULLS, it never pushes
|
||||||
// to us). Hikvision (ISAPI) and Dahua (CGI) differ only in the snapshot URL and
|
// to us). Hikvision (ISAPI) and Dahua (CGI) differ in the snapshot URL, the
|
||||||
// channel encoding. Both use HTTP Digest auth (see ./http-digest.ts).
|
// channel encoding and the clock endpoint. Both use HTTP Digest auth (see ./http-digest.ts).
|
||||||
|
//
|
||||||
|
// VERIFIED on hardware (2026-09-17): a Dahua IPC-HFW2549T-AS-IL (fw 2.880) at
|
||||||
|
// 10.0.10.11 returns a 2880×1620 JPEG from /cgi-bin/snapshot.cgi?channel=1 —
|
||||||
|
// and HTTP 400 for channel=0. See wiki/entities/dahua-ipc-hfw2549t.md.
|
||||||
//
|
//
|
||||||
// VERIFIED on hardware (2026-06-15): a Hikvision unit at 10.0.10.121 returns a
|
// VERIFIED on hardware (2026-06-15): a Hikvision unit at 10.0.10.121 returns a
|
||||||
// 2688×1520 JPEG from /ISAPI/Streaming/channels/101/picture with Digest auth.
|
// 2688×1520 JPEG from /ISAPI/Streaming/channels/101/picture with Digest auth.
|
||||||
@@ -70,6 +77,8 @@ class HttpCamera implements CameraDevice {
|
|||||||
// Source outbound from the device-facing NIC on a multi-homed host (the
|
// Source outbound from the device-facing NIC on a multi-homed host (the
|
||||||
// multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md).
|
// multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md).
|
||||||
readonly #localAddress: string | undefined;
|
readonly #localAddress: string | undefined;
|
||||||
|
/** RTSP port for the live view (not a Setup field: 554 everywhere so far). */
|
||||||
|
readonly #rtspPort: number;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
readonly driverId: string,
|
readonly driverId: string,
|
||||||
@@ -88,6 +97,7 @@ class HttpCamera implements CameraDevice {
|
|||||||
this.#localAddress = config.localAddress
|
this.#localAddress = config.localAddress
|
||||||
? String(config.localAddress)
|
? String(config.localAddress)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
this.#rtspPort = Number(config.rtspPort ?? 554);
|
||||||
}
|
}
|
||||||
|
|
||||||
async connect(): Promise<void> {}
|
async connect(): Promise<void> {}
|
||||||
@@ -139,10 +149,9 @@ class HttpCamera implements CameraDevice {
|
|||||||
`${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}${busy}`,
|
`${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}${busy}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
stubLog(
|
// Per-snapshot chatter → debug (a busy lane logs one every few seconds); the retry
|
||||||
this.driverId,
|
// and failure lines above stay at info/throw.
|
||||||
`captureSnapshot ${ctx.direction} (${res.body.length} bytes)`,
|
stubLog(this.driverId, `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`, "debug");
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
bytes: res.body,
|
bytes: res.body,
|
||||||
contentType: res.contentType || "image/jpeg",
|
contentType: res.contentType || "image/jpeg",
|
||||||
@@ -162,8 +171,25 @@ class HttpCamera implements CameraDevice {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Digest request against an arbitrary device path (ISAPI config reads/writes). */
|
/** An RTSP MJPEG session on `path` with this camera's address + credentials. */
|
||||||
protected isapi(method: "GET" | "PUT", path: string, body?: string) {
|
protected rtspStream(path: string): LiveVideoSource {
|
||||||
|
return new RtspMjpegStream({
|
||||||
|
host: this.#host,
|
||||||
|
port: this.#rtspPort,
|
||||||
|
path,
|
||||||
|
user: this.#user,
|
||||||
|
password: this.#password,
|
||||||
|
timeoutMs: this.#timeout,
|
||||||
|
...(this.#localAddress ? { localAddress: this.#localAddress } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected get channel(): number {
|
||||||
|
return this.#channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Digest request against an arbitrary device path (ISAPI / CGI config reads+writes). */
|
||||||
|
protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) {
|
||||||
return digestRequest({
|
return digestRequest({
|
||||||
host: this.#host,
|
host: this.#host,
|
||||||
port: this.#port,
|
port: this.#port,
|
||||||
@@ -186,24 +212,62 @@ class HttpCamera implements CameraDevice {
|
|||||||
// ANPR pushes. So the host (the site's time authority — offline-first, no NTP
|
// ANPR pushes. So the host (the site's time authority — offline-first, no NTP
|
||||||
// dependency) re-syncs the camera over the same Digest-auth ISAPI used for
|
// dependency) re-syncs the camera over the same Digest-auth ISAPI used for
|
||||||
// snapshots. The device monitor calls this at the offline→ready edge (the
|
// snapshots. The device monitor calls this at the offline→ready edge (the
|
||||||
// power-restored moment) + a daily backstop. See wiki/entities/lpr-camera.md.
|
// power-restored moment), a daily backstop, and whenever the site's UTC offset
|
||||||
|
// changes (DST). See wiki/entities/lpr-camera.md.
|
||||||
|
//
|
||||||
|
// TIME ZONE: the OSD shows the camera's LOCAL time = instant + its `timeZone` setting.
|
||||||
|
// park-2 (2026-10-09) ran both cameras on the factory CST-8 (Beijing): the instant was
|
||||||
|
// right, the burned-in time six hours off, and a correct-instant sync never touched it.
|
||||||
|
// This firmware (DS-2CD1047G3H) also ignores the DST rule in a POSIX-style zone string
|
||||||
|
// ("CET-1:00:00DST01:00:00,M3.5.0/02:00:00,M10.5.0/03:00:00" was accepted, echoed back,
|
||||||
|
// and NOT applied — OSD stayed on +01:00 in October). So the host owns DST too: the zone
|
||||||
|
// is written as a FIXED offset equal to the site's CURRENT offset ("CST-2:00:00" in summer,
|
||||||
|
// "CST-1:00:00" in winter — Hikvision's inverted POSIX sign) and rewritten at the next
|
||||||
|
// sync after the site's offset changes. The abbreviation is cosmetic (the camera renames
|
||||||
|
// whatever we send to "CST").
|
||||||
|
|
||||||
class HikvisionCamera extends HttpCamera {
|
/** The Hikvision `timeZone` string for a FIXED offset equal to `localIso`'s UTC offset:
|
||||||
|
* "+02:00" → "CST-2:00:00", "-05:30" → "CST+5:30:00", "+00:00" → "CST0:00:00". */
|
||||||
|
export function hikvisionFixedZone(localIso: string): string {
|
||||||
|
const m = localIso.match(/([+-])(\d{2}):(\d{2})$/);
|
||||||
|
if (!m) throw new Error(`syncClock: host time has no utc offset: ${localIso}`);
|
||||||
|
const hours = Number(m[2]);
|
||||||
|
const minutes = m[3];
|
||||||
|
if (hours === 0 && minutes === "00") return "CST0:00:00";
|
||||||
|
// POSIX (and Hikvision) sign is inverted: east of UTC is negative.
|
||||||
|
const sign = m[1] === "+" ? "-" : "+";
|
||||||
|
return `CST${sign}${hours}:${minutes}:00`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class HikvisionCamera extends HttpCamera implements LiveStreamDevice {
|
||||||
/**
|
/**
|
||||||
* Read the camera clock; when it drifts more than `maxDriftSec` from `localIso`
|
* Live view for the booth's camera tiles: the channel's SUB-stream (x02) over RTSP,
|
||||||
* (the site's wall-clock now, WITH utc offset), set it via
|
* which must be set to MJPEG on the camera (H.264 is refused with that reason).
|
||||||
* PUT /ISAPI/System/time. The camera's own `timeZone` string is echoed back
|
* The ANPR/evidence stills keep coming from /picture on the configured stream —
|
||||||
* verbatim — we correct the CLOCK, never fight the tz/DST config; `localIso`'s
|
* the codec of the sub-stream does not change them (measured on park-lab
|
||||||
* explicit offset makes the instant unambiguous regardless of that config.
|
* 2026-11-17: no extra 503s with a stream open). See wiki/decisions/camera-live-view.md.
|
||||||
|
*/
|
||||||
|
openLiveStream(): LiveVideoSource {
|
||||||
|
return this.rtspStream(`/Streaming/Channels/${this.channel}02`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read the camera clock + zone. Rewrite the zone when it is not the site's current
|
||||||
|
* fixed offset (see above); otherwise set the clock only when it drifts more than
|
||||||
|
* `maxDriftSec` from `localIso` (the site's wall-clock now, WITH utc offset). The PUT
|
||||||
|
* always carries both: `localIso`'s explicit offset makes the instant unambiguous
|
||||||
|
* regardless of the zone the camera applies to it.
|
||||||
*/
|
*/
|
||||||
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
|
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
|
||||||
const read = await this.isapi("GET", "/ISAPI/System/time");
|
const read = await this.deviceRequest("GET", "/ISAPI/System/time");
|
||||||
if (read.status !== 200) {
|
if (read.status !== 200) {
|
||||||
throw new Error(`clock read failed: HTTP ${read.status}`);
|
throw new Error(`clock read failed: HTTP ${read.status}`);
|
||||||
}
|
}
|
||||||
const xml = read.body.toString("utf8");
|
const xml = read.body.toString("utf8");
|
||||||
const cameraTime = xml.match(/<localTime>([^<]+)<\/localTime>/)?.[1]?.trim() ?? null;
|
const cameraTime = xml.match(/<localTime>([^<]+)<\/localTime>/)?.[1]?.trim() ?? null;
|
||||||
const timeZone = xml.match(/<timeZone>([^<]+)<\/timeZone>/)?.[1]?.trim() ?? "";
|
const timeZone = xml.match(/<timeZone>([^<]+)<\/timeZone>/)?.[1]?.trim() ?? "";
|
||||||
|
const wantZone = hikvisionFixedZone(localIso);
|
||||||
|
const zoneChanged = timeZone !== wantZone;
|
||||||
|
|
||||||
// Drift: parse both sides as instants. A camera reply without a UTC offset (or
|
// Drift: parse both sides as instants. A camera reply without a UTC offset (or
|
||||||
// otherwise unparseable) can't be trusted → treat as infinite drift and sync.
|
// otherwise unparseable) can't be trusted → treat as infinite drift and sync.
|
||||||
@@ -212,19 +276,83 @@ class HikvisionCamera extends HttpCamera {
|
|||||||
const driftSeconds = Number.isFinite(cameraMs)
|
const driftSeconds = Number.isFinite(cameraMs)
|
||||||
? Math.round(Math.abs(hostMs - cameraMs) / 1000)
|
? Math.round(Math.abs(hostMs - cameraMs) / 1000)
|
||||||
: null;
|
: null;
|
||||||
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
|
if (!zoneChanged && driftSeconds != null && driftSeconds <= maxDriftSec) {
|
||||||
return { driftSeconds, synced: false };
|
return { driftSeconds, synced: false, zoneChanged: false, timeZone };
|
||||||
}
|
}
|
||||||
|
|
||||||
const body =
|
const body =
|
||||||
`<?xml version="1.0" encoding="UTF-8"?>` +
|
`<?xml version="1.0" encoding="UTF-8"?>` +
|
||||||
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
|
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
|
||||||
(timeZone ? `<timeZone>${timeZone}</timeZone>` : "") +
|
`<timeZone>${wantZone}</timeZone>` +
|
||||||
`</Time>`;
|
`</Time>`;
|
||||||
const put = await this.isapi("PUT", "/ISAPI/System/time", body);
|
const put = await this.deviceRequest("PUT", "/ISAPI/System/time", body);
|
||||||
if (put.status !== 200) {
|
if (put.status !== 200) {
|
||||||
throw new Error(`clock set failed: HTTP ${put.status}`);
|
throw new Error(`clock set failed: HTTP ${put.status}`);
|
||||||
}
|
}
|
||||||
|
stubLog(
|
||||||
|
this.driverId,
|
||||||
|
`clock synced (was ${driftSeconds ?? "unparseable"}s off${zoneChanged ? `; zone ${timeZone || "unset"} → ${wantZone}` : ""})`,
|
||||||
|
);
|
||||||
|
return { driftSeconds, synced: true, zoneChanged, timeZone: wantZone };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Dahua clock sync (CGI global.cgi getCurrentTime / setCurrentTime) --------------
|
||||||
|
// Same problem, different surface. The Dahua CGI reads and writes the clock as a
|
||||||
|
// NAIVE local wall-time string ("2026-09-17 10:35:49", no offset) in whatever time
|
||||||
|
// zone / DST the camera is configured for. We deliberately write the HOST's local
|
||||||
|
// wall time verbatim: what must match the booth is the OSD timestamp burned into
|
||||||
|
// every snapshot and the event times, i.e. the wall clock — not the camera's idea
|
||||||
|
// of UTC. (The bench unit ran a year-round UTC+1 with DST off and NTP off; after
|
||||||
|
// this sync its OSD read the booth's time.) VERIFIED on hardware 2026-09-17:
|
||||||
|
// setCurrentTime answers 200 "OK" and getCurrentTime reads the new value back.
|
||||||
|
// See wiki/entities/dahua-ipc-hfw2549t.md.
|
||||||
|
|
||||||
|
const DAHUA_TIME_PATH = "/cgi-bin/global.cgi?action=getCurrentTime";
|
||||||
|
|
||||||
|
/** "2026-09-17T10:35:49+02:00" (host localIso, WITH offset) → "2026-09-17 10:35:49"
|
||||||
|
* (the naive wall time the Dahua CGI speaks). */
|
||||||
|
function naiveWallTime(localIso: string): string {
|
||||||
|
const m = localIso.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/);
|
||||||
|
if (!m) throw new Error(`syncClock: unparseable host time ${localIso}`);
|
||||||
|
return `${m[1]} ${m[2]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a naive "YYYY-MM-DD HH:MM:SS" as an instant in the HOST's zone — both sides
|
||||||
|
* of the drift comparison go through this, so the zone cancels out. */
|
||||||
|
function naiveMs(naive: string): number {
|
||||||
|
return Date.parse(naive.replace(" ", "T"));
|
||||||
|
}
|
||||||
|
|
||||||
|
class DahuaCamera extends HttpCamera {
|
||||||
|
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
|
||||||
|
const read = await this.deviceRequest("GET", DAHUA_TIME_PATH);
|
||||||
|
if (read.status !== 200) {
|
||||||
|
throw new Error(`clock read failed: HTTP ${read.status}`);
|
||||||
|
}
|
||||||
|
// Reply body: "result=2026-09-17 09:35:51"
|
||||||
|
const cameraNaive =
|
||||||
|
read.body.toString("utf8").match(/result=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1] ?? null;
|
||||||
|
const hostNaive = naiveWallTime(localIso);
|
||||||
|
|
||||||
|
const cameraMs = cameraNaive ? naiveMs(cameraNaive) : NaN;
|
||||||
|
const driftSeconds = Number.isFinite(cameraMs)
|
||||||
|
? Math.round(Math.abs(naiveMs(hostNaive) - cameraMs) / 1000)
|
||||||
|
: null;
|
||||||
|
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
|
||||||
|
return { driftSeconds, synced: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const set = await this.deviceRequest(
|
||||||
|
"GET",
|
||||||
|
`/cgi-bin/global.cgi?action=setCurrentTime&time=${encodeURIComponent(hostNaive)}`,
|
||||||
|
);
|
||||||
|
// Dahua answers 200 with a body of "OK"; a refused write is a non-200 or "Error".
|
||||||
|
if (set.status !== 200 || !/^OK/.test(set.body.toString("utf8").trim())) {
|
||||||
|
throw new Error(
|
||||||
|
`clock set failed: HTTP ${set.status} ${set.body.toString("utf8").trim().slice(0, 40)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
|
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
|
||||||
return { driftSeconds, synced: true };
|
return { driftSeconds, synced: true };
|
||||||
}
|
}
|
||||||
@@ -329,15 +457,17 @@ export const dahuaDriver: CameraDriver = {
|
|||||||
id: "dahua",
|
id: "dahua",
|
||||||
category: "camera",
|
category: "camera",
|
||||||
label: "Dahua camera",
|
label: "Dahua camera",
|
||||||
description: "Dahua snapshot via CGI (HTTP Digest).",
|
description: "Dahua snapshot via CGI (HTTP Digest) + clock sync.",
|
||||||
transports: ["tcp-ip"],
|
transports: ["tcp-ip"],
|
||||||
configFields: cameraConfigFields,
|
configFields: cameraConfigFields,
|
||||||
// Dahua channels are 0-based on the CGI; the admin enters 1-based. No stream in the
|
// snapshot.cgi channels are 1-BASED, exactly as the admin enters them (only Dahua's
|
||||||
// path (the second arg is ignored — Dahua has no main/sub snapshot distinction here).
|
// configManager TABLES are 0-indexed — the earlier `ch - 1` here drew a permanent
|
||||||
|
// HTTP 400 on real hardware, 2026-09-17). No stream in the path: `subtype` is
|
||||||
|
// ignored by snapshot.cgi, the still always comes off the main stream.
|
||||||
create: (c) =>
|
create: (c) =>
|
||||||
new HttpCamera(
|
new DahuaCamera(
|
||||||
"dahua",
|
"dahua",
|
||||||
c,
|
c,
|
||||||
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(0, ch - 1)}`,
|
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(1, ch)}`,
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ export const passwordField: ConfigField = {
|
|||||||
* Sink for stub/diagnostic device messages. Defaults to a no-op so the package
|
* Sink for stub/diagnostic device messages. Defaults to a no-op so the package
|
||||||
* has no host/runtime dependency; the server sets this to its Fastify logger.
|
* has no host/runtime dependency; the server sets this to its Fastify logger.
|
||||||
*/
|
*/
|
||||||
export type DeviceLogSink = (line: string) => void;
|
export type DeviceLogLevel = "debug" | "info" | "warn";
|
||||||
|
export type DeviceLogSink = (line: string, level: DeviceLogLevel) => void;
|
||||||
|
|
||||||
let sink: DeviceLogSink = () => {};
|
let sink: DeviceLogSink = () => {};
|
||||||
|
|
||||||
@@ -40,7 +41,10 @@ export function setDeviceLogSink(fn: DeviceLogSink): void {
|
|||||||
sink = fn;
|
sink = fn;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stubs log instead of performing real I/O. Replaced with real protocols later. */
|
/** Device-side diagnostics (the sink is the server's logger). `info` for things an
|
||||||
export function stubLog(driverId: string, msg: string): void {
|
* operator reading `docker logs` should see (a config write, a retry, a clock set);
|
||||||
sink(`[device:${driverId}] ${msg}`);
|
* `debug` for per-event chatter (every snapshot's byte count) that only matters under
|
||||||
|
* LOG_LEVEL=debug. */
|
||||||
|
export function stubLog(driverId: string, msg: string, level: DeviceLogLevel = "info"): void {
|
||||||
|
sink(`[device:${driverId}] ${msg}`, level);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,346 @@
|
|||||||
|
import { createSocket, type Socket } from "node:dgram";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
QR_CMD,
|
||||||
|
QR_OUTPUT_HTTP,
|
||||||
|
buildDeviceInfo,
|
||||||
|
checksum,
|
||||||
|
discoverReaders,
|
||||||
|
exchange,
|
||||||
|
frameHeader,
|
||||||
|
parseDeviceInfo,
|
||||||
|
parseFirmware,
|
||||||
|
parseFrame,
|
||||||
|
parseParams,
|
||||||
|
readFirmware,
|
||||||
|
readParams,
|
||||||
|
setNetwork,
|
||||||
|
writeSetting,
|
||||||
|
ipToBytes,
|
||||||
|
} from "./dingtian-qr-config.js";
|
||||||
|
|
||||||
|
// The DT-008 configuration protocol, against a FAKE reader on loopback that behaves like
|
||||||
|
// the real one (wiki/raw/dingtian_qr_linux/PROTOCOL.md): header + payload must arrive as
|
||||||
|
// two datagrams, every write is acked with cmd+1 and a status byte, search answers with
|
||||||
|
// a 96-byte DeviceInfo, set-network is applied WITHOUT a reply. Byte layouts below are
|
||||||
|
// the worked examples and the reference capture from the bench reader HC002721.
|
||||||
|
|
||||||
|
// --- reference bytes -------------------------------------------------------
|
||||||
|
|
||||||
|
/** Build a 720-byte Params struct like the bench capture (HTTP, 10.0.10.204:8080, 8H…). */
|
||||||
|
function referenceParams(over: Partial<{ outputType: number; server: string; serverPort: number }> = {}): Buffer {
|
||||||
|
const b = Buffer.alloc(720);
|
||||||
|
b.writeUInt32LE(0, 0x000); // static IP
|
||||||
|
ipToBytes("10.0.10.12").copy(b, 0x004);
|
||||||
|
ipToBytes("255.255.255.0").copy(b, 0x008);
|
||||||
|
ipToBytes("10.0.10.1").copy(b, 0x00c);
|
||||||
|
ipToBytes("8.8.8.8").copy(b, 0x010);
|
||||||
|
ipToBytes("8.8.4.4").copy(b, 0x014);
|
||||||
|
b.write(over.server ?? "10.0.10.204", 0x018, "utf8");
|
||||||
|
b.writeUInt32LE(over.serverPort ?? 8080, 0x048);
|
||||||
|
b.writeUInt32LE(0, 0x04c); // PHP
|
||||||
|
b.writeUInt8(over.outputType ?? 3, 0x198); // HTTP
|
||||||
|
b.writeUInt8(2, 0x19c); // 8H
|
||||||
|
b.writeUInt8(1, 0x1a0); // add Enter
|
||||||
|
b.writeUInt8(0, 0x1a1);
|
||||||
|
b.writeUInt32LE(1, 0x1a4); // ASCII
|
||||||
|
b.writeUInt32LE(1, 0x1c8);
|
||||||
|
b.writeUInt32LE(1, 0x1ec); // restart 12 h
|
||||||
|
b.writeUInt32LE(0, 0x1f0); // normal
|
||||||
|
b.writeUInt32LE(0, 0x1f8); // buzzer off
|
||||||
|
b.writeUInt32LE(20, 0x1fc); // 2000 µs
|
||||||
|
b.writeUInt32LE(4, 0x200); // 400 µs
|
||||||
|
b.writeUInt32LE(9600, 0x204);
|
||||||
|
b.writeUInt32LE(8, 0x208);
|
||||||
|
b.writeUInt32LE(1, 0x20c);
|
||||||
|
b.writeUInt32LE(2, 0x210); // parity none
|
||||||
|
b.writeUInt32LE(4, 0x214); // QR ASCII
|
||||||
|
b.writeUInt32LE(1, 0x218); // fill light open
|
||||||
|
b.writeUInt32LE(1, 0x288);
|
||||||
|
b.writeUInt32LE(1, 0x28c);
|
||||||
|
b.write("K:", 0x290, "utf8");
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
function referenceFirmware(serial = "HC002721"): Buffer {
|
||||||
|
const b = Buffer.alloc(64);
|
||||||
|
b.write("doorqrcode", 0);
|
||||||
|
b.write("ver_client1_1.1", 16);
|
||||||
|
b.write("v3s", 32);
|
||||||
|
b.write("h42", 40);
|
||||||
|
b.write(serial, 48);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- fake reader -----------------------------------------------------------
|
||||||
|
|
||||||
|
interface FakeReader {
|
||||||
|
readonly unicast: number;
|
||||||
|
readonly broadcast: number;
|
||||||
|
readonly writes: { cmd: number; value: number }[];
|
||||||
|
params: Buffer;
|
||||||
|
singleDatagramFrames: number;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A loopback reader. One socket plays both ports (unicast + "broadcast"). */
|
||||||
|
async function fakeReader(params = referenceParams(), serial = "HC002721"): Promise<FakeReader> {
|
||||||
|
const bind = (): Promise<Socket> =>
|
||||||
|
new Promise((res) => {
|
||||||
|
const s = createSocket("udp4");
|
||||||
|
s.bind(0, "127.0.0.1", () => res(s));
|
||||||
|
});
|
||||||
|
const uni = await bind();
|
||||||
|
const bc = await bind();
|
||||||
|
const state: FakeReader = {
|
||||||
|
unicast: uni.address().port,
|
||||||
|
broadcast: bc.address().port,
|
||||||
|
writes: [],
|
||||||
|
params,
|
||||||
|
singleDatagramFrames: 0,
|
||||||
|
close: () => {
|
||||||
|
uni.close();
|
||||||
|
bc.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const reply = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
|
||||||
|
// Real replies: header + payload in ONE datagram, id arbitrary.
|
||||||
|
sock.send(Buffer.concat([frameHeader(cmd, payload, 0x1234), payload]), rinfo.port, rinfo.address);
|
||||||
|
};
|
||||||
|
const deviceInfo = () => {
|
||||||
|
const p = parseParams(state.params);
|
||||||
|
return buildDeviceInfo({ ...p, serial });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handle = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
|
||||||
|
switch (cmd) {
|
||||||
|
case QR_CMD.firmware:
|
||||||
|
return reply(sock, rinfo, 1, referenceFirmware(serial));
|
||||||
|
case QR_CMD.getParams:
|
||||||
|
return reply(sock, rinfo, 31, state.params);
|
||||||
|
case QR_CMD.search:
|
||||||
|
return reply(sock, rinfo, 3, deviceInfo());
|
||||||
|
case QR_CMD.setNetwork: {
|
||||||
|
// Applied only when the serial matches; the real reader sends NO ack.
|
||||||
|
const info = parseDeviceInfo(payload);
|
||||||
|
if (info.serial !== serial) return;
|
||||||
|
const next = Buffer.from(state.params);
|
||||||
|
next.fill(0, 0x018, 0x048);
|
||||||
|
next.write(info.server, 0x018, "utf8");
|
||||||
|
next.writeUInt32LE(info.serverPort, 0x048);
|
||||||
|
next.writeUInt32LE(info.httpLanguage, 0x04c);
|
||||||
|
state.params = next;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case QR_CMD.outputType: {
|
||||||
|
const v = payload.readUInt32LE(0);
|
||||||
|
state.writes.push({ cmd, value: v });
|
||||||
|
if (v < 1 || v > 10) return reply(sock, rinfo, cmd + 1, Buffer.from([1])); // rejected
|
||||||
|
state.params = Buffer.from(state.params);
|
||||||
|
state.params.writeUInt8(v, 0x198);
|
||||||
|
return reply(sock, rinfo, cmd + 1, Buffer.from([0]));
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Two-datagram write discipline, like the hardware: a header announcing len > 0 waits
|
||||||
|
// for the payload datagram; a header WITH payload glued on is a single-datagram frame
|
||||||
|
// → counted and ignored.
|
||||||
|
for (const sock of [uni, bc]) {
|
||||||
|
let pending: { cmd: number; len: number } | null = null;
|
||||||
|
sock.on("message", (msg, rinfo) => {
|
||||||
|
if (pending) {
|
||||||
|
const p = pending;
|
||||||
|
pending = null;
|
||||||
|
if (msg.length === p.len) handle(sock, rinfo, p.cmd, msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.length < 17 || msg.subarray(0, 4).toString("ascii") !== "XXXX") return;
|
||||||
|
const cmd = msg.readUInt32LE(8);
|
||||||
|
const len = msg.readUInt32LE(12);
|
||||||
|
if (msg.length > 17) {
|
||||||
|
state.singleDatagramFrames++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (len === 0) handle(sock, rinfo, cmd, Buffer.alloc(0));
|
||||||
|
else pending = { cmd, len };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
let reader: FakeReader | null = null;
|
||||||
|
const opts = () => ({
|
||||||
|
timeoutMs: 300,
|
||||||
|
retries: 0,
|
||||||
|
ports: { unicast: reader!.unicast, broadcast: reader!.broadcast },
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
reader?.close();
|
||||||
|
reader = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- framing (worked examples from PROTOCOL.md §2) -------------------------
|
||||||
|
|
||||||
|
describe("DT-008 config frame", () => {
|
||||||
|
it("search request: magic, id 0, cmd 2, len 0, checksum 0xFF", () => {
|
||||||
|
expect(frameHeader(QR_CMD.search).toString("hex")).toBe("58585858" + "00000000" + "02000000" + "00000000" + "ff");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("set buzzer on (cmd 18, u32 1): checksum 0xFF − 1 = 0xFE", () => {
|
||||||
|
const payload = Buffer.from([1, 0, 0, 0]);
|
||||||
|
expect(checksum(payload)).toBe(0xfe);
|
||||||
|
expect(frameHeader(18, payload).toString("hex")).toBe("58585858" + "00000000" + "12000000" + "04000000" + "fe");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses a reader ack (cmd 19, one status byte) and rejects a bad checksum", () => {
|
||||||
|
const ack = Buffer.from("58585858" + "00000000" + "13000000" + "01000000" + "ff" + "00", "hex");
|
||||||
|
expect(parseFrame(ack)).toEqual({ id: 0, cmd: 19, payload: Buffer.from([0]) });
|
||||||
|
const bad = Buffer.from(ack);
|
||||||
|
bad[16] = 0x00;
|
||||||
|
expect(parseFrame(bad)).toBeNull();
|
||||||
|
expect(parseFrame(Buffer.from("YYYY", "ascii"))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("IPv4 is stored little-endian (bytes reversed): 10.0.10.12 → 0c 0a 00 0a", () => {
|
||||||
|
expect(ipToBytes("10.0.10.12").toString("hex")).toBe("0c0a000a");
|
||||||
|
expect(() => ipToBytes("10.0.10")).toThrow(/IPv4/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("DT-008 blocks", () => {
|
||||||
|
it("decodes the reference 720-byte params", () => {
|
||||||
|
const p = parseParams(referenceParams());
|
||||||
|
expect(p).toMatchObject({
|
||||||
|
dhcp: 0,
|
||||||
|
ip: "10.0.10.12",
|
||||||
|
netmask: "255.255.255.0",
|
||||||
|
gateway: "10.0.10.1",
|
||||||
|
dns1: "8.8.8.8",
|
||||||
|
dns2: "8.8.4.4",
|
||||||
|
server: "10.0.10.204",
|
||||||
|
serverPort: 8080,
|
||||||
|
httpLanguage: 0,
|
||||||
|
outputType: QR_OUTPUT_HTTP,
|
||||||
|
cardInputFormat: 2,
|
||||||
|
lastAddEnter: 1,
|
||||||
|
restartInterval: 1,
|
||||||
|
buzzer: 0,
|
||||||
|
highPulseUs: 2000,
|
||||||
|
lowPulseUs: 400,
|
||||||
|
baudrate: 9600,
|
||||||
|
parity: 2,
|
||||||
|
qrOutputFormat: 4,
|
||||||
|
fillLight: 1,
|
||||||
|
cardPrefix: "K:",
|
||||||
|
qrPrefix: "",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("DeviceInfo round-trips (serial, addresses, server, port, language)", () => {
|
||||||
|
const info = {
|
||||||
|
serial: "HC009E84",
|
||||||
|
ip: "10.0.10.7",
|
||||||
|
netmask: "255.255.255.0",
|
||||||
|
gateway: "0.0.0.0",
|
||||||
|
dns1: "0.0.0.0",
|
||||||
|
dns2: "0.0.0.0",
|
||||||
|
server: "10.0.10.101",
|
||||||
|
serverPort: 3000,
|
||||||
|
httpLanguage: 1,
|
||||||
|
};
|
||||||
|
const b = buildDeviceInfo(info);
|
||||||
|
expect(b.length).toBe(96);
|
||||||
|
expect(b.subarray(0, 8).toString("ascii")).toBe("HC009E84");
|
||||||
|
expect(b.readUInt32LE(88)).toBe(3000);
|
||||||
|
expect(parseDeviceInfo(b)).toEqual(info);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("decodes FirmwareInfo", () => {
|
||||||
|
expect(parseFirmware(referenceFirmware())).toEqual({
|
||||||
|
model: "doorqrcode",
|
||||||
|
firmware: "ver_client1_1.1",
|
||||||
|
chip: "v3s",
|
||||||
|
hardware: "h42",
|
||||||
|
serial: "HC002721",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- transport against the fake reader ------------------------------------
|
||||||
|
|
||||||
|
describe("DT-008 config transport", () => {
|
||||||
|
it("readFirmware / readParams: unicast cmd 0 and 30, reply cmd+1", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
expect((await readFirmware("127.0.0.1", opts()))?.serial).toBe("HC002721");
|
||||||
|
const p = await readParams("127.0.0.1", opts());
|
||||||
|
expect(p?.server).toBe("10.0.10.204");
|
||||||
|
expect(p?.outputType).toBe(3);
|
||||||
|
expect(reader.singleDatagramFrames).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("writeSetting sends header THEN payload (two datagrams) and returns the status byte", async () => {
|
||||||
|
reader = await fakeReader(referenceParams({ outputType: 6 })); // WG26, like park-2
|
||||||
|
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, QR_OUTPUT_HTTP, opts())).toBe(0);
|
||||||
|
expect(reader.writes).toEqual([{ cmd: 6, value: 3 }]);
|
||||||
|
expect(parseParams(reader.params).outputType).toBe(3);
|
||||||
|
expect(reader.singleDatagramFrames).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("an out-of-range value is acknowledged with status 1 and changes nothing", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, 42, opts())).toBe(1);
|
||||||
|
expect(parseParams(reader.params).outputType).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no reader → null after the retries (never throws)", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
const dead = { ...opts(), ports: { unicast: 1, broadcast: 1 } }; // nobody listens on :1
|
||||||
|
expect(await exchange("127.0.0.1", QR_CMD.getParams, undefined, { ...dead, retries: 1 })).toBeNull();
|
||||||
|
expect(await readParams("127.0.0.1", dead)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("discoverReaders: cmd 2 to each broadcast, collects cmd 3 DeviceInfo, dedupes by serial", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
const found = await discoverReaders({ ...opts(), broadcasts: ["127.0.0.1", "127.0.0.1"] });
|
||||||
|
expect(found).toHaveLength(1);
|
||||||
|
expect(found[0]).toMatchObject({
|
||||||
|
serial: "HC002721",
|
||||||
|
ip: "10.0.10.12",
|
||||||
|
server: "10.0.10.204",
|
||||||
|
serverPort: 8080,
|
||||||
|
replyFrom: "127.0.0.1",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("discoverReaders with no broadcast targets returns [] without touching the network", async () => {
|
||||||
|
expect(await discoverReaders({ broadcasts: [], timeoutMs: 50 })).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("setNetwork: broadcast cmd 32; the matching reader applies it silently (re-read to confirm)", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
const before = parseParams(reader.params);
|
||||||
|
await setNetwork(
|
||||||
|
{ ...before, serial: "HC002721", server: "10.0.10.101", serverPort: 3000 },
|
||||||
|
"127.0.0.1",
|
||||||
|
opts(),
|
||||||
|
);
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
const after = await readParams("127.0.0.1", opts());
|
||||||
|
expect(after?.server).toBe("10.0.10.101");
|
||||||
|
expect(after?.serverPort).toBe(3000);
|
||||||
|
expect(after?.ip).toBe(before.ip); // network block preserved
|
||||||
|
});
|
||||||
|
|
||||||
|
it("setNetwork for another serial is ignored by this reader", async () => {
|
||||||
|
reader = await fakeReader();
|
||||||
|
const before = parseParams(reader.params);
|
||||||
|
await setNetwork({ ...before, serial: "HC00FFFF", server: "1.2.3.4", serverPort: 1 }, "127.0.0.1", opts());
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
expect((await readParams("127.0.0.1", opts()))?.server).toBe("10.0.10.204");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,483 @@
|
|||||||
|
import { createSocket, type Socket } from "node:dgram";
|
||||||
|
import { networkInterfaces } from "node:os";
|
||||||
|
|
||||||
|
// Dingtian DT-008 QR/RFID reader — CONFIGURATION protocol (UDP). This is what the
|
||||||
|
// vendor's Windows-only `QRCode_v1_6_5.exe` speaks for "Search device" / "Get parameter"
|
||||||
|
// / the Set buttons; reversed in wiki/raw/dingtian_qr_linux/PROTOCOL.md and verified on
|
||||||
|
// real readers (bench HC002721; park-2's two units read with it on 2026-10-08). Lets the
|
||||||
|
// setup wizard FIND readers on the device VLAN and put a freshly assigned reader into HTTP
|
||||||
|
// mode pointing at this booth — instead of a Windows laptop on site. The scan push itself
|
||||||
|
// (HTTP GET /qa/mcardsea.<ext>) is a different protocol, handled by routes/qr-reader.ts.
|
||||||
|
//
|
||||||
|
// Frame (both directions, little-endian):
|
||||||
|
// 'XXXX' | id u32 | cmd u32 | len u32 | checksum u8 (0xFF − Σpayload) | payload
|
||||||
|
// Even cmd = request/write, reply = cmd + 1. QUIRK: the reader only accepts a write when
|
||||||
|
// the 17-byte header and the payload arrive as TWO datagrams (header first); a single
|
||||||
|
// datagram is silently ignored. Replies come as one datagram, from an arbitrary source
|
||||||
|
// port. Reader listens on 24680 (unicast: 0 firmware, 30 params, every field write) and
|
||||||
|
// 24582 (broadcast: 2 search, 32 set-network). set-network is applied but NOT acknowledged
|
||||||
|
// by the real reader — verify it by re-reading the params (cmd 30).
|
||||||
|
//
|
||||||
|
// SECURITY: unauthenticated UDP, like the relay board — the reader sits on the isolated
|
||||||
|
// device VLAN reachable only by the host (wiki/concepts/network-isolation.md).
|
||||||
|
|
||||||
|
export const QR_PORT_UNICAST = 24680;
|
||||||
|
export const QR_PORT_BROADCAST = 24582;
|
||||||
|
const MAGIC = Buffer.from("XXXX", "ascii");
|
||||||
|
const HEADER_LEN = 17;
|
||||||
|
const PARAMS_LEN = 720;
|
||||||
|
const DEVICE_INFO_LEN = 96;
|
||||||
|
const FIRMWARE_LEN = 64;
|
||||||
|
|
||||||
|
/** Command numbers (requests; the reply is cmd + 1). */
|
||||||
|
export const QR_CMD = {
|
||||||
|
firmware: 0,
|
||||||
|
search: 2,
|
||||||
|
outputType: 6,
|
||||||
|
cardInputFormat: 8,
|
||||||
|
getParams: 30,
|
||||||
|
setNetwork: 32,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** `output type` values on the wire (cmd 6 / Params 0x198). Only HTTP contacts the booth;
|
||||||
|
* in every other mode the reader beeps locally and the scan goes elsewhere. */
|
||||||
|
export const QR_OUTPUT_HTTP = 3;
|
||||||
|
export const QR_OUTPUT_TYPES: Record<number, string> = {
|
||||||
|
1: "USB virtual keyboard",
|
||||||
|
2: "USB virtual serial port",
|
||||||
|
3: "HTTP",
|
||||||
|
4: "MQTT",
|
||||||
|
5: "RS232",
|
||||||
|
6: "WG26",
|
||||||
|
7: "WG34",
|
||||||
|
8: "RS485",
|
||||||
|
9: "AC Output",
|
||||||
|
10: "TCP",
|
||||||
|
};
|
||||||
|
export const QR_CARD_INPUT_FORMATS: Record<number, string> = {
|
||||||
|
1: "6H",
|
||||||
|
2: "8H",
|
||||||
|
3: "8H10D",
|
||||||
|
4: "6H10D",
|
||||||
|
5: "2H3D+4H5D",
|
||||||
|
};
|
||||||
|
export const QR_HTTP_LANGUAGES: Record<number, string> = {
|
||||||
|
0: "PHP",
|
||||||
|
1: "JSP",
|
||||||
|
2: "C#",
|
||||||
|
3: "ASP",
|
||||||
|
4: "CGI",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function outputTypeName(v: number): string {
|
||||||
|
return QR_OUTPUT_TYPES[v] ?? `unknown (${v})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QrOptions {
|
||||||
|
/** Per-attempt reply wait. */
|
||||||
|
readonly timeoutMs?: number;
|
||||||
|
/** Extra attempts after the first (the exe never retries; UDP can drop). */
|
||||||
|
readonly retries?: number;
|
||||||
|
/** Port overrides (tests run a fake reader on loopback ephemeral ports). */
|
||||||
|
readonly ports?: { readonly unicast?: number; readonly broadcast?: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 1500;
|
||||||
|
const DEFAULT_RETRIES = 1;
|
||||||
|
|
||||||
|
// --- framing ---------------------------------------------------------------
|
||||||
|
|
||||||
|
export function checksum(payload: Buffer): number {
|
||||||
|
let sum = 0;
|
||||||
|
for (const b of payload) sum += b;
|
||||||
|
return (0xff - sum) & 0xff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The 17-byte header for `cmd` + `payload` (the payload is sent as its own datagram). */
|
||||||
|
export function frameHeader(cmd: number, payload: Buffer = Buffer.alloc(0), id = 0): Buffer {
|
||||||
|
const h = Buffer.alloc(HEADER_LEN);
|
||||||
|
MAGIC.copy(h, 0);
|
||||||
|
h.writeUInt32LE(id >>> 0, 4);
|
||||||
|
h.writeUInt32LE(cmd >>> 0, 8);
|
||||||
|
h.writeUInt32LE(payload.length, 12);
|
||||||
|
h.writeUInt8(checksum(payload), 16);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QrFrame {
|
||||||
|
readonly id: number;
|
||||||
|
readonly cmd: number;
|
||||||
|
readonly payload: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a reply datagram (header + payload in one). null = not a valid frame. */
|
||||||
|
export function parseFrame(datagram: Buffer): QrFrame | null {
|
||||||
|
if (datagram.length < HEADER_LEN || !datagram.subarray(0, 4).equals(MAGIC)) return null;
|
||||||
|
const id = datagram.readUInt32LE(4);
|
||||||
|
const cmd = datagram.readUInt32LE(8);
|
||||||
|
const len = datagram.readUInt32LE(12);
|
||||||
|
const payload = datagram.subarray(HEADER_LEN, HEADER_LEN + len);
|
||||||
|
if (payload.length !== len || checksum(payload) !== datagram.readUInt8(16)) return null;
|
||||||
|
return { id, cmd, payload };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- field codecs ----------------------------------------------------------
|
||||||
|
|
||||||
|
/** IPv4 as the reader stores it: little-endian u32 = the dotted bytes REVERSED. */
|
||||||
|
export function ipToBytes(ip: string): Buffer {
|
||||||
|
const parts = ip.split(".").map(Number);
|
||||||
|
if (parts.length !== 4 || parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) {
|
||||||
|
throw new Error(`not an IPv4 address: ${ip}`);
|
||||||
|
}
|
||||||
|
return Buffer.from(parts.reverse());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bytesToIp(b: Buffer, off: number): string {
|
||||||
|
return `${b[off + 3]}.${b[off + 2]}.${b[off + 1]}.${b[off]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cstr(b: Buffer, off: number, len: number): string {
|
||||||
|
const s = b.subarray(off, off + len);
|
||||||
|
const nul = s.indexOf(0);
|
||||||
|
return s.subarray(0, nul < 0 ? s.length : nul).toString("utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
function putStr(b: Buffer, off: number, len: number, s: string): void {
|
||||||
|
b.fill(0, off, off + len);
|
||||||
|
// Leave the last byte NUL (the exe caps the 48-byte server field at 47 chars).
|
||||||
|
b.write(s, off, len - 1, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- blocks ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 96-byte DeviceInfo: the search reply (cmd 3) and the set-network payload (cmd 32). */
|
||||||
|
export interface QrDeviceInfo {
|
||||||
|
readonly serial: string;
|
||||||
|
readonly ip: string;
|
||||||
|
readonly netmask: string;
|
||||||
|
readonly gateway: string;
|
||||||
|
readonly dns1: string;
|
||||||
|
readonly dns2: string;
|
||||||
|
/** Hostname or IP the reader pushes scans to (factory: "ipc.fondvision.com"). */
|
||||||
|
readonly server: string;
|
||||||
|
readonly serverPort: number;
|
||||||
|
/** 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI — only picks the push URL's extension. */
|
||||||
|
readonly httpLanguage: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseDeviceInfo(b: Buffer): QrDeviceInfo {
|
||||||
|
if (b.length < DEVICE_INFO_LEN) throw new Error(`DeviceInfo too short: ${b.length}`);
|
||||||
|
return {
|
||||||
|
serial: cstr(b, 0, 20),
|
||||||
|
ip: bytesToIp(b, 20),
|
||||||
|
netmask: bytesToIp(b, 24),
|
||||||
|
gateway: bytesToIp(b, 28),
|
||||||
|
dns1: bytesToIp(b, 32),
|
||||||
|
dns2: bytesToIp(b, 36),
|
||||||
|
server: cstr(b, 40, 48),
|
||||||
|
serverPort: b.readUInt32LE(88),
|
||||||
|
httpLanguage: b.readUInt32LE(92),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildDeviceInfo(info: QrDeviceInfo): Buffer {
|
||||||
|
const b = Buffer.alloc(DEVICE_INFO_LEN);
|
||||||
|
putStr(b, 0, 20, info.serial);
|
||||||
|
ipToBytes(info.ip).copy(b, 20);
|
||||||
|
ipToBytes(info.netmask).copy(b, 24);
|
||||||
|
ipToBytes(info.gateway).copy(b, 28);
|
||||||
|
ipToBytes(info.dns1).copy(b, 32);
|
||||||
|
ipToBytes(info.dns2).copy(b, 36);
|
||||||
|
putStr(b, 40, 48, info.server);
|
||||||
|
b.writeUInt32LE(info.serverPort >>> 0, 88);
|
||||||
|
b.writeUInt32LE(info.httpLanguage >>> 0, 92);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 64-byte FirmwareInfo (reply 1). */
|
||||||
|
export interface QrFirmware {
|
||||||
|
readonly model: string; // "doorqrcode"
|
||||||
|
readonly firmware: string; // "ver_client1_1.1"
|
||||||
|
readonly chip: string; // "v3s"
|
||||||
|
readonly hardware: string; // "h42"
|
||||||
|
readonly serial: string; // "HC002721"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseFirmware(b: Buffer): QrFirmware {
|
||||||
|
if (b.length < FIRMWARE_LEN) throw new Error(`FirmwareInfo too short: ${b.length}`);
|
||||||
|
return {
|
||||||
|
model: cstr(b, 0, 16),
|
||||||
|
firmware: cstr(b, 16, 16),
|
||||||
|
chip: cstr(b, 32, 8),
|
||||||
|
hardware: cstr(b, 40, 8),
|
||||||
|
serial: cstr(b, 48, 16),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The 720-byte parameter struct (reply 31). Only the fields the exe shows are decoded. */
|
||||||
|
export interface QrParams {
|
||||||
|
readonly dhcp: number;
|
||||||
|
readonly ip: string;
|
||||||
|
readonly netmask: string;
|
||||||
|
readonly gateway: string;
|
||||||
|
readonly dns1: string;
|
||||||
|
readonly dns2: string;
|
||||||
|
readonly server: string;
|
||||||
|
readonly serverPort: number;
|
||||||
|
readonly httpLanguage: number;
|
||||||
|
/** See QR_OUTPUT_TYPES; 3 = HTTP. */
|
||||||
|
readonly outputType: number;
|
||||||
|
/** See QR_CARD_INPUT_FORMATS; 1 = 6H. */
|
||||||
|
readonly cardInputFormat: number;
|
||||||
|
readonly lastAddEnter: number;
|
||||||
|
readonly lastAddNewline: number;
|
||||||
|
readonly qrPrefix: string;
|
||||||
|
readonly qrSuffix: string;
|
||||||
|
readonly restartInterval: number;
|
||||||
|
readonly workMode: number;
|
||||||
|
readonly buzzer: number;
|
||||||
|
readonly highPulseUs: number;
|
||||||
|
readonly lowPulseUs: number;
|
||||||
|
readonly baudrate: number;
|
||||||
|
readonly dataBits: number;
|
||||||
|
readonly stopBits: number;
|
||||||
|
readonly parity: number;
|
||||||
|
readonly qrOutputFormat: number;
|
||||||
|
readonly fillLight: number;
|
||||||
|
readonly cardOutputFormat: number;
|
||||||
|
readonly cardPrefix: string;
|
||||||
|
readonly cardSuffix: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseParams(b: Buffer): QrParams {
|
||||||
|
if (b.length < PARAMS_LEN) throw new Error(`Params too short: ${b.length}`);
|
||||||
|
return {
|
||||||
|
dhcp: b.readUInt32LE(0x000),
|
||||||
|
ip: bytesToIp(b, 0x004),
|
||||||
|
netmask: bytesToIp(b, 0x008),
|
||||||
|
gateway: bytesToIp(b, 0x00c),
|
||||||
|
dns1: bytesToIp(b, 0x010),
|
||||||
|
dns2: bytesToIp(b, 0x014),
|
||||||
|
server: cstr(b, 0x018, 48),
|
||||||
|
serverPort: b.readUInt32LE(0x048),
|
||||||
|
httpLanguage: b.readUInt32LE(0x04c),
|
||||||
|
outputType: b.readUInt8(0x198),
|
||||||
|
cardInputFormat: b.readUInt8(0x19c),
|
||||||
|
lastAddEnter: b.readUInt8(0x1a0),
|
||||||
|
lastAddNewline: b.readUInt8(0x1a1),
|
||||||
|
qrPrefix: cstr(b, 0x1a8, 32),
|
||||||
|
qrSuffix: cstr(b, 0x1cc, 32),
|
||||||
|
restartInterval: b.readUInt32LE(0x1ec),
|
||||||
|
workMode: b.readUInt32LE(0x1f0),
|
||||||
|
buzzer: b.readUInt32LE(0x1f8),
|
||||||
|
highPulseUs: b.readUInt32LE(0x1fc) * 100,
|
||||||
|
lowPulseUs: b.readUInt32LE(0x200) * 100,
|
||||||
|
baudrate: b.readUInt32LE(0x204),
|
||||||
|
dataBits: b.readUInt32LE(0x208),
|
||||||
|
stopBits: b.readUInt32LE(0x20c),
|
||||||
|
parity: b.readUInt32LE(0x210),
|
||||||
|
qrOutputFormat: b.readUInt32LE(0x214),
|
||||||
|
fillLight: b.readUInt32LE(0x218),
|
||||||
|
cardOutputFormat: b.readUInt32LE(0x288),
|
||||||
|
cardPrefix: cstr(b, 0x290, 32),
|
||||||
|
cardSuffix: cstr(b, 0x2b0, 32),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- transport -------------------------------------------------------------
|
||||||
|
|
||||||
|
function openSocket(): Promise<Socket> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const s = createSocket({ type: "udp4", reuseAddr: true });
|
||||||
|
s.once("error", reject);
|
||||||
|
s.bind(0, "0.0.0.0", () => {
|
||||||
|
s.removeListener("error", reject);
|
||||||
|
resolve(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendTo(sock: Socket, host: string, port: number, buf: Buffer): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
sock.send(buf, port, host, (err) => (err ? reject(err) : resolve()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send `cmd` the way the exe does: the header datagram, then the payload datagram. */
|
||||||
|
async function sendCommand(sock: Socket, host: string, port: number, cmd: number, payload: Buffer): Promise<void> {
|
||||||
|
await sendTo(sock, host, port, frameHeader(cmd, payload));
|
||||||
|
if (payload.length) await sendTo(sock, host, port, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collect reply frames matching `want` for up to `ms`, calling `onFrame` for each;
|
||||||
|
* resolves early when `onFrame` returns true (= done). */
|
||||||
|
function collect(
|
||||||
|
sock: Socket,
|
||||||
|
ms: number,
|
||||||
|
onFrame: (f: QrFrame, from: string) => boolean,
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const done = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
sock.removeListener("message", onMsg);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
const onMsg = (msg: Buffer, rinfo: { address: string }) => {
|
||||||
|
const f = parseFrame(msg);
|
||||||
|
if (f && onFrame(f, rinfo.address)) done();
|
||||||
|
};
|
||||||
|
const timer = setTimeout(done, ms);
|
||||||
|
sock.on("message", onMsg);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unicast `cmd` to the reader and await the `cmd + 1` reply payload; null = no reply. */
|
||||||
|
export async function exchange(
|
||||||
|
host: string,
|
||||||
|
cmd: number,
|
||||||
|
payload: Buffer = Buffer.alloc(0),
|
||||||
|
opts: QrOptions = {},
|
||||||
|
): Promise<Buffer | null> {
|
||||||
|
const port = opts.ports?.unicast ?? QR_PORT_UNICAST;
|
||||||
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
|
const retries = opts.retries ?? DEFAULT_RETRIES;
|
||||||
|
const sock = await openSocket();
|
||||||
|
try {
|
||||||
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||||
|
await sendCommand(sock, host, port, cmd, payload);
|
||||||
|
let got: Buffer | null = null;
|
||||||
|
await collect(sock, timeoutMs, (f) => {
|
||||||
|
if (f.cmd !== cmd + 1) return false;
|
||||||
|
got = f.payload;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (got) return got;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
sock.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readFirmware(host: string, opts?: QrOptions): Promise<QrFirmware | null> {
|
||||||
|
const b = await exchange(host, QR_CMD.firmware, undefined, opts);
|
||||||
|
return b && b.length >= FIRMWARE_LEN ? parseFirmware(b) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readParams(host: string, opts?: QrOptions): Promise<QrParams | null> {
|
||||||
|
const b = await exchange(host, QR_CMD.getParams, undefined, opts);
|
||||||
|
return b && b.length >= PARAMS_LEN ? parseParams(b) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write one u32 setting (cmd 6 output type, 8 card input format, 18 work mode, 22
|
||||||
|
* buzzer, …). Resolves the reader's status byte: 0 = applied (immediately, no reboot),
|
||||||
|
* 1 = rejected (out of range); null = no acknowledgement. */
|
||||||
|
export async function writeSetting(
|
||||||
|
host: string,
|
||||||
|
cmd: number,
|
||||||
|
value: number,
|
||||||
|
opts?: QrOptions,
|
||||||
|
): Promise<number | null> {
|
||||||
|
const payload = Buffer.alloc(4);
|
||||||
|
payload.writeUInt32LE(value >>> 0, 0);
|
||||||
|
const b = await exchange(host, cmd, payload, opts);
|
||||||
|
return b && b.length >= 1 ? b.readUInt8(0) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the reader's network block (IP/netmask/gateway/DNS, push server + port, URL
|
||||||
|
* language) — cmd 32, an L2 BROADCAST that only the reader whose serial matches applies.
|
||||||
|
* The real reader applies it without replying, so this resolves after sending; the caller
|
||||||
|
* must re-read the params to confirm. `broadcast` is the subnet-directed address
|
||||||
|
* (e.g. 10.0.10.255 — see subnetBroadcastFor); the global 255.255.255.255 is refused by
|
||||||
|
* the kernel on some hosts (EACCES) and is not what the exe sends.
|
||||||
|
*/
|
||||||
|
export async function setNetwork(info: QrDeviceInfo, broadcast: string, opts: QrOptions = {}): Promise<void> {
|
||||||
|
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
|
||||||
|
const sock = await openSocket();
|
||||||
|
try {
|
||||||
|
sock.setBroadcast(true);
|
||||||
|
await sendCommand(sock, broadcast, port, QR_CMD.setNetwork, buildDeviceInfo(info));
|
||||||
|
} finally {
|
||||||
|
sock.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DiscoveredReader extends QrDeviceInfo {
|
||||||
|
/** Address the reply came from (normally = ip). */
|
||||||
|
readonly replyFrom: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search the LAN: cmd 2 to every subnet-directed broadcast (one per local IPv4 interface
|
||||||
|
* unless `broadcasts` is given), collect cmd 3 replies for `timeoutMs`, dedupe by serial.
|
||||||
|
* Readers must share an L2 segment with the host — fine on the booth (host network) and
|
||||||
|
* the device VLAN; impossible from a bridged dev container or across Netbird.
|
||||||
|
*/
|
||||||
|
export async function discoverReaders(
|
||||||
|
opts: QrOptions & { readonly broadcasts?: readonly string[] } = {},
|
||||||
|
): Promise<DiscoveredReader[]> {
|
||||||
|
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
|
||||||
|
const timeoutMs = opts.timeoutMs ?? 2000;
|
||||||
|
const targets = opts.broadcasts ?? subnetBroadcasts();
|
||||||
|
if (targets.length === 0) return [];
|
||||||
|
const sock = await openSocket();
|
||||||
|
const found = new Map<string, DiscoveredReader>();
|
||||||
|
try {
|
||||||
|
sock.setBroadcast(true);
|
||||||
|
for (const b of targets) {
|
||||||
|
// One unreachable interface must not abort the whole scan.
|
||||||
|
await sendCommand(sock, b, port, QR_CMD.search, Buffer.alloc(0)).catch(() => {});
|
||||||
|
}
|
||||||
|
await collect(sock, timeoutMs, (f, from) => {
|
||||||
|
if (f.cmd === QR_CMD.search + 1 && f.payload.length >= DEVICE_INFO_LEN) {
|
||||||
|
const info = parseDeviceInfo(f.payload);
|
||||||
|
found.set(info.serial, { ...info, replyFrom: from });
|
||||||
|
}
|
||||||
|
return false; // keep collecting until the deadline
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
sock.close();
|
||||||
|
}
|
||||||
|
return [...found.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- local network helpers -------------------------------------------------
|
||||||
|
|
||||||
|
function parseV4(s: string): number[] | null {
|
||||||
|
const p = s.split(".").map(Number);
|
||||||
|
return p.length === 4 && p.every((o) => Number.isInteger(o) && o >= 0 && o <= 255) ? p : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Subnet-directed broadcast addresses of every non-loopback local IPv4 interface. */
|
||||||
|
export function subnetBroadcasts(): string[] {
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const ifaces of Object.values(networkInterfaces())) {
|
||||||
|
for (const i of ifaces ?? []) {
|
||||||
|
if (i.family !== "IPv4" || i.internal) continue;
|
||||||
|
const a = parseV4(i.address);
|
||||||
|
const m = parseV4(i.netmask);
|
||||||
|
if (!a || !m) continue;
|
||||||
|
out.add(a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join("."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The subnet-directed broadcast of the local interface whose subnet contains `host`;
|
||||||
|
* null when no directly attached interface does (set-network can't reach it then). */
|
||||||
|
export function subnetBroadcastFor(host: string): string | null {
|
||||||
|
const h = parseV4(host);
|
||||||
|
if (!h) return null;
|
||||||
|
for (const ifaces of Object.values(networkInterfaces())) {
|
||||||
|
for (const i of ifaces ?? []) {
|
||||||
|
if (i.family !== "IPv4" || i.internal) continue;
|
||||||
|
const a = parseV4(i.address);
|
||||||
|
const m = parseV4(i.netmask);
|
||||||
|
if (!a || !m) continue;
|
||||||
|
const same = h.every((o, k) => (o & m[k]!) === (a[k]! & m[k]!));
|
||||||
|
if (same) return a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join(".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user