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:
@@ -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: {
|
||||
|
||||
@@ -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…",
|
||||
|
||||
@@ -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…",
|
||||
|
||||
@@ -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: {} }),
|
||||
}));
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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">
|
||||
|
||||
Reference in New Issue
Block a user