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.
{shown.map((id) => ( onClose(id)} /> ))}
); } 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 (
{showLive ? ( {t("camera.live")} ) : null} {title}
{/* Live frames are painted straight into this (no re-render per frame). */} {!showLive && snapshot.url && ( )} {!showLive && !snapshot.url && (
{canSeeSnapshots ? t("camera.noSnapshot") : t("camera.idle")}
)}
{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") : ""}
); } /** 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(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(null); const [status, setStatus] = useState({ 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 | 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 }; }