diff --git a/apps/server/src/routes/setup-crossing.test.ts b/apps/server/src/routes/setup-crossing.test.ts new file mode 100644 index 0000000..60a379c --- /dev/null +++ b/apps/server/src/routes/setup-crossing.test.ts @@ -0,0 +1,72 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { devices, eq, type Db } from "@parking/db"; +import { createTestDb } from "@parking/db/testing"; +import type { FastifyInstance } from "fastify"; +import { buildServer } from "../server.js"; +import { seedUser, login } from "../test-helpers.js"; + +// A camera's crossing line (passage confirmation) rides in its config as `crossing`. The +// save validates it (the driver never reads it), and since an edit MERGES onto the stored +// config, clearing it must be an explicit `null`. + +let db: Db; +let close: () => void; +let app: FastifyInstance; +const CAM = "cam-1"; +const line = { p1: { x: 0.1, y: 0.6 }, p2: { x: 0.9, y: 0.55 }, direction: "a-to-b" }; + +beforeEach(async () => { + ({ db, close } = createTestDb()); + db.insert(devices).values({ + id: CAM, + category: "camera", + driverId: "dahua", + config: { host: "127.0.0.1", port: 80, username: "u", password: "p" }, + enabled: true, + }).run(); + app = await buildServer({ db }); + await app.ready(); + auth = undefined; +}); +afterEach(async () => { + await app.close(); + close(); +}); + +let auth: { cookie: string; csrf: string } | undefined; +async function edit(config: Record) { + if (!auth) { + await seedUser(db, { username: "admin", password: "pw" }); + auth = await login(app, "admin", "pw"); + } + return app.inject({ + method: "PATCH", + url: `/api/setup/assign/${CAM}`, + headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf }, + payload: { config: { host: "127.0.0.1", port: 80, username: "u", password: "p", ...config } }, + }); +} +const stored = () => db.select().from(devices).where(eq(devices.id, CAM)).get()!.config as Record; + +describe("camera crossing line on save", () => { + it("stores a valid line", async () => { + const res = await edit({ crossing: line }); + expect(res.statusCode).toBe(200); + expect(stored().crossing).toEqual(line); + }); + + it("keeps the stored line when the edit doesn't mention it, and clears it on null", async () => { + await edit({ crossing: line }); + await edit({}); + expect(stored().crossing).toEqual(line); + const res = await edit({ crossing: null }); + expect(res.statusCode).toBe(200); + expect(stored()).not.toHaveProperty("crossing"); + }); + + it("rejects an invalid line and leaves the stored config alone", async () => { + const res = await edit({ crossing: { ...line, p2: { x: 1.4, y: 0.5 } } }); + expect(res.statusCode).toBe(400); + expect(stored()).not.toHaveProperty("crossing"); + }); +}); diff --git a/apps/server/src/routes/setup.ts b/apps/server/src/routes/setup.ts index b2ae2f9..55d106b 100644 --- a/apps/server/src/routes/setup.ts +++ b/apps/server/src/routes/setup.ts @@ -16,7 +16,7 @@ import { type DeviceCategory, type DeviceConfig, } from "@parking/devices"; -import { reasonPayload } from "@parking/shared"; +import { parseCrossingLine, reasonPayload } from "@parking/shared"; import { requirePermission } from "../auth.js"; import type { EventLog } from "../event-log.js"; import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js"; @@ -147,6 +147,17 @@ async function configureDevice( // webPasswordCurrent is an input-only credential (the OLD password used to // authorize the change) — never persist it as typed. delete fullConfig.webPasswordCurrent; + // Camera crossing line (passage confirmation): validated here, since the driver doesn't + // read it. `null` clears it — the merge above would otherwise keep the stored line. + if ("crossing" in config) { + if (config.crossing === null) { + delete fullConfig.crossing; + } else { + const line = parseCrossingLine(config.crossing); + if (!line) return { error: { code: 400, message: "invalid crossing line" } }; + fullConfig.crossing = { ...line }; + } + } // Residual-risk warnings from device hardening (shown to the admin; the // save still succeeds — these are "configured, but note X" advisories). const hardenWarnings: string[] = []; diff --git a/apps/web/src/SetupWizard.tsx b/apps/web/src/SetupWizard.tsx index 12a086c..6175997 100644 --- a/apps/web/src/SetupWizard.tsx +++ b/apps/web/src/SetupWizard.tsx @@ -32,6 +32,8 @@ import { fetchUsbPrinters, } from "./api.js"; import { Modal } from "./ui/Modal.js"; +import { CrossingLineEditor } from "./ui/CrossingLineEditor.js"; +import { parseCrossingLine, type CrossingLine } from "@parking/shared"; // First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with // a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each @@ -534,6 +536,8 @@ function DeviceForm({ // back-plate read would otherwise phantom-exit the car that just entered). Defaults ON // when anpr is on (back-compat). (config.anprAutoTrigger). const [anprAuto, setAnprAuto] = useState(editCfg?.anprAutoTrigger !== false); + // Crossing line drawn over this camera's view (passage confirmation). (config.crossing) + const [crossing, setCrossing] = useState(() => parseCrossingLine(editCfg?.crossing)); // Pre-fill scalar config fields from the existing assignment when editing. // (relays/controllerId/relay are model fields handled by their own state below.) @@ -735,6 +739,8 @@ function DeviceForm({ // park can explicitly DISABLE auto-open on a camera (e.g. the exit cam of a shared lane) // while keeping recognition. Absent ⇒ defaults ON (back-compat for existing cameras). if (isCamera && anpr) out.anprAutoTrigger = anprAuto; + // Crossing line: always sent for a camera, `null` to clear (the server merges configs). + if (isCamera) out.crossing = crossing ? { p1: { ...crossing.p1 }, p2: { ...crossing.p2 }, direction: crossing.direction } : null; return out; } @@ -1085,6 +1091,15 @@ function DeviceForm({ )} + {/* CAMERA: the crossing line (passage confirmation), drawn over the live picture. + Needs a saved camera — the live stream is addressed by its device id. */} + {isCamera && + (editing?.id ? ( + + ) : ( +

