39fb5fb7c2
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>
166 lines
7.2 KiB
TypeScript
166 lines
7.2 KiB
TypeScript
import { useEffect, useRef } from "react";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import type { DeviceStatus, LedgerEvent, Occupancy } from "../api.js";
|
|
import { qk } from "./query.js";
|
|
import { useLiveStore, type LaneStatus, type LanePresence } from "./live-store.js";
|
|
import { wsUrl } from "./origin.js";
|
|
import { createPlatformSocket, type PlatformSocket } from "./platform-ws.js";
|
|
|
|
// Booth WebSocket client. Opens ONE socket to /api/ws and turns server pushes into
|
|
// (a) live-store updates for the ticker/occupancy and (b) Query cache invalidations
|
|
// so TanStack Query remains the source of truth for durable server data. The browser
|
|
// attaches the auth cookie automatically; the backend gates by cookie + Origin
|
|
// (see routes/ws.ts). Auto-reconnects with capped backoff so a booth left running
|
|
// recovers from a server restart without a manual refresh.
|
|
|
|
/** 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; 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" } };
|
|
|
|
|
|
/**
|
|
* @param enabled Gate on the WATCHER permission (`report:read` — mirrors the server's
|
|
* WS guard in routes/ws.ts). A user whose role lacks it (e.g. a merchant validator
|
|
* with only `validation:create`) must not attempt the socket at all: the server
|
|
* 403s the upgrade and the capped-backoff reconnect would otherwise hammer it
|
|
* forever, filling the server log with a 403 every few seconds.
|
|
*/
|
|
export function useLiveFeed(enabled: boolean = true): void {
|
|
const qc = useQueryClient();
|
|
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);
|
|
const retryRef = useRef(0);
|
|
const closedRef = useRef(false);
|
|
|
|
useEffect(() => {
|
|
if (!enabled) {
|
|
setStatus("closed");
|
|
return;
|
|
}
|
|
closedRef.current = false;
|
|
|
|
const connect = () => {
|
|
if (closedRef.current) return;
|
|
setStatus(retryRef.current === 0 ? "connecting" : "connecting");
|
|
const sock = createPlatformSocket(wsUrl("/api/ws"));
|
|
sockRef.current = sock;
|
|
|
|
sock.onopen = () => {
|
|
retryRef.current = 0;
|
|
setStatus("open");
|
|
};
|
|
|
|
sock.onmessage = (ev) => {
|
|
let msg: WsMessage;
|
|
try {
|
|
msg = JSON.parse(ev.data as string) as WsMessage;
|
|
} catch {
|
|
return; // ignore malformed frames
|
|
}
|
|
if (msg.kind === "hello") {
|
|
if (msg.occupancy) setOccupancy(msg.occupancy);
|
|
// Initial device-status snapshot for the footer.
|
|
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") {
|
|
setLanes(msg.lanes);
|
|
} else if (msg.kind === "lane-presence") {
|
|
setRadar(msg.radar);
|
|
} else if (msg.kind === "plate-recognized") {
|
|
// Backfill the badge on the already-rendered feed row, and refetch the
|
|
// Query-owned active-sessions list (re-runs enrichEvents → the now-written plate).
|
|
patchPlate(msg.plate.identity, msg.plate.plate);
|
|
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
|
} else if (msg.kind === "ledger") {
|
|
if (msg.occupancy) setOccupancy(msg.occupancy);
|
|
pushEvent(msg.event);
|
|
// Keep Query authoritative: the durable event list, occupancy totals,
|
|
// and active-sessions list refetch on the next read instead of trusting
|
|
// the pushed copy alone.
|
|
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 (
|
|
msg.event.type === "shift_open" ||
|
|
msg.event.type === "shift_z_report" ||
|
|
msg.event.type === "cash_movement" ||
|
|
msg.event.type === "cash_in" ||
|
|
msg.event.type === "cash_out" ||
|
|
msg.event.type === "carwash_payment"
|
|
) {
|
|
void qc.invalidateQueries({ queryKey: qk.shift });
|
|
}
|
|
} else if (msg.kind === "printer-status") {
|
|
void qc.invalidateQueries({ queryKey: ["printers"] });
|
|
}
|
|
};
|
|
|
|
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;
|
|
window.setTimeout(connect, delay);
|
|
};
|
|
|
|
sock.onclose = scheduleReconnect;
|
|
// onerror fires before onclose; let onclose own the reconnect to avoid double.
|
|
sock.onerror = () => sock.close();
|
|
};
|
|
|
|
connect();
|
|
|
|
return () => {
|
|
closedRef.current = true;
|
|
sockRef.current?.close();
|
|
sockRef.current = null;
|
|
};
|
|
// qc / store setters are stable; re-run only if the permission gate flips
|
|
// (login as a different role without a full reload).
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [enabled]);
|
|
}
|