feat(cameras): booth camera tiles — latest snapshot at rest, live video while a vehicle is in view

Footer camera chips open/close a tile per camera (bottom right, ~15% wide, stacking
leftwards); the open set is a per-user preference (users.open_cameras). A tile shows the
camera's newest entry/exit snapshot and switches to live video while that camera pushes
vehicle events (per-camera activity, same 30 s TTL as lane status).

- devices: RTSP MJPEG client + RFC 2435 RTP/JPEG reassembly; Hikvision openLiveStream()
  on the sub-stream (x02, must be MJPEG — H.264 is refused with that reason)
- server: CameraLiveHub (one shared upstream per camera, latest-frame delivery, fps cap,
  linger, backoff), CameraActivity, /api/cameras/:id/latest-snapshot, WS
  /api/cameras/:id/live (shared handshake auth with /api/ws + device:read),
  PUT /api/auth/open-cameras, migration 0033 (open_cameras + snapshot device/time index)
- web: CameraDock, footer toggles, binary frames in the platform socket (Tauri too)
- .gitattributes: *.jpg / *.bin binary (byte-exact test fixtures)

Verified on park-lab cameras end to end and in headless Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:48:50 +01:00
parent b6f7ea65a4
commit 39fb5fb7c2
36 changed files with 2067 additions and 45 deletions
+52
View File
@@ -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 }]);
});
});
+50
View File
@@ -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();
}
}
+149
View File
@@ -0,0 +1,149 @@
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("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);
});
});
+199
View File
@@ -0,0 +1,199 @@
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, and a per-viewer frame
// cap keeps the desktop shell's IPC light. 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. The cameras send 12.5–20 fps; 10 is plenty to watch a car. */
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;
}
export function liveMaxFps(): number {
const raw = Number(process.env.CAMERA_LIVE_MAX_FPS ?? 10);
return Number.isFinite(raw) && raw > 0 ? raw : 10;
}
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;
this.#minFrameGapMs = 1000 / (opts.maxFps ?? liveMaxFps());
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();
}
}
+16
View File
@@ -89,6 +89,13 @@ export interface DeviceStatusEvent {
* 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
* 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 {
readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity)
readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity)
@@ -193,6 +200,15 @@ class DeviceEventBus extends EventEmitter {
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
* at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */
emitLanePresence(event: LanePresenceEvent): void {
+47
View File
@@ -37,6 +37,24 @@ interface FontScaleBody {
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
// 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
@@ -90,6 +108,7 @@ function sessionView(
language: string;
theme: string;
fontScale: number;
openCameras?: string | null;
fullName?: string | null;
email?: string | null;
},
@@ -106,6 +125,7 @@ function sessionView(
language: user.language,
theme: user.theme,
fontScale: user.fontScale,
openCameras: parseOpenCameras(user.openCameras),
fullName: user.fullName ?? null,
email: user.email ?? null,
// 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
// touches the caller). Cannot change username or role — those stay admin-only (users.ts).
app.put<{ Body: ProfileBody }>(
+137
View File
@@ -0,0 +1,137 @@
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("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);
});
});
+83
View File
@@ -0,0 +1,83 @@
import type { FastifyInstance } from "fastify";
import { desc, devices, eq, 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.
// - 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))
.limit(1)
.get();
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
return row;
},
);
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);
},
);
}
+11 -1
View File
@@ -6,6 +6,7 @@ import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { hikvisionAlarmRoutes } from "./hikvision-alarm.js";
import type { AnprBridge } from "../anpr-entry.js";
import type { CameraActivity } from "../camera-activity.js";
import { seedUser, login } from "../test-helpers.js";
// 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 rawClose: () => void;
let onVehicleDetected: ReturnType<typeof vi.fn>;
let cameraSaw: ReturnType<typeof vi.fn>;
beforeEach(async () => {
const t = createTestDb();
@@ -243,7 +245,9 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
onVehicleDetected = vi.fn(async () => {});
const bridge = { onVehicleDetected } as unknown as AnprBridge;
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();
rawDb.insert(devices).values({
id: CAM_ID,
@@ -275,10 +279,16 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
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 () => {
const human = VEHICLE_XML.replace("vehicle", "human");
await post(human);
expect(onVehicleDetected).not.toHaveBeenCalled();
expect(cameraSaw).not.toHaveBeenCalled();
});
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 type { LaneStatus } from "../lane-status.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 →
// Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm
@@ -101,6 +102,7 @@ export async function hikvisionAlarmRoutes(
db: Db,
laneStatus?: LaneStatus,
anprBridge?: AnprBridge,
cameraActivity?: CameraActivity,
): Promise<void> {
// 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
@@ -213,6 +215,10 @@ export async function hikvisionAlarmRoutes(
if (laneStatus && isVehicleActive) {
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),
// pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read
+40 -20
View File
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
import type { FastifyInstance } from "fastify";
import type { FastifyInstance, FastifyRequest } from "fastify";
import type { Db } from "@parking/db";
import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared";
import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js";
@@ -9,7 +9,9 @@ import {
type LaneStatusEvent,
type LanePresenceEvent,
type PlateRecognizedEvent,
type CameraActivityEvent,
} from "../device-events.js";
import type { CameraActivity } from "../camera-activity.js";
import { enrichEvent } from "../event-enrich.js";
import type { DeviceMonitor } from "../device-monitor.js";
import type { LaneStatus } from "../lane-status.js";
@@ -111,6 +113,32 @@ function isAllowedOrigin(origin: string | undefined, host: string | undefined):
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 =
| {
kind: "hello";
@@ -118,12 +146,15 @@ type OutMsg =
devices: unknown;
lanes: LaneStatusEvent | 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: "printer-status"; event: unknown }
| { kind: "device-status"; event: unknown }
| { kind: "lane-status"; lanes: LaneStatusEvent }
| { kind: "lane-presence"; radar: LanePresenceEvent }
| { kind: "camera-activity"; camera: CameraActivityEvent }
| { kind: "plate-recognized"; plate: PlateRecognizedEvent };
declare module "fastify" {
@@ -139,6 +170,7 @@ export async function wsRoutes(
deviceMonitor: DeviceMonitor,
laneStatus: LaneStatus,
lanePresence: LanePresence,
cameraActivity: CameraActivity,
): Promise<void> {
// 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
@@ -157,25 +189,7 @@ export async function wsRoutes(
// cross/absent origin before touching either credential, so a hijack
// attempt never reaches an authenticated socket.
preHandler: async (req) => {
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;
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 roleId = await authenticateWsHandshake(req);
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
req.wsRoleId = roleId;
@@ -206,6 +220,7 @@ export async function wsRoutes(
devices: seesDevices ? deviceMonitor.snapshot() : null,
lanes: seesDevices ? laneStatus.snapshot() : null,
radar: seesDevices ? lanePresence.snapshot() : null,
cameras: seesDevices ? cameraActivity.snapshot() : null,
});
// Subscribe to the live buses. Each handler recomputes occupancy from the
@@ -233,6 +248,10 @@ export async function wsRoutes(
const offPresence = deviceEvents.onLanePresence((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.
const offPlate = deviceEvents.onPlateRecognized((plate) => {
if (seesOccupancy) send({ kind: "plate-recognized", plate });
@@ -245,6 +264,7 @@ export async function wsRoutes(
offLane();
offPresence();
offPlate();
offCamera();
});
},
);
+14 -2
View File
@@ -47,6 +47,9 @@ import { entryRoutes } from "./routes/entry.js";
import { siteRoutes } from "./routes/site.js";
import { registerModules } from "./modules/index.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 { printerRoutes } from "./routes/printers.js";
import { setupRoutes } from "./routes/setup.js";
@@ -176,6 +179,14 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
const laneStatus = new LaneStatus(db, app.log);
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
// physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI.
const lanePresence = new LanePresence(db, app.log);
@@ -216,10 +227,11 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// Live booth feed: server-pushed ledger + occupancy + printer-status over a
// 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.
await snapshotRoutes(app, db);
await cameraRoutes(app, db, cameraLive);
// 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
@@ -270,7 +282,7 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// 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
// 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
// CHOSEN reader to populate a subscription credential, without blocking the other
+33
View File
@@ -94,6 +94,8 @@ export interface SessionUser {
theme: Theme;
/** Preferred UI font scale, percent of base (100 = base; clamped 80–160). */
fontScale: number;
/** Booth camera tiles left open (camera device ids, opening order). */
openCameras: string[];
/** Optional display name (profile metadata); null if unset. */
fullName: string | null;
/** Optional contact email (profile metadata); null if unset. */
@@ -156,6 +158,37 @@ export function setFontScalePref(fontScale: number): Promise<{ fontScale: number
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;
}
}
/** 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.
* Self-service — touches only the signed-in user; no `user:*` permission needed. */
export function updateMyProfile(patch: {
+10
View File
@@ -269,6 +269,16 @@ export const en: Catalog = {
clickForIssues: "Click for details",
checkedAt: "checked {{time}}",
},
camera: {
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",
},
booth: {
processTicket: "Process ticket",
scanPlaceholder: "Scan or type ticket number…",
+10
View File
@@ -271,6 +271,16 @@ export const sq = {
clickForIssues: "Kliko për detajet",
checkedAt: "kontrolluar {{time}}",
},
camera: {
live: "Live",
showTile: "Shfaq këtë kamerë",
hideTile: "Fshih këtë kamerë",
noSnapshot: "Ende pa foto",
idle: "Videoja live nis kur vjen një automjet",
connecting: "Po lidhet videoja live…",
liveUnavailable: "Videoja live nuk është e disponueshme",
vehicleInView: "Automjet në pamje",
},
booth: {
processTicket: "Proceso biletën",
scanPlaceholder: "Skano ose shkruaj numrin e biletës…",
+16 -1
View File
@@ -41,6 +41,8 @@ interface LiveState {
lanes: LaneStatus | null;
/** Per-lane radar presence (advisory blink). Null until the first WS hello. */
radar: LanePresence | null;
/** Camera ids currently seeing a vehicle — their booth tiles show live video. */
activeCameras: Record<string, true>;
setStatus: (s: WsStatus) => void;
setOccupancy: (o: Occupancy) => void;
pushEvent: (e: LedgerEvent) => void;
@@ -52,6 +54,10 @@ interface LiveState {
setLanes: (l: LaneStatus) => void;
/** Set lane radar presence (WS hello + each lane-presence push). */
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
* recognition that landed after the event's own push). No-op if no row matches. */
patchPlate: (identity: string, plate: string) => void;
@@ -70,6 +76,7 @@ export const useLiveStore = create<LiveState>((set) => ({
occupancy: null,
feed: [],
devices: {},
activeCameras: {},
lanes: null,
radar: null,
setStatus: (status) => set({ status }),
@@ -83,10 +90,18 @@ export const useLiveStore = create<LiveState>((set) => ({
upsertDevice: (d) => set((s) => ({ devices: { ...s.devices, [d.deviceId]: d } })),
setLanes: (lanes) => set({ lanes }),
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) =>
set((s) => {
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)) };
}),
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: {} }),
}));
+13 -6
View File
@@ -27,9 +27,12 @@ import { inTauri } from "./tauri-env.js";
const CONNECT_FAIL_LOG_INTERVAL_MS = 60_000;
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 {
onopen: (() => void) | null;
onmessage: ((ev: { data: string }) => void) | null;
onmessage: ((ev: PlatformMessage) => void) | null;
onclose: (() => void) | null;
onerror: (() => void) | null;
close(): void;
@@ -37,15 +40,16 @@ export interface PlatformSocket {
class NativeSocketAdapter implements PlatformSocket {
onopen: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null;
onmessage: ((ev: PlatformMessage) => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
#sock: WebSocket;
constructor(url: string) {
this.#sock = new WebSocket(url);
this.#sock.binaryType = "arraybuffer";
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.onerror = () => this.onerror?.();
}
@@ -57,7 +61,7 @@ class NativeSocketAdapter implements PlatformSocket {
class TauriSocketAdapter implements PlatformSocket {
onopen: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null;
onmessage: ((ev: PlatformMessage) => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
#closed = false;
@@ -95,11 +99,14 @@ class TauriSocketAdapter implements PlatformSocket {
conn.addListener((msg: { type: string; data: unknown }) => {
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?.();
}
// Binary/Ping/Pong: the server protocol here is text-JSON only (see
// routes/ws.ts) — nothing else is expected.
// Ping/Pong: nothing to do.
});
this.onopen?.();
} catch (err) {
+30 -3
View File
@@ -16,12 +16,13 @@ import { createPlatformSocket, type PlatformSocket } from "./platform-ws.js";
/** Server → client message shapes (mirror routes/ws.ts OutMsg). */
type WsMessage =
// 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: "printer-status"; event: unknown }
| { kind: "device-status"; event: DeviceStatus }
| { kind: "lane-status"; lanes: LaneStatus }
| { kind: "lane-presence"; radar: LanePresence }
| { kind: "camera-activity"; camera: { deviceId: string; active: boolean } }
| { kind: "plate-recognized"; plate: { identity: string; plate: string; direction: "entry" | "exit" } };
@@ -34,8 +35,18 @@ type WsMessage =
*/
export function useLiveFeed(enabled: boolean = true): void {
const qc = useQueryClient();
const { setStatus, setOccupancy, pushEvent, setDevices, upsertDevice, setLanes, setRadar, patchPlate } =
useLiveStore();
const {
setStatus,
setOccupancy,
pushEvent,
setDevices,
upsertDevice,
setLanes,
setRadar,
patchPlate,
setActiveCameras,
setCameraActive,
} = useLiveStore();
// Hold the socket + reconnect timer across renders; guard against StrictMode
// double-invoke and unmount.
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 (msg.lanes) setLanes(msg.lanes);
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") {
upsertDevice(msg.event);
} 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.occupancy });
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
// state and the per-shift log window — refresh the shift status too.
if (
@@ -113,6 +136,10 @@ export function useLiveFeed(enabled: boolean = true): void {
const scheduleReconnect = () => {
if (closedRef.current) return;
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.
const delay = Math.min(500 * 2 ** retryRef.current, 10_000);
retryRef.current += 1;
+19 -1
View File
@@ -17,6 +17,7 @@ import {
setLanguagePref,
setThemePref,
setFontScalePref,
setOpenCamerasPref,
FONT_SCALE_MIN,
FONT_SCALE_MAX,
FONT_SCALE_STEP,
@@ -384,6 +385,17 @@ function RootLayout() {
const canWatch = canWatchFeed(user);
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 (
<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">
@@ -459,7 +471,13 @@ function RootLayout() {
{/* Fixed device-status footer — relays, readers, cameras, printers. Its REST
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). */}
{user && show("device:read") && <DeviceFooter />}
{user && show("device:read") && (
<DeviceFooter
openCameras={user.openCameras ?? []}
onToggleCamera={toggleCamera}
canSeeSnapshots={show("session:read")}
/>
)}
</div>
);
}
+230
View File
@@ -0,0 +1,230 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { fetchLatestCameraSnapshot, fetchSnapshotObjectUrl, type DeviceStatus } from "../api.js";
import { formatClock } 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). Live frames come over their own socket as JPEG
// binaries; only the newest frame is shown. 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();
const active = useLiveStore((s) => s.activeCameras[deviceId] === true);
const live = useLiveFrames(deviceId, active);
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
const showLive = active && live.hasFrame;
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]">
{showLive ? (
<span className="flex items-center gap-1 font-semibold uppercase tracking-wider text-term-red">
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-term-red" />
{t("camera.live")}
</span>
) : null}
<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>
<div className="relative aspect-video bg-black">
{/* Live frames are painted straight into this <img> (no re-render per frame). */}
<img
ref={live.imgRef}
alt=""
className={`absolute inset-0 h-full w-full object-contain ${showLive ? "" : "hidden"}`}
/>
{!showLive && snapshot.url && (
<img src={snapshot.url} alt="" className="absolute inset-0 h-full w-full object-contain" />
)}
{!showLive && !snapshot.url && (
<div className="absolute inset-0 flex items-center justify-center px-2 text-center text-[0.6875rem] text-term-muted">
{canSeeSnapshots ? t("camera.noSnapshot") : t("camera.idle")}
</div>
)}
<div className="absolute bottom-0 left-0 right-0 truncate bg-black/60 px-1.5 py-0.5 text-[0.625rem] text-term-muted">
{active && !showLive
? live.status.state === "unavailable" || live.status.state === "retrying"
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
: t("camera.connecting")
: !showLive && snapshot.meta
? `${snapshot.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.meta.capturedAt)}`
: showLive
? t("camera.vehicleInView")
: ""}
</div>
</div>
</div>
);
}
/** Newest snapshot for the tile's resting picture, as an object URL (revoked on change). */
function useLatestSnapshot(deviceId: string, enabled: boolean) {
const meta = useQuery({
queryKey: ["camera-latest", deviceId],
queryFn: () => fetchLatestCameraSnapshot(deviceId),
enabled,
staleTime: 60_000,
});
const id = meta.data?.id ?? null;
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
if (!id) {
setUrl(null);
return;
}
let cancelled = false;
let made: string | null = null;
fetchSnapshotObjectUrl(id)
.then((u) => {
if (cancelled) URL.revokeObjectURL(u);
else {
made = u;
setUrl(u);
}
})
.catch(() => !cancelled && setUrl(null));
return () => {
cancelled = true;
if (made) URL.revokeObjectURL(made);
};
}, [id]);
return { meta: meta.data ?? null, url };
}
/**
* While `active`, 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.
*/
function useLiveFrames(deviceId: string, active: boolean) {
const imgRef = useRef<HTMLImageElement>(null);
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) => {
const img = imgRef.current;
if (closed || !img) 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;
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);
if (imgRef.current) imgRef.current.removeAttribute("src");
};
}, [deviceId, active]);
return { imgRef, status, hasFrame };
}
+45 -8
View File
@@ -5,6 +5,7 @@ import { fetchDeviceStatus, type DeviceStatus } from "../api.js";
import { formatClock } from "../lib/format.js";
import { qk } from "../lib/query.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
// 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 label = useLabel();
// Seed/fallback from REST; the WS keeps the live store authoritative thereafter.
@@ -111,17 +123,33 @@ export function DeviceFooter() {
) : (
devices.map((d) => {
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 (
<button
key={d.deviceId}
type="button"
// Only a problem chip is interactive (opens the issues panel).
onClick={isProblem ? () => setOpen((v) => !v) : undefined}
aria-disabled={!isProblem}
title={isProblem ? t("devices.clickForIssues") : undefined}
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 ${
isProblem ? "cursor-pointer hover:border-term-amber" : "cursor-default"
}`}
onClick={onClick}
aria-disabled={!onClick}
aria-pressed={isCamera ? isOpen : undefined}
title={
isCamera
? 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
className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT[d.state]} ${
@@ -153,6 +181,15 @@ export function DeviceFooter() {
)}
</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. */}
{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">