{t("setup.crossingSaveFirst")}

+ ))} + {/* CAMERA + Alarm Server push ON: show the camera's Alarm Server settings, ready to copy, so the operator never has to find the deviceId or memorise the endpoint. The CAMERA reaches us over the device VLAN, NOT via the browser's diff --git a/apps/web/src/lib/i18n/en.ts b/apps/web/src/lib/i18n/en.ts index 8456439..18a48da 100644 --- a/apps/web/src/lib/i18n/en.ts +++ b/apps/web/src/lib/i18n/en.ts @@ -626,6 +626,15 @@ export const en: Catalog = { anprHint: "Read plates on this camera: the vision service reads the plate from each snapshot and records it (both entry and exit). Requires the vision service running.", anprAuto: "Auto open/close on subscriber plate", + crossingTitle: "Crossing line", + crossingHint: + "Drag across the picture to draw the line a vehicle must cross; drag an end to move it. Choose which crossing counts: A → B, B → A, or either.", + crossingDirection: "Direction", + crossingSwap: "Swap A/B", + crossingClear: "Clear", + crossingNone: "No line drawn.", + crossingWaiting: "Waiting for the camera…", + crossingSaveFirst: "Save the camera first to draw its crossing line.", anprAutoHint: "Let THIS camera auto-open the barrier when it recognises a subscriber's plate. Turn OFF on a shared entry/exit lane's exit camera, so a car driving IN isn't auto-EXITed by its back plate (recognition still runs — only the auto-trigger is off).", testAnpr: "Test ANPR", diff --git a/apps/web/src/lib/i18n/sq.ts b/apps/web/src/lib/i18n/sq.ts index 4078bec..57fa2b3 100644 --- a/apps/web/src/lib/i18n/sq.ts +++ b/apps/web/src/lib/i18n/sq.ts @@ -636,6 +636,15 @@ export const sq = { anprHint: "Lexo targat në këtë aparat: shërbimi i vizionit lexon targën nga çdo pamje dhe e regjistron (hyrje dhe dalje). Kërkon shërbimin e vizionit aktiv.", anprAuto: "Hapje/mbyllje automatike me targën e abonentit", + crossingTitle: "Vija e kalimit", + crossingHint: + "Tërhiq mbi pamje për të vizatuar vijën që duhet të kalojë mjeti; tërhiq një skaj për ta lëvizur. Zgjidh cili kalim numërohet: A → B, B → A, ose të dyja.", + crossingDirection: "Drejtimi", + crossingSwap: "Ndërro A/B", + crossingClear: "Pastro", + crossingNone: "Nuk ka vijë të vizatuar.", + crossingWaiting: "Në pritje të kamerës…", + crossingSaveFirst: "Ruaje kamerën fillimisht për të vizatuar vijën e kalimit.", anprAutoHint: "Lejo që KY aparat të hapë vetë barrierën kur njeh targën e një abonenti. ÇAKTIVIZOJE te aparati i daljes në një korsi të përbashkët hyrje/dalje, që një makinë që HYN të mos DALË automatikisht nga targa e pasme (njohja vazhdon — fiket vetëm hapja automatike).", testAnpr: "Testo ANPR", diff --git a/apps/web/src/ui/CameraDock.tsx b/apps/web/src/ui/CameraDock.tsx index 69686ed..b9055ee 100644 --- a/apps/web/src/ui/CameraDock.tsx +++ b/apps/web/src/ui/CameraDock.tsx @@ -409,7 +409,7 @@ function useSnapshotPicture(want: CameraSnapshotMeta | null): SnapshotPicture { * 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) { +export function useLiveFrames(deviceId: string, active: boolean) { // Every showing this camera (the tile, and the large view while open) gets each // frame; a view that mounts between frames is given the newest one at once. const imgs = useRef(new Map()); @@ -423,7 +423,7 @@ function useLiveFrames(deviceId: string, active: boolean) { imgs.current.delete(name); } }; - return { tile: slot("tile"), modal: slot("modal") }; + return { tile: slot("tile"), modal: slot("modal"), editor: slot("editor") }; }, []); const [status, setStatus] = useState({ state: "connecting" }); const [hasFrame, setHasFrame] = useState(false); diff --git a/apps/web/src/ui/CrossingLineEditor.tsx b/apps/web/src/ui/CrossingLineEditor.tsx new file mode 100644 index 0000000..2e96633 --- /dev/null +++ b/apps/web/src/ui/CrossingLineEditor.tsx @@ -0,0 +1,225 @@ +import { useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { + CROSSING_MIN_LENGTH, + type CrossingDirection, + type CrossingLine, + type FramePoint, +} from "@parking/shared"; +import { useLiveFrames } from "./CameraDock.js"; + +// Draws a camera's crossing line over its live picture — our own version of a Hikvision +// Line Crossing rule, for cameras that have none: a segment, sides A and B, and which +// crossing counts (A→B, B→A, A↔B). Points are normalised to the frame, so the line holds +// at any display size. Side A is the screen-left of p1→p2 (see crossingSide in shared). + +type Drag = { end: "p1" | "p2" } | null; + +const HANDLE_PX = 14; // grab radius around an end point + +export function CrossingLineEditor({ + deviceId, + value, + onChange, +}: { + deviceId: string; + value: CrossingLine | null; + onChange: (next: CrossingLine | null) => void; +}) { + const { t } = useTranslation(); + const live = useLiveFrames(deviceId, true); + const surface = useRef(null); + const [size, setSize] = useState({ w: 0, h: 0 }); + const [drag, setDrag] = useState(null); + // While drawing a new line it lives here, so a click-length line never reaches the form. + const [draft, setDraft] = useState(null); + const line = draft ?? value; + + // The overlay sits exactly on the picture (the wrapper is sized by the ), so its + // rectangle IS the frame: no letterbox offset to correct for. + useEffect(() => { + const el = surface.current; + if (!el) return; + const ro = new ResizeObserver(([e]) => e && setSize({ w: e.contentRect.width, h: e.contentRect.height })); + ro.observe(el); + return () => ro.disconnect(); + }, [live.hasFrame]); + + const toFrame = (ev: React.PointerEvent): FramePoint => { + const r = surface.current!.getBoundingClientRect(); + const clamp = (v: number) => Math.min(1, Math.max(0, v)); + return { x: clamp((ev.clientX - r.left) / r.width), y: clamp((ev.clientY - r.top) / r.height) }; + }; + const px = (p: FramePoint) => ({ x: p.x * size.w, y: p.y * size.h }); + + function onDown(ev: React.PointerEvent) { + if (!live.hasFrame) return; + ev.currentTarget.setPointerCapture(ev.pointerId); + const at = toFrame(ev); + if (value) { + for (const end of ["p1", "p2"] as const) { + const e = px(value[end]); + const a = px(at); + if (Math.hypot(e.x - a.x, e.y - a.y) <= HANDLE_PX) { + setDrag({ end }); + return; + } + } + } + // Anywhere else: draw a new line from here, keeping the chosen direction. + setDraft({ p1: at, p2: at, direction: value?.direction ?? "a-to-b" }); + setDrag({ end: "p2" }); + } + + function onMove(ev: React.PointerEvent) { + if (!drag) return; + const at = toFrame(ev); + if (draft) setDraft({ ...draft, [drag.end]: at }); + else if (value) onChange({ ...value, [drag.end]: at }); + } + + function onUp() { + if (draft && Math.hypot(draft.p2.x - draft.p1.x, draft.p2.y - draft.p1.y) >= CROSSING_MIN_LENGTH) { + onChange(draft); + } + setDraft(null); + setDrag(null); + } + + const directions: [CrossingDirection, string][] = [ + ["a-to-b", "A → B"], + ["b-to-a", "B → A"], + ["both", "A ↔ B"], + ]; + + return ( +
+
{t("setup.crossingTitle")}
+

{t("setup.crossingHint")}

+ +
+ + {!live.hasFrame && ( +
+ {live.status.state === "unavailable" || live.status.state === "retrying" + ? live.status.reason + : t("setup.crossingWaiting")} +
+ )} + {live.hasFrame && ( + + {line && size.w > 0 && } + + )} +
+ +
+
+ {directions.map(([d, label]) => ( + + ))} +
+ + +
+ {!value &&

{t("setup.crossingNone")}

} +
+ ); +} + +/** The segment, its end handles, the A/B labels either side, and an arrow across the + * middle pointing the way that counts (double-headed for A↔B). Pixel space. */ +function LineOverlay({ line, p1, p2 }: { line: CrossingLine; p1: FramePoint; p2: FramePoint }) { + const dx = p2.x - p1.x; + const dy = p2.y - p1.y; + const len = Math.hypot(dx, dy) || 1; + // Unit normal toward side A: the screen-left of p1→p2 (y down) is (dy, -dx). + const nA = { x: dy / len, y: -dx / len }; + const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }; + const at = (k: number) => ({ x: mid.x + nA.x * k, y: mid.y + nA.y * k }); + const aSide = at(22); + const bSide = at(-22); + const labelA = at(40); + const labelB = at(-40); + // Arrow runs from the side crossings start on to the side they end on. + const [from, to] = line.direction === "b-to-a" ? [bSide, aSide] : [aSide, bSide]; + const both = line.direction === "both"; + const stroke = "rgb(250 204 21)"; // amber, readable over daylight and night pictures + return ( + + + + + + + + + + {[p1, p2].map((p, i) => ( + + ))} + {( + [ + ["A", labelA], + ["B", labelB], + ] as const + ).map(([txt, p]) => ( + + {txt} + + ))} + + ); +} diff --git a/packages/shared/src/crossing-line.test.ts b/packages/shared/src/crossing-line.test.ts new file mode 100644 index 0000000..fdb32ff --- /dev/null +++ b/packages/shared/src/crossing-line.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { crossingSide, parseCrossingLine, type CrossingLine } from "./index.js"; + +// A horizontal line drawn left→right across the middle of the frame. +const line: CrossingLine = { p1: { x: 0.1, y: 0.5 }, p2: { x: 0.9, y: 0.5 }, direction: "a-to-b" }; + +describe("crossingSide", () => { + it("puts the screen-left of p1→p2 on side A (above a left→right line)", () => { + expect(crossingSide(line, { x: 0.5, y: 0.2 })).toBe("a"); + expect(crossingSide(line, { x: 0.5, y: 0.8 })).toBe("b"); + }); + it("swapping the points swaps the sides", () => { + const swapped = { ...line, p1: line.p2, p2: line.p1 }; + expect(crossingSide(swapped, { x: 0.5, y: 0.2 })).toBe("b"); + }); + it("is null exactly on the line", () => { + expect(crossingSide(line, { x: 0.3, y: 0.5 })).toBeNull(); + }); +}); + +describe("parseCrossingLine", () => { + it("accepts a valid line", () => { + expect(parseCrossingLine(line)).toEqual(line); + }); + it("rejects out-of-frame points, unknown directions and a click-length line", () => { + expect(parseCrossingLine({ ...line, p1: { x: -0.1, y: 0.5 } })).toBeNull(); + expect(parseCrossingLine({ ...line, direction: "up" })).toBeNull(); + expect(parseCrossingLine({ ...line, p2: { x: 0.11, y: 0.5 } })).toBeNull(); + expect(parseCrossingLine(null)).toBeNull(); + expect(parseCrossingLine({ p1: { x: "0.1", y: 0.5 }, p2: line.p2, direction: "both" })).toBeNull(); + }); +}); diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index a8e685a..5790438 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2211,3 +2211,57 @@ export function effectiveModules(entitled: readonly ModuleId[], activated: reado } return MODULE_IDS.filter((id) => on.has(id)); } + +// --- Passage confirmation: a crossing line drawn over a camera's view --------- +// The fleet cameras have no line-crossing rule of their own, so Setup draws one (like a +// Hikvision Line Crossing rule: a segment, sides A and B, and the direction that counts), +// and the booth's own tracker judges the crossing. See wiki/concepts/passage-confirmation.md. + +/** Which crossing counts as a passage: A→B, B→A, or either (A↔B). */ +export const CROSSING_DIRECTIONS = ["a-to-b", "b-to-a", "both"] as const; +export type CrossingDirection = (typeof CROSSING_DIRECTIONS)[number]; + +/** A point normalised to the camera frame: x right, y down, both 0..1. */ +export interface FramePoint { + x: number; + y: number; +} + +/** Stored as camera `config.crossing`. Side A is on the LEFT of p1→p2 as seen on screen; + * swapping the sides is swapping the two points. */ +export interface CrossingLine { + p1: FramePoint; + p2: FramePoint; + direction: CrossingDirection; +} + +/** Shortest line accepted (normalised length) — a click, not a drawn line. */ +export const CROSSING_MIN_LENGTH = 0.03; + +/** A valid `CrossingLine` from untrusted JSON, or null. */ +export function parseCrossingLine(v: unknown): CrossingLine | null { + if (!v || typeof v !== "object") return null; + const o = v as Record; + const pt = (p: unknown): FramePoint | null => { + if (!p || typeof p !== "object") return null; + const { x, y } = p as Record; + if (typeof x !== "number" || typeof y !== "number") return null; + if (!(x >= 0 && x <= 1 && y >= 0 && y <= 1)) return null; + return { x, y }; + }; + const p1 = pt(o.p1); + const p2 = pt(o.p2); + const direction = o.direction; + if (!p1 || !p2) return null; + if (!CROSSING_DIRECTIONS.includes(direction as CrossingDirection)) return null; + if (Math.hypot(p2.x - p1.x, p2.y - p1.y) < CROSSING_MIN_LENGTH) return null; + return { p1, p2, direction: direction as CrossingDirection }; +} + +/** Which side of the (infinite) line a point lies on, or null exactly on it. Note the + * frame's y axis points down: the left of p1→p2 on screen has a negative cross product. */ +export function crossingSide(line: CrossingLine, pt: FramePoint): "a" | "b" | null { + const { p1, p2 } = line; + const cross = (p2.x - p1.x) * (pt.y - p1.y) - (p2.y - p1.y) * (pt.x - p1.x); + return cross < 0 ? "a" : cross > 0 ? "b" : null; +}