import { randomUUID } from "node:crypto"; import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db, type DeviceRow } from "@parking/db"; import type { Snapshot } from "@parking/devices"; import type { FastifyBaseLogger } from "fastify"; import { deviceEvents, type DeviceReadEvent } from "./device-events.js"; import { directionOf, type FlowDirection } from "./device-resolve.js"; import { buildCamera, encodeForStorage, normalizedBoxes } from "./snapshot.js"; import type { SubscriptionFlow } from "./subscription-flow.js"; import type { VisionClient, VisionResult } from "./vision-client.js"; // The ANPR "bridge": a subscriber's plate, read from the lane camera, admits them through // the SAME gated SubscriptionFlow a QR/card scan uses. It is the one missing wire between // the camera's vehicle PUSH (hikvision-alarm.ts) and the read bus — NOT a new service. // // On a `vehicle`/`active` event from an OPT-IN camera (config.anpr === true), the bridge runs // ONE poll loop per camera: while the camera keeps pushing (a car is moving in the zone) it // pulls fresh frames back-to-back → vision.analyze → entry confidence floor → MATCH the plate // to a subscription → emit a DeviceReadEvent{kind:"plate"} ONLY if it matched — once per // plate per loop, and once per plate per ANPR_DEBOUNCE_MS across loops. The existing onRead → // ReadDispatcher then re-matches and runs the gated SubscriptionFlow (active / window / // blocklist / car-count), which signs the entry/exit and opens the relay. // // The loop does NOT stop at the first confident plate (2026-10-11). The camera fires an // independent push on every motion (~1.2 s apart while a car moves — park-2, 2780 pushes, all // activePostCount=1, never `inactive`), so a second car tailgating the first keeps the loop // alive and is read by the same loop. Before, the loop broke on the first read and a 12 s // CAMERA-level debounce then dropped every push — 40 of 57 plate-driven opens at park-2 had // a push land in that blind window. The debounce is per PLATE now. // // INVARIANTS (see wiki/concepts/lane-presence-and-anpr-entry.md §2, append-only-event-chain.md): // - Advisory, never sole authority: the bridge only emitRead()s — the signed decision + // barrier open stay inside the existing flow. A spoofed printed plate is just another // credential through the same gate. // - Subscriber-ONLY: it MATCHES before emitting, so a random plate never reaches the // transient plate-as-ticket exit flow. // - Fail-soft + fire-and-forget: any snapshot/vision error degrades to the card/QR path; // never throws into the push handler, never awaited on the camera's 200 response. // - Opt-in per camera, and debounced PER PLATE (the same car reads confidently on every // frame once it is framed; one presentation = one read). /** Camera config flag opting it into the ANPR bridge (same flag advisory ANPR uses). */ interface CameraConfig { readonly anpr?: boolean; /** Whether this camera may AUTO-OPEN the barrier (entry/exit). Absent ⇒ true (when anpr is * on). Set false to keep recognition but suppress auto-trigger — e.g. the exit camera on a * shared entry/exit lane. */ readonly anprAutoTrigger?: boolean; readonly [k: string]: unknown; } /** Stricter-than-advisory confidence floor for a BARRIER-driving plate read. A near-miss * read falls back to the subscriber's card/QR, so we'd rather skip than wrongly admit. * Distinct from vision-client's advisory VISION_MIN_CONFIDENCE. */ function entryMinConfidence(): number { const raw = Number(process.env.VISION_ENTRY_MIN_CONFIDENCE ?? 0.85); return Number.isFinite(raw) && raw > 0 ? raw : 0.85; } /** Same plate on the same camera within this window = ONE credential presentation. A framed * car reads confidently on every frame, and a car that stops and re-starts in the zone * starts a new loop; emitting each time would drive repeat entries (a fleet sub opens a 2nd * occurrence) or exit spam. Keyed by PLATE, never by camera — a camera-level stamp made the * lane blind to the next car for the whole window. Required for correctness, not CPU. */ function debounceMs(): number { const raw = Number(process.env.ANPR_DEBOUNCE_MS ?? 12_000); return Number.isFinite(raw) && raw > 0 ? raw : 12_000; } /** A single alarm fires the INSTANT motion starts — the car is still approaching, so the * first frame often has a small/blurry/absent plate (a low-confidence misread). The readable * moments (stopped at the barrier; a gap in headlight glare) are short, so the loop pulls * frames BACK-TO-BACK: a pull is ~0.1 s and an analyze ~0.25 s on the booth (park-2, * 2026-10-11), i.e. ~3 frames/s per camera, serial, which the camera's single-threaded * picture endpoint takes without a 503. This is the MINIMUM spacing between two pulls * (ms); 0 = as fast as the camera + recognizer go. Raise it to throttle a weak host. */ function pollMs(): number { const raw = Number(process.env.ANPR_POLL_MS ?? 0); return Number.isFinite(raw) && raw >= 0 ? raw : 0; } /** How long to keep polling AFTER THE LAST vehicle push before giving up. SLIDING: each new * push for the camera extends the deadline by this much from now — so a loop started by a * far/early car keeps pulling fresh frames as the REAL car arrives and settles at the * barrier (the loop tracks "whoever is here now", not the car that started it). */ function pollWindowMs(): number { const raw = Number(process.env.ANPR_POLL_WINDOW_MS ?? 8000); return Number.isFinite(raw) && raw >= 0 ? raw : 8000; // 0 = one frame per push } /** Hard ceiling on a single loop from its START, so a continuously-busy lane (pushes never * stop) can't slide the window forever. The loop ends at min(lastPush + window, start + max). */ function pollMaxMs(): number { const raw = Number(process.env.ANPR_POLL_MAX_MS ?? 30_000); return Number.isFinite(raw) && raw > 0 ? raw : 30_000; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** A plate DeviceReadEvent skeleton (value filled by the caller) — for matching the * subscriber by plate during the poll loop without re-building the whole event. */ function baseRead(row: { driverId: string }, deviceId: string): Omit { return { driverId: row.driverId, deviceId, kind: "plate", at: new Date().toISOString() }; } export class AnprBridge { readonly #db: Db; readonly #vision: VisionClient | null; readonly #subscription: SubscriptionFlow; readonly #logger: FastifyBaseLogger; readonly #entryMinConfidence: number; readonly #debounceMs: number; readonly #pollMs: number; readonly #pollWindowMs: number; readonly #pollMaxMs: number; /** Last emit timestamps keyed by `deviceId:plate`, gated against #debounceMs. Nothing is * keyed by camera: the lane must never go blind to the NEXT car. Pruned on stamp. */ readonly #lastFire = new Map(); /** Cameras with a poll loop already in flight — a re-fired alarm (the camera pushes on * every motion while a car moves) must NOT start a second concurrent loop on the same * camera: its picture endpoint is single-threaded (a parallel GET gets HTTP 503). */ readonly #polling = new Set(); /** Per-camera SLIDING deadline for the running poll loop. A push that joins a running loop * bumps this forward (lastPush + window, capped at start + max), so the loop keeps pulling * fresh frames while cars keep arriving — tracking whoever settles at the barrier. */ readonly #pollDeadline = new Map(); constructor(db: Db, vision: VisionClient | null, subscription: SubscriptionFlow, logger: FastifyBaseLogger) { this.#db = db; this.#vision = vision; this.#subscription = subscription; this.#logger = logger; this.#entryMinConfidence = entryMinConfidence(); this.#debounceMs = debounceMs(); this.#pollMs = pollMs(); this.#pollWindowMs = pollWindowMs(); this.#pollMaxMs = pollMaxMs(); } /** * A camera reported a vehicle. If the camera opts into ANPR, pull a snapshot, read the * plate, and — only if it matches a subscription — emit a plate read onto the bus. * Fire-and-forget; fail-soft. Never throws (the push handler must always 200). */ async onVehicleDetected(deviceId: string): Promise { try { if (!this.#vision?.enabled) return; // no recognizer configured // Admin master switch (read LIVE so toggling in Site Settings takes effect with no // restart). Gates ONLY this barrier-driving bridge — advisory snapshot-ANPR and lane // busy/free are unaffected. Absent/unreadable config ⇒ enabled (the default). const site = this.#db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get(); if (site && site.anprEntryEnabled === false) return; const row = this.#db.select().from(devices).where(eq(devices.id, deviceId)).get(); if (!row || !row.enabled || row.category !== "camera") return; const cfg = row.config as CameraConfig; if (cfg?.anpr !== true) return; // recognition opt-in (also gates the evidence/advisory path) // Per-camera AUTO-TRIGGER gate. `anpr` keeps recognition (snapshots + plate record) on; // this controls whether THIS camera may auto-open the barrier. A shared entry/exit lane // sets it false on (e.g.) the exit camera so its back-plate read doesn't phantom-exit the // car that just entered. Absent ⇒ true (back-compat: existing anpr cameras still trigger). if (cfg.anprAutoTrigger === false) return; // One poll loop per camera. A push that arrives while a loop runs JOINs it — and // SLIDES the deadline forward (a different car arriving mid-loop keeps the loop alive // so it reads whoever is at the barrier now; the loop never stops on the first plate). const now = Date.now(); if (this.#polling.has(deviceId)) { const cur = this.#pollDeadline.get(deviceId) ?? now; // Slide to lastPush + window, but never past the per-loop hard ceiling (set at start). this.#pollDeadline.set(deviceId, Math.max(cur, now + this.#pollWindowMs)); return; } this.#polling.add(deviceId); // Initial deadline; the hard ceiling (start + max) is enforced in the loop below. this.#pollDeadline.set(deviceId, now + this.#pollWindowMs); const camera = buildCamera(row); if (!camera) { this.#polling.delete(deviceId); this.#logger.warn(`anpr-bridge: camera ${deviceId} config won't build`); return; } // "both" collapses to entry purely for the capture hint (it doesn't pick the lane — // the gated flow infers the verb from the camera's bound relay direction). const direction: FlowDirection = directionOf(this.#db, row) === "exit" ? "exit" : "entry"; // READ-EVERY-FRAME. The alarm fires as the car APPROACHES (small/blurry/absent plate → // low-confidence misread, e.g. '111'@0.20); the readable moments come later and may be // short (stopped at the barrier; a gap in glare). So we pull FRESH frames back-to-back // (#pollMs is only a floor) and re-run ANPR for as long as the camera keeps pushing — // the sliding deadline — or until the hard cap. Every confident plate is SETTLED once // per loop (emitted, skipped, or declined); the loop goes on afterwards so a second car // behind the first is read by the same loop. NB: a fresh pull each tick — NOT // captureSnapshotShared, whose TTL would re-serve the same bad frame. // // Credential race: a subscriber may scan their card/QR at the reader while we are still // reading them. We learn a subscription as soon as a frame reads its plate (identity // needs no confidence) and remember their open-occurrence count; if it has moved by the // time the plate reads confidently, they already transacted and we do NOT emit (it would // act on the NEXT open occurrence: a phantom double-exit, worst for a fleet sub). const hardCap = Date.now() + this.#pollMaxMs; let attempts = 0; /** Plates settled in THIS loop — a framed car reads confidently on every frame. */ const handled = new Set(); /** Below-floor plate texts already logged at info (repeats go to debug). */ const weakLogged = new Set(); /** Subscriptions sighted this loop → open-occurrence count at first sighting. */ const sighted = new Map(); let emitted = 0; // The best-framed vehicle PER CONFIDENT PLATE (highest body-type confidence with a // box), plus one "" bucket for frames with no confident plate: PASS samples, one per // car the loop could tell apart, whatever happens to the plate. const best = new Map(); try { // DO-while: a detection always analyzes AT LEAST ONE frame, however loaded the // host — a plain while could zero-iterate if the window elapsed between setting // the deadline and reaching the loop (seen as a CI flake with the tests' 5ms // window; on a busy booth it would silently drop a real car's detection). do { attempts++; const tick = Date.now(); const shot = await camera.captureSnapshot({ direction }); const r = await this.#vision.analyze(shot.bytes, shot.contentType); const plate = r?.plate?.text.trim().toUpperCase() ?? ""; const confident = plate !== "" && r!.plate!.confidence >= this.#entryMinConfidence; if (r?.vehicle?.bbox) { const key = confident ? plate : ""; const cur = best.get(key); if (!cur || r.vehicle.confidence > cur.r.vehicle!.confidence) best.set(key, { shot, r }); } // Identify the subscriber from ANY readable plate (even below the barrier floor) // and baseline their open count once — so we can detect a credential beating us. if (plate) { const m0 = this.#subscription.match({ ...baseRead(row, deviceId), value: plate }); if (m0 && !sighted.has(m0.subscriptionId)) { sighted.set(m0.subscriptionId, this.#subscription.openOccurrenceCount(m0.subscriptionId)); } } if (confident && !handled.has(plate)) { handled.add(plate); if (this.#settle(row, deviceId, plate, r!.plate!.confidence, sighted)) emitted++; } else if (plate && !confident && !handled.has(plate)) { const line = `anpr-bridge: '${plate}' (${r!.plate!.confidence.toFixed(3)}) below floor ` + `${this.#entryMinConfidence} — re-pulling (attempt ${attempts})`; if (weakLogged.has(plate)) this.#logger.debug(line); else { weakLogged.add(plate); this.#logger.info(line); } } // Stop once the (possibly slid) deadline or the cap has passed; else pace to #pollMs. const effDeadline = Math.min(this.#pollDeadline.get(deviceId) ?? 0, hardCap); const left = effDeadline - Date.now(); if (left <= 0) break; const wait = this.#pollMs - (Date.now() - tick); if (wait > 0) await sleep(Math.min(wait, left)); } while (true); } finally { this.#polling.delete(deviceId); this.#pollDeadline.delete(deviceId); // One pass sample per plated car. The plateless bucket only when NO car got a plate // (otherwise it is mostly the plated cars' approach frames — not another car). for (const [key, b] of best) { if (key !== "" || best.size === 1) void this.#recordPass(deviceId, direction, b); } } if (handled.size === 0) { this.#logger.info( `anpr-bridge: no confident plate from ${deviceId} after ${attempts} frame(s) ` + `in ${Date.now() - now}ms — gave up`, ); } else { this.#logger.info( `anpr-bridge: ${deviceId} loop done — ${attempts} frame(s) in ${Date.now() - now}ms, ` + `${handled.size} plate(s), ${emitted} emitted`, ); } } catch (err) { // Fail-soft: an ANPR failure degrades to the subscriber's card/QR, never strands the lane. this.#logger.warn(`anpr-bridge failed (${deviceId}): ${(err as Error).message}`); } } /** * Settle ONE confident plate: match it to a subscriber (MATCH BEFORE EMIT — a non-subscriber * plate records advisory telemetry and stops; it must NEVER reach the transient * plate-as-ticket exit flow), decline if that subscriber already transacted by another * credential during this loop, debounce per plate, then emit. Returns true if emitted. */ #settle( row: { driverId: string }, deviceId: string, plate: string, confidence: number, sighted: ReadonlyMap, ): boolean { const e: DeviceReadEvent = { ...baseRead(row, deviceId), value: plate }; const match = this.#subscription.match(e); if (!match) { this.#recordSkip(deviceId, plate, confidence); return false; } const base = sighted.get(match.subscriptionId); if (base != null && this.#subscription.openOccurrenceCount(match.subscriptionId) !== base) { this.#logger.info( `anpr-bridge: subscriber ${match.subscriptionId} transacted by another credential mid-poll — not emitting '${plate}'`, ); return false; } // Per-PLATE debounce across loops: the same car re-starting in the zone within the window // is still the same presentation. Never per camera — the next car must not be blind. const plateKey = `${deviceId}:${plate}`; if (this.#debounced(plateKey)) { this.#logger.debug(`anpr-bridge: '${plate}' read again within ${this.#debounceMs}ms — debounced`); return false; } this.#stamp(plateKey); this.#logger.info(`anpr-bridge: subscriber plate '${plate}' (${confidence.toFixed(3)}) → read bus`); deviceEvents.emitRead(e); // → onRead → ReadDispatcher → gated SubscriptionFlow return true; } #debounced(key: string): boolean { const last = this.#lastFire.get(key); return last != null && Date.now() - last < this.#debounceMs; } #stamp(key: string): void { const now = Date.now(); this.#lastFire.set(key, now); // One key per plate ever seen would grow forever on a busy lane; drop expired stamps. if (this.#lastFire.size > 256) { for (const [k, t] of this.#lastFire) if (now - t >= this.#debounceMs) this.#lastFire.delete(k); } } /** EVERY car the camera flagged becomes one stored frame + one vehicle read on the bus — * plate or no plate, ticket or no ticket. The read is what the Car Wash module samples * for the reviewer (wiki/concepts/vision-review-outbox.md §entry stream); until this, * only session-tied reads were sampled, so a lot with its barriers up (nobody takes a * ticket) sent nothing however many cars the camera saw. One sample per car the loop * could tell apart (per confident plate; one for a plateless loop), from its best-framed * frame. Fire-and-forget: never on the ANPR path, a failure is a log line. Identity * `pass:` — no session to tie it to. */ async #recordPass(deviceId: string, direction: FlowDirection, best: { shot: Snapshot; r: VisionResult }): Promise { try { const vehicle = best.r.vehicle; if (!vehicle) return; const { vehicleBox, plateBox } = await normalizedBoxes(best.shot.bytes, best.r); if (!vehicleBox) return; const stored = await encodeForStorage(best.shot, this.#logger); const id = randomUUID(); const identity = `pass:${id}`; this.#db .insert(snapshots) .values({ id, direction, deviceId, identity, contentType: stored.contentType, bytes: stored.bytes, capturedAt: best.shot.capturedAt }) .run(); // plateBox whenever the detector saw a plate, confident or not: it is what the // review crop blurs — privacy, not identity. deviceEvents.emitVehicleRead({ identity, direction, deviceId, read: { bodyType: vehicle.bodyType, confidence: vehicle.confidence, snapshotId: id, box: vehicleBox, plateBox }, }); this.#logger.debug(`anpr-bridge: pass sample ${id} '${vehicle.bodyType}' (${vehicle.confidence.toFixed(3)}) from ${deviceId}`); } catch (err) { this.#logger.warn(`anpr-bridge: pass sample failed for ${deviceId}: ${(err as Error).message}`); } } /** Advisory telemetry: a plate was read at the lane but matched no subscription. Not a * read on the bus — just a breadcrumb so the operator can see ANPR is working. */ #recordSkip(deviceId: string, plate: string, confidence: number): void { this.#logger.info(`anpr-bridge: plate '${plate}' matched no subscription — skipped`); try { this.#db .insert(deviceEventsTable) .values({ id: randomUUID(), deviceId, category: "camera", kind: "anpr-skip", detail: { plate, confidence, source: "anpr-bridge", reason: "no subscription match" }, occurredAt: new Date().toISOString(), }) .run(); } catch (err) { this.#logger.error(`anpr-bridge skip-record insert failed: ${(err as Error).message}`); } } } // DeviceRow is re-exported for the test's seed typing convenience. export type { DeviceRow };