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>
231 lines
8.0 KiB
TypeScript
231 lines
8.0 KiB
TypeScript
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 };
|
|
}
|