feat(review): sample every detected car, not only ticketed entries
Build & push images / images (push) Successful in 5m20s

The entry stream for the reviewer was fed from the session-tied read only (ticket
printed / exit signed). park-2 ran an afternoon with its barriers up: hundreds of
camera vehicle pushes, zero tickets, zero samples.

- anpr-entry: keep the best-framed vehicle of each poll loop (highest body-type
  confidence with a box), store that frame as a snapshot (identity pass:<id>, no
  session) and emit a vehicle read with the camera id — plate or no plate. One
  sample per detection, fire-and-forget, never on the ANPR path.
- snapshot.ts: normalizedBoxes() shared by the session-tied read and the bridge;
  vehicle reads now carry deviceId.
- review-outbox: sampleEntry(deviceId) dedups per camera for 30 s so the pass
  sample and a ticket entry's read (same car, seconds apart) go once.
- wiki: outbox page (entry stream, troubleshooting checklist for 'nothing arrives':
  the month-long silence was a missing Netbird policy, not code), park-2 camera
  port-forward procedure (site-device-installation §7), log.
This commit is contained in:
2026-10-08 19:30:03 +02:00
parent 354de04a3d
commit 30a1180108
10 changed files with 288 additions and 28 deletions
+76 -9
View File
@@ -1,10 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db } from "@parking/db"; import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing"; import { createTestDb } from "@parking/db/testing";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js"; import { deviceEvents, type DeviceReadEvent, type VehicleReadEvent } from "./device-events.js";
import { silentLogger } from "./test-helpers.js"; import { silentLogger } from "./test-helpers.js";
import type { VisionClient, VisionResult } from "./vision-client.js"; import type { VisionClient, VisionResult, VisionVehicle } from "./vision-client.js";
import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js"; import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js";
// The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a // The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a
@@ -14,7 +14,12 @@ import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js
// Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub // Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub
// (no registry, no network). The factory returns a fresh shot each call. // (no registry, no network). The factory returns a fresh shot each call.
const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg" })); const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg", capturedAt: new Date().toISOString() }));
// The pass sample's box normalisation (needs a real JPEG header in prod) — stubbed so a
// test can hand the bridge a vehicle box, or none.
const { normalizedBoxes } = vi.hoisted(() => ({
normalizedBoxes: vi.fn(async (): Promise<{ vehicleBox: unknown; plateBox: unknown }> => ({ vehicleBox: null, plateBox: null })),
}));
// The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in // The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in
// snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this // snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this
// suite stays focused on the bridge's own match/debounce/emit logic. // suite stays focused on the bridge's own match/debounce/emit logic.
@@ -22,6 +27,9 @@ vi.mock("./snapshot.js", () => ({
buildCamera: () => ({ captureSnapshot }), buildCamera: () => ({ captureSnapshot }),
captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) => captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) =>
camera.captureSnapshot(ctx as never), camera.captureSnapshot(ctx as never),
// Storage re-encode is sharp's business (snapshot.test.ts); here the bytes pass through.
encodeForStorage: async (shot: { bytes: Buffer; contentType: string }) => ({ bytes: shot.bytes, contentType: shot.contentType }),
normalizedBoxes,
})); }));
// Import AFTER the mock is registered. // Import AFTER the mock is registered.
@@ -31,6 +39,8 @@ let db: Db;
beforeEach(() => { beforeEach(() => {
({ db } = createTestDb()); ({ db } = createTestDb());
captureSnapshot.mockClear(); captureSnapshot.mockClear();
normalizedBoxes.mockReset();
normalizedBoxes.mockResolvedValue({ vehicleBox: null, plateBox: null });
delete process.env.VISION_ENTRY_MIN_CONFIDENCE; delete process.env.VISION_ENTRY_MIN_CONFIDENCE;
delete process.env.ANPR_DEBOUNCE_MS; delete process.env.ANPR_DEBOUNCE_MS;
// Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate // Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate
@@ -74,17 +84,18 @@ function seedCamera(opts: { anpr?: boolean; anprAutoTrigger?: boolean } = {}): s
return camId; return camId;
} }
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null). */ /** A fake VisionClient: enabled, returning a chosen plate/confidence (or null), and
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number } = {}): VisionClient { * optionally a vehicle (body type + box) the way the vehicle stage reports it. */
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number; vehicle?: VisionVehicle } = {}): VisionClient {
const enabled = opts.enabled ?? true; const enabled = opts.enabled ?? true;
const result: VisionResult | null = const result: VisionResult | null =
opts.plate == null opts.plate == null && opts.vehicle == null
? null ? null
: { : {
plate: { text: opts.plate, confidence: opts.confidence ?? 0.99 }, plate: opts.plate == null ? null : { text: opts.plate, confidence: opts.confidence ?? 0.99 },
plates: [], plates: [],
lowConfidence: false, lowConfidence: false,
vehicle: null, vehicle: opts.vehicle ?? null,
modelVersion: "test", modelVersion: "test",
tookMs: 1, tookMs: 1,
}; };
@@ -122,6 +133,62 @@ async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]>
return got; return got;
} }
/** Capture vehicle-read (pass sample) events during `fn`, waiting for the bridge's
* fire-and-forget recording to land. */
async function captureVehicleReads(fn: () => Promise<void>, expectCount: number): Promise<VehicleReadEvent[]> {
const got: VehicleReadEvent[] = [];
const off = deviceEvents.onVehicleRead((e) => got.push(e));
try {
await fn();
if (expectCount > 0) await vi.waitFor(() => expect(got).toHaveLength(expectCount));
else await new Promise((r) => setTimeout(r, 20));
} finally {
off();
}
return got;
}
describe("AnprBridge pass sample — every detected car, ticket or not", () => {
const VEHICLE: VisionVehicle = { bodyType: "car", confidence: 0.91, bbox: { x1: 10, y1: 10, x2: 200, y2: 120 } };
const BOX = { x1: 0.1, y1: 0.1, x2: 0.5, y2: 0.6 };
it("stores the frame + emits a vehicle read with NO plate at all (barriers up: no ticket, no session)", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ vehicle: VEHICLE }), fakeSubFlow(null), silentLogger());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 1);
const read = got[0]!;
expect(read).toMatchObject({ direction: "entry", deviceId: cam, read: { bodyType: "car", confidence: 0.91, box: BOX, plateBox: null } });
expect(read.identity).toBe(`pass:${read.read.snapshotId}`);
const row = db.select().from(snapshots).where(eq(snapshots.id, read.read.snapshotId!)).get();
expect(row).toMatchObject({ direction: "entry", deviceId: cam, identity: read.identity, contentType: "image/jpeg" });
});
it("is ONE sample per detection even when the loop polls several frames, and rides along a subscriber emit", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: { x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 } });
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ plate: "AA111BB", confidence: 0.97, vehicle: VEHICLE }), fakeSubFlow(SUB_MATCH), silentLogger());
let reads: DeviceReadEvent[] = [];
const got = await captureVehicleReads(async () => {
reads = await captureReads(() => bridge.onVehicleDetected(cam));
}, 1);
expect(reads).toHaveLength(1); // the subscriber's plate read still goes out
expect(got[0]!.read.plateBox).toEqual({ x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 }); // for the crop's blur
expect(db.select().from(snapshots).all()).toHaveLength(1);
});
it("records nothing without a vehicle box (nothing to crop) — a bare class is not a sample", async () => {
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ vehicle: { bodyType: "car", confidence: 0.9 } }), fakeSubFlow(null), silentLogger());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 0);
expect(got).toEqual([]);
expect(db.select().from(snapshots).all()).toHaveLength(0);
});
});
describe("AnprBridge", () => { describe("AnprBridge", () => {
it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => { it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => {
const cam = seedCamera({ anpr: false }); const cam = seedCamera({ anpr: false });
+43 -3
View File
@@ -1,11 +1,12 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db, type DeviceRow } from "@parking/db"; 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 type { FastifyBaseLogger } from "fastify";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js"; import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
import { directionOf, type FlowDirection } from "./device-resolve.js"; import { directionOf, type FlowDirection } from "./device-resolve.js";
import { buildCamera } from "./snapshot.js"; import { buildCamera, encodeForStorage, normalizedBoxes } from "./snapshot.js";
import type { SubscriptionFlow } from "./subscription-flow.js"; import type { SubscriptionFlow } from "./subscription-flow.js";
import type { VisionClient } from "./vision-client.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 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 SAME gated SubscriptionFlow a QR/card scan uses. It is the one missing wire between
@@ -191,6 +192,9 @@ export class AnprBridge {
// pushes) is read from #pollDeadline each tick but never allowed past this cap. // pushes) is read from #pollDeadline each tick but never allowed past this cap.
const hardCap = Date.now() + this.#pollMaxMs; const hardCap = Date.now() + this.#pollMaxMs;
let attempts = 0; let attempts = 0;
// The best-framed vehicle of this loop (highest body-type confidence with a box):
// recorded once per detection as a PASS sample, whatever happens to the plate.
let best: { shot: Snapshot; r: VisionResult } | null = null;
try { try {
// DO-while: a detection always analyzes AT LEAST ONE frame, however loaded the // 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 // host — a plain while could zero-iterate if the window elapsed between setting
@@ -201,6 +205,7 @@ export class AnprBridge {
attempts++; attempts++;
const shot = await camera.captureSnapshot({ direction }); const shot = await camera.captureSnapshot({ direction });
const r = await this.#vision.analyze(shot.bytes, shot.contentType); const r = await this.#vision.analyze(shot.bytes, shot.contentType);
if (r?.vehicle?.bbox && (!best || r.vehicle.confidence > best.r.vehicle!.confidence)) best = { shot, r };
// Identify the subscriber from ANY readable plate (even below the barrier floor), // 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. // and baseline their open count once — so we can detect a credential beating us.
@@ -238,6 +243,7 @@ export class AnprBridge {
} finally { } finally {
this.#polling.delete(deviceId); this.#polling.delete(deviceId);
this.#pollDeadline.delete(deviceId); this.#pollDeadline.delete(deviceId);
if (best) void this.#recordPass(deviceId, direction, best);
} }
if (!result || !result.plate) { if (!result || !result.plate) {
@@ -302,6 +308,40 @@ export class AnprBridge {
this.#lastFire.set(key, Date.now()); this.#lastFire.set(key, Date.now());
} }
/** 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 poll loop, i.e.
* per detection, from its best-framed vehicle. Fire-and-forget: never on the ANPR path,
* a failure is a log line. Identity `pass:<snapshotId>` — no session to tie it to. */
async #recordPass(deviceId: string, direction: FlowDirection, best: { shot: Snapshot; r: VisionResult }): Promise<void> {
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 /** 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. */ * read on the bus — just a breadcrumb so the operator can see ANPR is working. */
#recordSkip(deviceId: string, plate: string, confidence: number): void { #recordSkip(deviceId: string, plate: string, confidence: number): void {
+3
View File
@@ -114,6 +114,9 @@ export interface PlateRecognizedEvent {
export interface VehicleReadEvent { export interface VehicleReadEvent {
readonly identity: string; readonly identity: string;
readonly direction: "entry" | "exit"; readonly direction: "entry" | "exit";
/** The camera that took the frame, so a listener can tell "same car, two reads seconds
* apart" (the bridge's pass sample + the ticket entry's read) from two cars. */
readonly deviceId?: string;
readonly read: VehicleRead; readonly read: VehicleRead;
} }
+1 -1
View File
@@ -23,7 +23,7 @@ export const carwashModule: ServerModule = {
// training material (the gate view, no order attached). The core announces the read; // training material (the gate view, no order attached). The core announces the read;
// the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set. // the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set.
const offVehicleRead = deviceEvents.onVehicleRead((e) => { const offVehicleRead = deviceEvents.onVehicleRead((e) => {
if (e.direction === "entry" && outbox.sampleEntry()) void outbox.enqueueEntry(e.read); if (e.direction === "entry" && outbox.sampleEntry(e.deviceId)) void outbox.enqueueEntry(e.read);
}); });
app.addHook("onClose", async () => offVehicleRead()); app.addHook("onClose", async () => offVehicleRead());
app.addHook("onClose", async () => outbox.stop()); app.addHook("onClose", async () => outbox.stop());
@@ -6,7 +6,7 @@ import type { FastifyInstance } from "fastify";
import { deviceEvents as deviceEventBus } from "../../device-events.js"; import { deviceEvents as deviceEventBus } from "../../device-events.js";
import { buildServer } from "../../server.js"; import { buildServer } from "../../server.js";
import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js"; import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js";
import { EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js"; import { ENTRY_DEDUP_MS, EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
// The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred // The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred
// vehicle crop + the operator's choice, queued off the intake path, drained one-way with // vehicle crop + the operator's choice, queued off the intake path, drained one-way with
@@ -165,6 +165,20 @@ describe("queue + drain", () => {
const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn); const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn);
expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]); expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]);
expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off
// Per-camera dedup: the bridge's pass sample and the ticket entry's read, seconds
// apart from the same camera, are ONE car — the second is skipped and not counted.
vi.useFakeTimers();
try {
const every = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 1 }, fetchFn);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry("cam-a")).toBe(false);
expect(every.sampleEntry("cam-b")).toBe(true); // another camera = another car
vi.advanceTimersByTime(ENTRY_DEDUP_MS + 1);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry()).toBe(true); // camera unknown → no dedup
} finally {
vi.useRealTimers();
}
expect(await sampler.enqueueEntry(read)).toBe(true); expect(await sampler.enqueueEntry(read)).toBe(true);
const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!; const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!;
expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } }); expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } });
@@ -63,6 +63,9 @@ const CROP_MARGIN = 0.08;
/** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks /** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks
* should not resurface a fortnight of crops in one burst. */ * should not resurface a fortnight of crops in one burst. */
export const EXPIRE_DAYS = 14; export const EXPIRE_DAYS = 14;
/** Two entry reads from the same camera closer than this are one car (the ANPR bridge's
* per-detection pass sample, then the ticket entry's session-tied read ~seconds later). */
export const ENTRY_DEDUP_MS = 30_000;
/** Backoff: 1 min · 2^attempts, capped. */ /** Backoff: 1 min · 2^attempts, capped. */
const BACKOFF_BASE_MS = 60_000; const BACKOFF_BASE_MS = 60_000;
const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000; const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000;
@@ -166,6 +169,9 @@ export class ReviewOutbox {
#timer: NodeJS.Timeout | null = null; #timer: NodeJS.Timeout | null = null;
#draining = false; #draining = false;
#entrySeen = 0; #entrySeen = 0;
/** Last entry sample per camera: the bridge's pass sample and the ticket entry's read are
* the SAME car seconds apart — one goes, the other is skipped (and not counted). */
readonly #lastEntryByDevice = new Map<string, number>();
constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) { constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) {
this.#db = db; this.#db = db;
@@ -202,9 +208,15 @@ export class ReviewOutbox {
/** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted /** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted
* in-process, so "1 in 5" is exactly that across a booth's day. */ * in-process, so "1 in 5" is exactly that across a booth's day. */
sampleEntry(): boolean { sampleEntry(deviceId?: string): boolean {
const n = this.#cfg?.entrySample ?? 0; const n = this.#cfg?.entrySample ?? 0;
if (n <= 0) return false; if (n <= 0) return false;
if (deviceId) {
const now = Date.now();
const last = this.#lastEntryByDevice.get(deviceId);
if (last != null && now - last < ENTRY_DEDUP_MS) return false;
this.#lastEntryByDevice.set(deviceId, now);
}
this.#entrySeen += 1; this.#entrySeen += 1;
return this.#entrySeen % n === 0; return this.#entrySeen % n === 0;
} }
+25 -12
View File
@@ -2,12 +2,12 @@ import { randomUUID } from "node:crypto";
import sharp from "sharp"; import sharp from "sharp";
import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db"; import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
import { registry, type CameraDevice, type Snapshot } from "@parking/devices"; import { registry, type CameraDevice, type Snapshot } from "@parking/devices";
import { reasonPayload } from "@parking/shared"; import { reasonPayload, type NormBox } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify"; import type { FastifyBaseLogger } from "fastify";
import { devicesByDirection, type FlowDirection } from "./device-resolve.js"; import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
import { deviceEvents } from "./device-events.js"; import { deviceEvents } from "./device-events.js";
import type { EventLog } from "./event-log.js"; import type { EventLog } from "./event-log.js";
import type { VisionClient } from "./vision-client.js"; import type { VisionClient, VisionResult } from "./vision-client.js";
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the // Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera // open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
@@ -171,23 +171,16 @@ async function recognizePlate(
// Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a // Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a
// downscaled copy — see reencodeForStorage), so the wash's review crop can cut the // downscaled copy — see reencodeForStorage), so the wash's review crop can cut the
// vehicle out of whatever copy survives and blur the plate inside it. // vehicle out of whatever copy survives and blur the plate inside it.
const frame = await frameSize(shot.bytes); const boxes = await normalizedBoxes(shot.bytes, result);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined) =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
// The vehicle's body type (advisory; the wash desk's category suggestion — see // The vehicle's body type (advisory; the wash desk's category suggestion — see
// venue-modules.md §Vehicle category). Rides the plate's read row when there is one, // venue-modules.md §Vehicle category). Rides the plate's read row when there is one,
// else a row of its own: a car with an unreadable plate is still a car of some class. // else a row of its own: a car with an unreadable plate is still a car of some class.
const vehicleBox = norm(result.vehicle?.bbox); const vehicleBox = boxes.vehicleBox;
const vehicle = result.vehicle const vehicle = result.vehicle
? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) } ? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) }
: {}; : {};
const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase(); const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase();
const plateBox = plate ? norm(result.plate?.bbox) : null; const plateBox = plate ? boxes.plateBox : null;
if (!plate && !result.vehicle) return; // nothing trustworthy to record if (!plate && !result.vehicle) return; // nothing trustworthy to record
db.insert(deviceEventsTable) db.insert(deviceEventsTable)
.values({ .values({
@@ -216,6 +209,7 @@ async function recognizePlate(
deviceEvents.emitVehicleRead({ deviceEvents.emitVehicleRead({
identity, identity,
direction, direction,
deviceId,
read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox }, read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox },
}); });
} }
@@ -241,6 +235,25 @@ function clamp01(v: number): number {
return Math.max(0, Math.min(1, v)); return Math.max(0, Math.min(1, v));
} }
/** The vehicle's and the plate's boxes as FRACTIONS of the analysed frame (null when the
* stage found none or the frame size is unreadable). Fractions, so the box fits the
* downscaled stored copy the wash's review crop is cut from. Shared by the session-tied
* recognition above and the ANPR bridge's per-car pass sample (anpr-entry.ts). */
export async function normalizedBoxes(
bytes: Buffer,
result: VisionResult,
): Promise<{ vehicleBox: NormBox | null; plateBox: NormBox | null }> {
const frame = await frameSize(bytes);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined): NormBox | null =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
return { vehicleBox: norm(result.vehicle?.bbox), plateBox: norm(result.plate?.bbox) };
}
/** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */ /** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */
async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> { async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {
try { try {
+43
View File
@@ -285,6 +285,49 @@ barcode with a real ticket (the KP-300H garbled overflowing barcodes until the g
8. Record in the site record: every IP, serial, camera password, printer model, which relay is 8. Record in the site record: every IP, serial, camera password, printer model, which relay is
which, photos of the labels. Remove the temporary laptop addresses. Log out of every device UI. which, photos of the labels. Remove the temporary laptop addresses. Log out of every device UI.
## 7. Reaching the cameras remotely — port forward through the booth host (park-2, 2026-10-08)
park-buzi exposed its two Hikvision web UIs on the site router (`park-buzi.msai.al:8081` / `:8082`,
see [[lpr-camera]]). park-2 does the same **through the booth host**, because its router only
knows the 192.168.1.0/24 side while the cameras live on the device VLAN:
| | address |
| --- | --- |
| router / internet side | `eno1` 192.168.1.101, gateway 192.168.1.1, public 91.230.255.154 |
| device VLAN side | `eno1` 10.0.10.101 (same NIC, second address) |
| Netbird | `wt0` 100.75.7.237 = `park-2.nb.infra` |
| entry camera | 10.0.10.9:80 → published as **8081** |
| exit camera | 10.0.10.10:80 → published as **8082** |
Done with iptables on the host (needs root; the admin account has no passwordless sudo).
`ip_forward` is already 1 because Docker set it. Docker also sets the FORWARD policy to DROP, so
the explicit ACCEPTs are mandatory, and the SNAT is what brings the camera's replies back through
the host (the cameras' gateway is not the booth):
```bash
iptables -t nat -A PREROUTING -p tcp --dport 8081 -j DNAT --to-destination 10.0.10.9:80
iptables -t nat -A PREROUTING -p tcp --dport 8082 -j DNAT --to-destination 10.0.10.10:80
iptables -t nat -A POSTROUTING -p tcp -d 10.0.10.9 --dport 80 -j SNAT --to-source 10.0.10.101
iptables -t nat -A POSTROUTING -p tcp -d 10.0.10.10 --dport 80 -j SNAT --to-source 10.0.10.101
iptables -I FORWARD -p tcp -d 10.0.10.9 --dport 80 -j ACCEPT
iptables -I FORWARD -p tcp -d 10.0.10.10 --dport 80 -j ACCEPT
iptables -I FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
apt install -y iptables-persistent && netfilter-persistent save # survive reboots
```
- **Reach:** from any Netbird peer with a policy to park-2, `http://park-2.nb.infra:8081/`
(no router change needed). From the internet only once the router forwards 8081/8082 to
192.168.1.101. PREROUTING does not apply to the host's own traffic — test from another machine.
- **Netbird-only variant:** add `-d 100.75.7.237` to the two PREROUTING rules; then the public
forward can never reach the cameras even if someone adds it on the router.
- **Undo:** the same lines with `-D`. **ufw**, if ever enabled there, also needs
`ufw route allow proto tcp to 10.0.10.9 port 80` (and `.10`).
- **Why not Docker:** `docker run -p 100.75.7.237:8081:80 alpine/socat …` would do the same
without sudo, bound to the overlay only; the user chose the iptables route.
- This is a deliberate hole in [[network-isolation]] (camera web UI reachable off the VLAN);
the camera's own digest auth is the only gate behind it. Keep the public side off unless
needed; prefer the Netbird path.
## Gaps to fill next time you hold the hardware ## Gaps to fill next time you hold the hardware
- Factory address and configuration tool of the **Cashino KP-300H** and the **Rongta RP** units - Factory address and configuration tool of the **Cashino KP-300H** and the **Rongta RP** units
+44 -1
View File
@@ -1,7 +1,7 @@
--- ---
title: Vision review outbox — harvesting the operator's category choice for a trusted reviewer title: Vision review outbox — harvesting the operator's category choice for a trusted reviewer
type: concept type: concept
status: booth side built 2026-09-06; collector pending status: live — first package delivered park-2 → collector 2026-10-08 (after a month blocked by a missing Netbird policy)
related: [venue-modules, opencv-anpr-service, threat-model, append-only-event-chain, network-isolation] related: [venue-modules, opencv-anpr-service, threat-model, append-only-event-chain, network-isolation]
--- ---
@@ -58,6 +58,20 @@ exactly one in N) and calls `enqueueEntry()`; the core never imports the module.
as "entry stream — label the vehicle", the export carries a `kind` column, and **operator as "entry stream — label the vehicle", the export carries a `kind` column, and **operator
agreement is computed from wash items only** (an entry sample has no operator decision). agreement is computed from wash items only** (an entry sample has no operator decision).
**Every car that passes, not only ticketed ones (2026-10-08).** The entry stream was fed from
the session-tied read only (`snapshot.ts`, taken when a ticket is printed or an exit is signed).
park-2 ran a whole afternoon with its barriers up: hundreds of camera vehicle pushes, zero
tickets, zero samples. So the ANPR bridge (`anpr-entry.ts`), which already pulls and analyses
frames for every vehicle push on an `anpr: true` camera, now keeps the **best-framed vehicle of
each poll loop** (highest body-type confidence with a box), stores that one frame as a snapshot
(`identity = pass:<snapshotId>`, no session) and emits a vehicle read with the camera's id —
plate or no plate. One sample per detection (the loop is one per car, joins slide it). The
module's `sampleEntry(deviceId)` **dedups per camera for 30 s** (`ENTRY_DEDUP_MS`): the pass
sample and the ticket entry's read, seconds apart from the same camera, are one car. The plate
box is handed over whenever the detector saw a plate, confident or not — it is what the crop
blurs. Pass snapshots ride the normal retention/pruning. Needs `anpr: true` and the per-camera
auto-trigger on (the bridge bails before polling otherwise) — same gate as recognition today.
An internet feed was considered the same day and kept OUT of the collector's ingest: licensed An internet feed was considered the same day and kept OUT of the collector's ingest: licensed
sets only, in a separate folder with provenance, used as warm-up and weighted down, and never sets only, in a separate folder with provenance, used as warm-up and weighted down, and never
the judge of accuracy — the evaluation set is gate crops only. the judge of accuracy — the evaluation set is gate crops only.
@@ -177,3 +191,32 @@ that start like a spreadsheet formula (category/service names are booth-supplied
**Status (2026-09-07).** Live: the collector runs on `art-docker-station` and park-2 is wired to **Status (2026-09-07).** Live: the collector runs on `art-docker-station` and park-2 is wired to
it (`stage-dbbb051` on both stacks, every entry sampled). The review screen at it (`stage-dbbb051` on both stacks, every entry sampled). The review screen at
`http://docker-station.nb.infra:8090/review` is filling; no labels reviewed yet. `http://docker-station.nb.infra:8090/review` is filling; no labels reviewed yet.
## Troubleshooting — "the cameras are busy but nothing reaches the collector" (2026-10-08)
Found a month after both sides were built: **not one package had ever arrived**. Both codebases
were fine; the Netbird **policy** between the booths group and the collector host did not exist,
so `docker-station.nb.infra` resolved nowhere from the booth (Node: `fetch failed`, cause
`ENOTFOUND`; every row `queued`, attempts climbing, the 6 h backoff cap hiding it). Adding the
policy in the Netbird dashboard was the whole fix — the first row went out at its next scheduled
retry, nothing restarted. Checklist, in order:
1. **Is anything queued at all?** Only a vehicle read **tied to a session** (ticket taken or an
exit) is sampled; the camera's motion pushes feed subscription plate matching only. Barriers
left open = no tickets = no samples, however busy the lane. Query on the booth (no sqlite3
there; use the image's own driver):
```bash
s=$(docker ps -q --filter name=server); m=/app/node_modules/.pnpm/better-sqlite3@12.10.1/node_modules/better-sqlite3
docker exec $s node -e "const D=require('$m');const db=new D('/data/parking.sqlite',{readonly:true});
console.log(db.prepare(\"select status, json_extract(payload,'\$.kind') kind, count(*) n, max(sent_at) lastSent, max(last_error) err from carwash_review_outbox group by 1,2\").all())"
```
(`kind` lives inside `payload`; the image is in the row until delivered.)
2. **`fetch failed`** → from the booth host: `resolvectl query docker-station.nb.infra` and
`netbird status -d | grep -A4 docker-station`. Not found / not listed = the booth and the
collector host are not peers → Netbird policy. Resolves = `curl -X POST
http://docker-station.nb.infra:8090/ingest` must answer **401** (the collector's token check),
anything else is the collector.
3. **Collector side:** `docker logs wash-collector-collector-1 | grep -c /ingest` — zero means
nothing ever arrived; the container's health lines are its own probes.
4. After the fix, rows drain on **their own timers** (`1 min · 2^attempts`, cap 6 h); a restart
does not reset `next_attempt_at`. Expect a backlog to trickle in over hours, new rows at once.
+25
View File
@@ -3442,3 +3442,28 @@ code, not by level: `/health` silent on both services, one request line instead
`onError` hook so 5xx keep logging under `disableRequestLogging`), hik-alarm HIT and per-snapshot `onError` hook so 5xx keep logging under `disableRequestLogging`), hik-alarm HIT and per-snapshot
byte lines demoted to debug via a level on `stubLog`. Pages: [[app-logs]] §Noise cut. byte lines demoted to debug via a level on `stubLog`. Pages: [[app-logs]] §Noise cut.
- 2026-10-08 — **stage-1167e27 never built**: the code fix and the TAG bump were pushed together, so CI tagged the image with the push head (`stage-32b4d9e`); Komodo deploy failed "not found". Re-pinned all four stacks to `stage-32b4d9e`; rule added to [[fleet-deployment-komodo]] (push code first, bump after the build). - 2026-10-08 — **stage-1167e27 never built**: the code fix and the TAG bump were pushed together, so CI tagged the image with the push head (`stage-32b4d9e`); Komodo deploy failed "not found". Re-pinned all four stacks to `stage-32b4d9e`; rule added to [[fleet-deployment-komodo]] (push code first, bump after the build).
## [2026-10-08] query | Review outbox never delivered — missing Netbird policy, not code
A month of silence from the collector: park-2 had 22 entry samples `queued`, all `fetch failed`
(`ENOTFOUND docker-station.nb.infra`). park-2's Netbird peer list had no docker-station and vice
versa — no policy booths → collector host. User added the access in the Netbird dashboard; the
first package went out at its next scheduled retry (16:49Z) and the collector logged the ingest.
Also clarified why camera traffic ≠ samples (only session-tied reads are sampled; barriers were
open, so almost no tickets). Troubleshooting checklist added to [[vision-review-outbox]].
## [2026-10-08] ingest | park-2 camera port forward through the booth host (iptables)
8081 → entry camera 10.0.10.9:80, 8082 → exit camera 10.0.10.10:80, DNAT + SNAT + FORWARD
ACCEPTs on park-2 (Docker's FORWARD DROP policy makes the ACCEPTs mandatory). Reachable over
Netbird as `park-2.nb.infra:8081/8082`; public only if the router forwards to 192.168.1.101.
Procedure, undo and the Netbird-only variant in [[site-device-installation]] §7.
## [2026-10-08] ingest | Review outbox: sample every detected car, not only ticketed entries
User: "I need every car that passes to be pushed to the server" — park-2's barriers were up, so
hundreds of camera pushes produced no session-tied reads and no samples. The ANPR bridge now
records one PASS sample per detection (best-framed vehicle of its poll loop → stored snapshot
`pass:<id>` + vehicle read with `deviceId`); the Car Wash sampler dedups per camera for 30 s so a
ticketed car is not sent twice. Also flushed park-2's 21 backed-off rows (`next_attempt_at = now`)
so the reviewer got the day's backlog at once. Pages: [[vision-review-outbox]] §entry stream.