3 Commits

Author SHA1 Message Date
julian d93089a491 feat(anpr): read every frame, settle every plate, debounce per plate
Build & push images / images (push) Successful in 3m9s
Measured on park-2 (i5-9500): a main-stream pull is ~0.1s and /analyze
~0.25s while the host sat under 3% CPU; the loop's fixed 1s sleep was the
limit (one frame per ~1.35s). The camera's picture endpoint is single-
threaded (4 parallel GETs -> two 503s) and the vision service serialises
inference, so no threads: pulls are back-to-back and serial per camera,
~3 fps. ANPR_POLL_MS is now a floor (default 0).

The loop no longer breaks on the first confident plate, and the 12s
camera-level debounce is gone: 40 of 57 plate-driven opens at park-2 had a
push dropped in that blind window, so a tailgating car was never looked at.
Each confident plate is settled once per loop (emit / anpr-skip / decline)
and the loop runs on while the camera keeps pushing, so a second car is
read by the same loop. Debounce is keyed deviceId:plate only; the card/QR
mid-poll guard is per subscriber instead of aborting the loop; the pass
sample is one per plated car. ANPR_POLL_WINDOW_MS=0 is honoured (it used to
fall back to 8s silently).

The camera event model was re-confirmed from 2780 pushes: every push is an
independent VMD/active with activePostCount=1, ~1.2s apart while a car
moves, never inactive. Nothing is held for 30s on the camera side.
2026-10-11 18:17:25 +02:00
julian 7b29331f52 fix(devices): Hikvision clock sync owns the time zone (fixed offset, re-set at DST edges)
park-2's cameras burned Beijing time into every frame: factory zone CST-8,
and the sync compared instants only, so zero drift meant the zone was never
touched. The G3H firmware also accepts a POSIX zone with a DST rule, echoes
it back, and ignores the rule.

syncClock now derives the site's current UTC offset as a fixed Hikvision
zone (hikvisionFixedZone) and rewrites it when it differs, sending the clock
with it. The device monitor adds a third trigger beside offline->ready and
the 24h backstop: the moment the site's UTC offset changes, so a DST switch
is handled within one poll. ClockSyncResult reports zoneChanged/timeZone.

Both park-2 cameras were set to CST-2:00:00 by hand on 2026-10-09; this
must be deployed there before 2026-10-25 or the OSD reads 1h ahead from
that day until it is.
2026-10-11 18:17:25 +02:00
julian 9332802e5d feat(server): log every relay pulse and echo it to device_events (kind relay)
One pulse path, pulseBarrier (relay-pulse.ts), for all six callers: entry
button/operator mint, reader and booth exits, subscription opens, manual
(forgiven) exits and the setup relay test. Each pulse writes an info line
naming relay, controller, direction, identity and operator, and inserts a
device_events row of kind "relay" for success and failure alike; failures
are still re-thrown so each flow keeps its own anomaly handling.

Prompted by the 2026-10-09 park-2 "barrier opened by itself" claim: the
ledger showed the why, but nothing recorded the moment a relay was actually
driven. The signed ledger stays the authority; this is unsigned telemetry.

Also git-ignores tmp/ (site snapshots pulled for incident review).
2026-10-11 18:17:25 +02:00
18 changed files with 729 additions and 199 deletions
+3
View File
@@ -33,3 +33,6 @@ questions.txt
task_plan.md
findings.md
progress.md
# local scratch (site snapshots pulled for incident review, never committed)
tmp/
+4 -1
View File
@@ -76,7 +76,10 @@ WS_ALLOWED_ORIGINS=http://localhost:5173,tauri://localhost,http://tauri.localhos
# camera's vehicle detection, admits them through the gated SubscriptionFlow. Opt-in per
# camera (the camera's config.anpr checkbox in Setup); the camera must be BOUND to a relay.
# VISION_ENTRY_MIN_CONFIDENCE=0.85 # stricter floor for a BARRIER-driving read (near-miss → falls back to card/QR)
# ANPR_DEBOUNCE_MS=12000 # same plate/camera within this window = ONE presentation (camera re-fires ~1Hz)
# ANPR_DEBOUNCE_MS=12000 # same PLATE on the same camera within this window = ONE presentation (never per camera)
# ANPR_POLL_MS=0 # MIN spacing between frame pulls while a car is in the zone; 0 = back-to-back (~3 fps/camera)
# ANPR_POLL_WINDOW_MS=8000 # keep reading this long after the camera's LAST vehicle push (0 = one frame per push)
# ANPR_POLL_MAX_MS=30000 # hard cap on one loop from its start, however busy the lane
# Venue modules --------------------------------------------------------------
# Comma-separated ids of the modules this site is ENTITLED to (a vendor/deployment
+92 -18
View File
@@ -43,9 +43,10 @@ beforeEach(() => {
normalizedBoxes.mockResolvedValue({ vehicleBox: null, plateBox: null });
delete process.env.VISION_ENTRY_MIN_CONFIDENCE;
delete process.env.ANPR_DEBOUNCE_MS;
// Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate
// case gives up in ~one tick instead of the 8s production window (tests stay fast). Each
// bridge reads these in its constructor, so set them before `new AnprBridge`.
// Read-every-frame loop: keep the window tiny so a loop ends in a few ticks instead of the
// 8s production window (tests stay fast); the 1ms floor keeps a mocked loop from spinning
// thousands of frames. Each bridge reads these in its constructor, so set them before
// `new AnprBridge`.
process.env.ANPR_POLL_MS = "1";
process.env.ANPR_POLL_WINDOW_MS = "5";
});
@@ -107,19 +108,35 @@ function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: numb
/** A fake SubscriptionFlow: only `match()` is called by the bridge. */
function fakeSubFlow(
match: SubscriptionMatch | null,
// A fixed answer, or a matcher by plate (several subscribers in one loop).
match: SubscriptionMatch | null | ((plate: string) => SubscriptionMatch | null),
// openOccurrenceCount: a constant, or a sequence consumed per call (to simulate a
// credential closing an occurrence mid-poll → count changes).
openCounts: number | number[] = 1,
): SubscriptionFlow {
const seq = Array.isArray(openCounts) ? [...openCounts] : null;
return {
match: vi.fn(() => match),
match: vi.fn((e: DeviceReadEvent) => (typeof match === "function" ? match(e.value) : match)),
openOccurrenceCount: vi.fn(() => (seq ? (seq.length > 1 ? seq.shift()! : seq[0]) : (openCounts as number))),
} as unknown as SubscriptionFlow;
}
const SUB_MATCH: SubscriptionMatch = { subscriptionId: "sub-1", carKey: "AA111BB", via: "plate" };
const SUB_MATCH_2: SubscriptionMatch = { subscriptionId: "sub-2", carKey: "CC333DD", via: "plate" };
/** A VisionClient whose analyze() walks a sequence of (plate, confidence) frames, holding the
* last one — the way a car's read evolves as it approaches and settles, or as one car gives
* way to the next. `vehicle` (optional) rides every frame. */
function sequenceVision(frames: { plate: string; confidence: number }[], vehicle: VisionVehicle | null = null): VisionClient {
let i = 0;
return {
enabled: true,
analyze: vi.fn(async () => {
const f = frames[Math.min(i++, frames.length - 1)]!;
return { plate: { text: f.plate, confidence: f.confidence }, plates: [], lowConfidence: false, vehicle, modelVersion: "test", tookMs: 1 };
}),
} as unknown as VisionClient;
}
/** Capture read events emitted during `fn` (async). */
async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]> {
@@ -165,7 +182,7 @@ describe("AnprBridge pass sample — every detected car, ticket or not", () => {
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 () => {
it("is ONE sample per car 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());
@@ -179,6 +196,23 @@ describe("AnprBridge pass sample — every detected car, ticket or not", () => {
expect(db.select().from(snapshots).all()).toHaveLength(1);
});
it("samples EACH plated car of a loop once — two cars back to back → two samples", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
const cam = seedCamera({ anpr: true });
// Car A (3 frames) then car B, both framed; a non-subscriber lot (match null) — the
// sample is about the reviewer's stream, not about admission.
const vision = sequenceVision(
[{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 }, { plate: "CC333DD", confidence: 0.96 }],
VEHICLE,
);
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 2);
expect(got).toHaveLength(2);
expect(db.select().from(snapshots).all()).toHaveLength(2);
});
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());
@@ -251,9 +285,10 @@ describe("AnprBridge", () => {
})),
} as unknown as VisionClient;
// Generous window so all 3 escalation attempts run deterministically under suite load
// (the global beforeEach sets a tiny 5ms window for the give-up cases).
// (the global beforeEach sets a tiny 5ms window for the give-up cases). The loop keeps
// reading until the window ends — the same plate must still be emitted exactly once.
process.env.ANPR_POLL_MS = "1";
process.env.ANPR_POLL_WINDOW_MS = "2000";
process.env.ANPR_POLL_WINDOW_MS = "150";
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
@@ -299,18 +334,40 @@ describe("AnprBridge", () => {
expect(reads[0]).toMatchObject({ value: "AA111BB" });
});
it("ABORTS if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
// The car's plate is read (identity known) but stays below the floor; meanwhile the
// subscriber scans their card → openOccurrenceCount drops. The bridge must abort and NOT
// emit (which would exit the NEXT open occurrence — a phantom double-exit, esp. fleet).
it("does NOT emit if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
// The car's plate is read (identity known) while still below the floor; meanwhile the
// subscriber scans their card → openOccurrenceCount drops. When the plate finally reads
// confidently the bridge must NOT emit (it would exit the NEXT open occurrence — a
// phantom double-exit, esp. fleet).
const cam = seedCamera({ anpr: true });
const vision = fakeVision({ plate: "AA111BB", confidence: 0.5 }); // never clears the floor
// openOccurrenceCount: 1 at baseline, then 0 (the card exit closed it) on the next check.
const vision = sequenceVision([{ plate: "AA111BB", confidence: 0.5 }, { plate: "AA111BB", confidence: 0.97 }]);
// openOccurrenceCount: 1 at first sighting, then 0 (the card exit closed it) at settle time.
const sub = fakeSubFlow(SUB_MATCH, [1, 0]);
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
expect(reads).toEqual([]); // aborted — the credential already handled it
expect(reads).toEqual([]); // declined — the credential already handled it
expect(vision.analyze).toHaveBeenCalledTimes; // (the loop itself kept going)
});
it("KEEPS READING after a confident plate: a second car in the same loop is emitted too", async () => {
// Car A reads confidently on frames 1-3, then car B pulls into the zone (frames 4+).
// Before 2026-10-11 the loop broke on A's first read and the camera-level debounce then
// dropped every push for 12s — B was invisible. Now A is settled once and the loop goes
// on; B is read by the same loop. Each plate exactly once, however many frames repeat.
const cam = seedCamera({ anpr: true });
const vision = sequenceVision([
{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 },
{ plate: "CC333DD", confidence: 0.96 },
]);
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
expect(captureSnapshot.mock.calls.length).toBeGreaterThan(4); // it did not stop at A
});
it("does NOT emit for a plate matching no subscription — records an advisory anpr-skip", async () => {
@@ -342,17 +399,34 @@ describe("AnprBridge", () => {
expect(skips).toHaveLength(1);
});
it("debounces: two vehicle events within the window analyze/emit at most once", async () => {
it("debounces PER PLATE: the same car re-detected within the window is emitted once", async () => {
const cam = seedCamera({ anpr: true });
const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 });
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
const reads = await captureReads(async () => {
await bridge.onVehicleDetected(cam);
await bridge.onVehicleDetected(cam); // within the 12s window → suppressed
await bridge.onVehicleDetected(cam); // a second loop — the same plate within 12s → suppressed
});
expect(reads).toHaveLength(1);
expect(captureSnapshot).toHaveBeenCalledTimes(1); // 2nd was gated before the snapshot
expect(captureSnapshot.mock.calls.length).toBeGreaterThanOrEqual(2); // the 2nd loop DID look
});
it("is NOT blind after a read: a different car detected right after is emitted", async () => {
// The old camera-level debounce dropped every push for 12s after a success. A car behind
// the first, arriving after the first loop ended, must get its own loop and its own read.
const cam = seedCamera({ anpr: true });
const frames = [{ plate: "AA111BB", confidence: 0.97 }];
const vision = sequenceVision(frames);
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(async () => {
await bridge.onVehicleDetected(cam); // car A
frames[0] = { plate: "CC333DD", confidence: 0.96 }; // car B now in the zone
await bridge.onVehicleDetected(cam); // its push starts a new loop
});
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
});
it("is a no-op (no throw) when vision is disabled or reads nothing", async () => {
+156 -123
View File
@@ -12,11 +12,20 @@ import type { VisionClient, VisionResult } from "./vision-client.js";
// 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:
// pull a fresh snapshot → vision.analyze → entry confidence floor → debounce → MATCH the
// plate to a subscription → emit a DeviceReadEvent{kind:"plate"} ONLY if it matched.
// 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.
// 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 +
@@ -26,7 +35,8 @@ import type { VisionClient, VisionResult } from "./vision-client.js";
// 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 (the camera re-fires ~1Hz while a car sits).
// - 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 {
@@ -46,22 +56,26 @@ function entryMinConfidence(): number {
return Number.isFinite(raw) && raw > 0 ? raw : 0.85;
}
/** Same plate/camera within this window = ONE credential presentation. The camera re-fires
* ~1Hz while a car is present; emitting every second would drive repeat entries (a fleet
* sub opens a 2nd occurrence) or exit spam. Required for correctness, not CPU. */
/** 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). But the car
* then STOPS at the barrier (waiting for it to open) — the same stationary, well-framed
* moment the manual test reads at ~100%. So instead of one shot, we POLL fresh frames and
* re-run ANPR until one clears the confidence floor, or the window elapses. Poll interval: */
* 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 ?? 1000);
return Number.isFinite(raw) && raw > 0 ? raw : 1000;
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
@@ -70,7 +84,7 @@ function pollMs(): number {
* 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;
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
@@ -98,11 +112,12 @@ export class AnprBridge {
readonly #pollMs: number;
readonly #pollWindowMs: number;
readonly #pollMaxMs: number;
/** Last-fire timestamps, keyed by deviceId (camera-level, pre-snapshot) AND by
* `deviceId:plate` (post-match) — both gated against #debounceMs. */
/** 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<string, number>();
/** Cameras with a poll loop already in flight — a re-fired alarm (the camera pushes ~1Hz
* while the car sits) must NOT start a second concurrent loop on the same camera. */
/** 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<string>();
/** 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
@@ -144,13 +159,9 @@ export class AnprBridge {
// car that just entered. Absent ⇒ true (back-compat: existing anpr cameras still trigger).
if (cfg.anprAutoTrigger === false) return;
// Post-success debounce: once we've emitted a read for this camera, ignore the
// ~1Hz re-fires for #debounceMs (set on success below). A fresh alarm AFTER the
// window is a new presentation and may start a new poll loop.
if (this.#debounced(deviceId)) 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 tracks whoever's at the barrier now, instead of giving up on the early car).
// 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;
@@ -173,148 +184,170 @@ export class AnprBridge {
// the gated flow infers the verb from the camera's bound relay direction).
const direction: FlowDirection = directionOf(this.#db, row) === "exit" ? "exit" : "entry";
// POLL-UNTIL-CONFIDENT. The alarm fires as the car APPROACHES (small/blurry/absent
// plate → low-confidence misread, e.g. '111'@0.20). But the car then STOPS at the
// barrier — the stationary, well-framed moment the manual test reads at ~100%. So we
// pull a FRESH frame every #pollMs and re-run ANPR until one clears the floor, or the
// #pollWindowMs window elapses (car drove off / non-subscriber). NB: a fresh pull each
// tick — NOT captureSnapshotShared, whose TTL would re-serve the same bad frame.
// While polling, watch whether THIS subscriber transacts by another credential
// (card/QR at the reader). If their open-occurrence count drops mid-poll, the
// subscriber already exited/entered — the bridge must NOT also emit (it would act on
// the NEXT open occurrence: a phantom double-exit, worst for a fleet sub). We learn the
// subscription as soon as a frame reads the bound plate (identity needs no confidence),
// snapshot the count, then keep polling for a CONFIDENT read; abort if the count moved.
let result: Awaited<ReturnType<VisionClient["analyze"]>> = null;
let watchedSubId: string | null = null;
let baselineOpen = 0;
// Hard ceiling for THIS loop (start + max); the sliding deadline (bumped by joining
// pushes) is read from #pollDeadline each tick but never allowed past this cap.
// 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;
// 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;
/** Plates settled in THIS loop — a framed car reads confidently on every frame. */
const handled = new Set<string>();
/** Below-floor plate texts already logged at info (repeats go to debug). */
const weakLogged = new Set<string>();
/** Subscriptions sighted this loop → open-occurrence count at first sighting. */
const sighted = new Map<string, number>();
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<string, { shot: Snapshot; r: VisionResult }>();
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). Exit
// is via the breaks below (confident read, or next tick would pass the deadline).
// 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);
if (r?.vehicle?.bbox && (!best || r.vehicle.confidence > best.r.vehicle!.confidence)) best = { shot, r };
const plate = r?.plate?.text.trim().toUpperCase() ?? "";
const confident = plate !== "" && r!.plate!.confidence >= this.#entryMinConfidence;
// Identify the subscriber from ANY readable plate (even below the barrier floor),
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 (r?.plate?.text) {
const m0 = this.#subscription.match({ ...baseRead(row, deviceId), value: r.plate.text.trim().toUpperCase() });
if (m0 && watchedSubId == null) {
watchedSubId = m0.subscriptionId;
baselineOpen = this.#subscription.openOccurrenceCount(watchedSubId);
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));
}
}
// A credential (card/QR) closed/opened an occurrence for this subscriber mid-poll →
// they already transacted; stop polling and do NOT emit.
if (watchedSubId && this.#subscription.openOccurrenceCount(watchedSubId) !== baselineOpen) {
this.#logger.info(
`anpr-bridge: subscriber ${watchedSubId} transacted by another credential mid-poll — aborting ANPR`,
);
return;
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);
}
}
if (r?.plate && r.plate.confidence >= this.#entryMinConfidence) {
result = r;
break;
}
if (r?.plate) {
this.#logger.info(
`anpr-bridge: '${r.plate.text}' (${r.plate.confidence.toFixed(3)}) below floor ` +
`${this.#entryMinConfidence} — re-pulling (attempt ${attempts})`,
);
}
// Stop if the next tick would land past the (possibly slid) deadline or the cap.
// 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);
if (Date.now() + this.#pollMs >= effDeadline) break;
await sleep(this.#pollMs);
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);
if (best) void this.#recordPass(deviceId, direction, best);
// 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 (!result || !result.plate) {
if (handled.size === 0) {
this.#logger.info(
`anpr-bridge: no confident plate from ${deviceId} after ${attempts} attempt(s) ` +
`in ${this.#pollWindowMs}ms — gave up`,
`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`,
);
return;
}
const plate = result.plate.text.trim().toUpperCase();
if (!plate) return;
const e: DeviceReadEvent = {
driverId: row.driverId,
deviceId,
value: plate,
kind: "plate",
at: new Date().toISOString(),
};
// MATCH BEFORE EMIT — subscriber-only. A non-subscriber plate records advisory
// telemetry and stops; it must NEVER reach the transient plate-as-ticket exit flow.
const match = this.#subscription.match(e);
if (!match) {
this.#recordSkip(deviceId, plate, result.plate.confidence);
return;
}
// Final guard against the credential-mid-poll race: if the subscriber transacted between
// our baseline and now (e.g. a card scan in the last tick), don't double-act.
if (watchedSubId === match.subscriptionId && this.#subscription.openOccurrenceCount(match.subscriptionId) !== baselineOpen) {
this.#logger.info(`anpr-bridge: ${match.subscriptionId} already transacted — skipping ANPR emit`);
return;
}
// Plate-level debounce — belt-and-suspenders against a gap that slips the
// camera-level gate re-emitting the SAME plate.
const plateKey = `${deviceId}:${plate}`;
if (this.#debounced(plateKey)) return;
this.#stamp(plateKey);
// Camera-level debounce stamp — now that we've emitted, suppress the camera's ~1Hz
// re-fires (and any new poll loop) for #debounceMs.
this.#stamp(deviceId);
this.#logger.info(
`anpr-bridge: subscriber plate '${plate}' (${result.plate.confidence.toFixed(3)}) → read bus`,
);
deviceEvents.emitRead(e); // → onRead → ReadDispatcher → gated SubscriptionFlow
} 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<string, number>,
): 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 {
this.#lastFire.set(key, Date.now());
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 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. */
* 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:<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;
+18 -6
View File
@@ -27,8 +27,10 @@ const POLL_MS = Number(process.env.DEVICE_POLL_MS ?? 8000);
// Camera clock sync (Hikvision loses its clock on power cuts — reboots at the 1970
// epoch until a human logs into its web UI). The monitor re-syncs from the HOST
// clock (the site's offline time authority) at the offline→ready edge — exactly the
// power-restored moment — plus a daily backstop; drift under the threshold is left
// alone. See wiki/entities/lpr-camera.md (clock sync).
// power-restored moment — plus a daily backstop, plus the moment the site's UTC offset
// changes (a DST switch: the camera's zone is a FIXED offset the host rewrites, see
// HikvisionCamera.syncClock); drift under the threshold is left alone. See
// wiki/entities/lpr-camera.md (clock sync).
const CLOCK_SYNC_BACKSTOP_MS = 24 * 60 * 60 * 1000;
const CLOCK_MAX_DRIFT_SEC = 60;
@@ -201,18 +203,26 @@ export class DeviceMonitor {
}
// Camera clock re-sync at the power-restored edge (prev offline/unknown →
// ready) + a daily backstop. Stamped BEFORE the async attempt so a failing
// camera is retried at backstop cadence, never every poll.
// ready) + a daily backstop + the site's UTC-offset edge (DST switch). Stamped
// BEFORE the async attempt so a failing camera is retried at backstop cadence,
// never every poll.
if (row.category === "camera" && next.state === "ready" && device && isClockSyncable(device)) {
const prev = this.#latest.get(row.id);
const cameBack = !prev || prev.state === "offline";
const last = this.#clockSyncedAt.get(row.id) ?? 0;
if (cameBack || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
const nowIso = localIsoWithOffset(siteTz(this.#db));
const offset = nowIso.slice(-6);
const offsetChanged = this.#clockSyncedOffset.get(row.id) !== offset;
if (cameBack || offsetChanged || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
this.#clockSyncedAt.set(row.id, Date.now());
this.#clockSyncedOffset.set(row.id, offset);
const cam = device;
void (async () => {
try {
const r = await cam.syncClock(localIsoWithOffset(siteTz(this.#db)), CLOCK_MAX_DRIFT_SEC);
const r = await cam.syncClock(nowIso, CLOCK_MAX_DRIFT_SEC);
if (r.zoneChanged) {
this.#log.warn(`device-monitor: camera ${row.id} time zone set to ${r.timeZone ?? "?"} (site offset ${offset})`);
}
if (r.synced) {
// A large jump is the 1970 power-cut signature — warn (persisted) so
// the reboot stays visible; a small correction is routine info.
@@ -249,6 +259,8 @@ export class DeviceMonitor {
/** Per-camera timestamp of the last clock-sync ATTEMPT (backstop pacing). */
readonly #clockSyncedAt = new Map<string, number>();
/** Per-camera site UTC offset ("+02:00") at the last attempt — a change (DST) re-syncs. */
readonly #clockSyncedOffset = new Map<string, string>();
/** Cache + emit a status, but only when it CHANGED (state or detail). */
#publish(id: string, next: DeviceStatusEvent): void {
+7 -1
View File
@@ -13,6 +13,7 @@ import {
} from "@parking/devices";
import { DEFAULT_VEHICLE_CATEGORY, reasonPayload } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import { pulseBarrier } from "./relay-pulse.js";
import type { DeviceInputEvent, LaneStatusEvent } from "./device-events.js";
import { getOccupancy } from "./occupancy.js";
import type { EventLog } from "./event-log.js";
@@ -386,7 +387,12 @@ export class EntryFlow {
const access = this.#buildAccess(resolved.controller);
let opened = false;
if (access) {
await access.pulseOpen(resolved.relay);
await pulseBarrier(this.#db, this.#logger, access, resolved, {
direction: "entry",
identity: ticketId,
source: opts.source,
...(opts.operator ? { operator: opts.operator } : {}),
});
opened = true;
} else this.#logger.warn(`entry signed for ${ticketId} but the entry relay won't build`);
+28 -7
View File
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db";
import { registry, type AccessControlDevice } from "@parking/devices";
import { pulseBarrier } from "./relay-pulse.js";
import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js";
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
import { snapshotAsync } from "./snapshot.js";
@@ -210,7 +211,12 @@ export class ExitFlow {
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
}
try {
await access.pulseOpen(resolved.relay);
await pulseBarrier(this.#db, this.#logger, access, resolved, {
direction: "exit",
identity: id,
source: "booth",
...(opts?.operator ? { operator: opts.operator } : {}),
});
} catch (err) {
await this.#openFailedAnomaly(id, `pulseOpen failed: ${(err as Error).message}`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
@@ -300,7 +306,7 @@ export class ExitFlow {
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
}
const r = await this.#pulseExit(resolved, `barrier re-open for ${id}`);
const r = await this.#pulseExit(resolved, id, operator, `barrier re-open for ${id}`);
if (r.opened) {
if (forgiven) this.#logger.warn(`FORGIVEN exit barrier open for ${id} by ${operator ?? "?"}: ${forgiven.note}`);
else this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
@@ -337,7 +343,7 @@ export class ExitFlow {
},
});
this.#fireExitSnapshot(ref);
const r = await this.#pulseExit(resolved, `forgiven open (no session) ${ref}`);
const r = await this.#pulseExit(resolved, ref, operator, `forgiven open (no session) ${ref}`);
if (r.opened) this.#logger.warn(`FORGIVEN exit barrier open with no session by ${operator}: ${note}`);
return r;
} finally {
@@ -347,7 +353,12 @@ export class ExitFlow {
/** Drive the exit relay for a human-intervention open; the exit/anomaly is already
* signed, so every failure is `ok: true, opened: false` + the reason to open by hand. */
async #pulseExit(resolved: ResolvedRelay | null, label: string): Promise<Extract<BoothReopenResult, { ok: true }>> {
async #pulseExit(
resolved: ResolvedRelay | null,
identity: string,
operator: string | undefined,
label: string,
): Promise<Extract<BoothReopenResult, { ok: true }>> {
if (!resolved) {
this.#logger.warn(`${label}: no exit relay configured`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
@@ -358,7 +369,12 @@ export class ExitFlow {
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
}
try {
await access.pulseOpen(resolved.relay);
await pulseBarrier(this.#db, this.#logger, access, resolved, {
direction: "exit",
identity,
source: "booth",
...(operator ? { operator } : {}),
});
} catch (err) {
this.#logger.error(`${label}: pulseOpen failed: ${(err as Error).message}`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
@@ -473,8 +489,13 @@ export class ExitFlow {
await this.#signExit(e.value, e.kind === "plate" ? "lpr" : "ticket");
const access = this.#buildAccess(resolved.controller);
if (access) await access.pulseOpen(resolved.relay);
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
if (access) {
await pulseBarrier(this.#db, this.#logger, access, resolved, {
direction: "exit",
identity: e.value,
source: e.kind === "plate" ? "lpr" : "ticket",
});
} else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
this.#fireExitSnapshot(e.value);
this.#closeSessionCache(e.value);
+86
View File
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { devices, deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db";
import { pulseBarrier } from "./relay-pulse.js";
import type { FastifyBaseLogger } from "fastify";
const silentLogger = { info() {}, warn() {}, error() {}, debug() {} } as unknown as FastifyBaseLogger;
// Every barrier pulse — success or failure — must leave an UNSIGNED device_events row
// (kind "relay") naming the relay, the direction, the identity and who asked, so a
// "did the server open the barrier?" question is answerable from telemetry alone
// (park-2, 2026-10-09). A failure is recorded AND re-thrown (each flow keeps its own
// anomaly handling).
let db: Db;
let close: () => void;
let controller: DeviceRow;
beforeEach(() => {
const t = createTestDb();
db = t.db;
close = t.close;
db.insert(devices)
.values({
id: "ctl-1",
category: "access",
driverId: "stub-access",
config: { relays: [{ relay: 2, direction: "exit" }] },
enabled: true,
})
.run();
controller = db.select().from(devices).get()!;
});
afterEach(() => close());
function relayRows() {
return db
.select()
.from(deviceEventsTable)
.all()
.filter((r) => r.kind === "relay")
.map((r) => ({ deviceId: r.deviceId, category: r.category, detail: r.detail as Record<string, unknown> }));
}
describe("pulseBarrier", () => {
it("pulses the relay and records a successful relay event with the context", async () => {
const fired: number[] = [];
const access = { pulseOpen: async (door: number) => void fired.push(door) };
await pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, {
direction: "exit",
identity: "forgiven:abc",
source: "booth",
operator: "admin",
});
expect(fired).toEqual([2]);
const rows = relayRows();
expect(rows).toHaveLength(1);
expect(rows[0].deviceId).toBe("ctl-1");
expect(rows[0].category).toBe("access");
expect(rows[0].detail).toMatchObject({
driverId: "stub-access",
relay: 2,
direction: "exit",
identity: "forgiven:abc",
source: "booth",
operator: "admin",
ok: true,
});
expect(typeof rows[0].detail.tookMs).toBe("number");
});
it("records a failed pulse with the error, then re-throws it", async () => {
const access = {
pulseOpen: async () => {
throw new Error("timeout");
},
};
await expect(
pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, { direction: "exit", identity: "T1", source: "ticket" }),
).rejects.toThrow("timeout");
const rows = relayRows();
expect(rows).toHaveLength(1);
expect(rows[0].detail).toMatchObject({ relay: 2, identity: "T1", source: "ticket", ok: false, error: "timeout" });
expect(rows[0].detail.operator).toBeUndefined();
});
});
+84
View File
@@ -0,0 +1,84 @@
import { randomUUID } from "node:crypto";
import type { FastifyBaseLogger } from "fastify";
import { deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db";
import type { AccessControlDevice } from "@parking/devices";
import type { Direction } from "./device-resolve.js";
// The ONE place a barrier relay is pulsed from business logic. Every pulse is logged at
// info (relay, controller, who asked and for which identity) and echoed into the UNSIGNED
// device_events stream (kind "relay") whether it succeeded or failed — so "did the server
// open the barrier at 15:50?" is answerable from `docker logs` or the telemetry table
// without reading the ledger. The signed ledger stays the authority on WHY (the
// vehicle_entry/exit/anomaly is appended BEFORE the pulse); this is the device-side echo
// (wiki/concepts/device-events.md). Failures are recorded, then re-thrown so each flow keeps
// its own anomaly/result handling. park-2 2026-10-09: a "barrier opened by itself" claim
// took ledger + snapshots to settle because pulses were only logged when they failed.
export interface PulseContext {
/** The barrier's direction (the relay's configured event). */
readonly direction: Direction;
/** The session/ticket/card/ref the open is for (matches the signed event's identity). */
readonly identity: string;
/** Who asked: ticket | manual | booth | lpr | subscription | relay-test … (free-form). */
readonly source: string;
readonly operator?: string;
}
export async function pulseBarrier(
db: Db,
logger: FastifyBaseLogger,
access: Pick<AccessControlDevice, "pulseOpen">,
target: { readonly controller: DeviceRow; readonly relay: number },
ctx: PulseContext,
): Promise<void> {
const { controller, relay } = target;
const who = ctx.operator ? ` by ${ctx.operator}` : "";
logger.info(
`relay pulse: ${ctx.direction} relay ${relay} on ${controller.driverId} ${controller.id} ← ${ctx.source} ${ctx.identity}${who}`,
);
const startedAt = Date.now();
const firedAt = new Date(startedAt).toISOString();
try {
await access.pulseOpen(relay);
record(db, logger, controller, relay, ctx, firedAt, { ok: true, tookMs: Date.now() - startedAt });
} catch (err) {
const error = (err as Error).message;
logger.error(`relay pulse FAILED: ${ctx.direction} relay ${relay} on ${controller.id} for ${ctx.identity}: ${error}`);
record(db, logger, controller, relay, ctx, firedAt, { ok: false, error, tookMs: Date.now() - startedAt });
throw err;
}
}
function record(
db: Db,
logger: FastifyBaseLogger,
controller: DeviceRow,
relay: number,
ctx: PulseContext,
firedAt: string,
outcome: { ok: boolean; error?: string; tookMs: number },
): void {
// Telemetry must never block or fail the open — swallow insert errors (logged).
try {
db.insert(deviceEventsTable)
.values({
id: randomUUID(),
deviceId: controller.id,
category: "access",
kind: "relay",
detail: {
driverId: controller.driverId,
relay,
direction: ctx.direction,
identity: ctx.identity,
source: ctx.source,
...(ctx.operator ? { operator: ctx.operator } : {}),
...outcome,
},
occurredAt: firedAt,
})
.run();
} catch (err) {
logger.error(`relay pulse telemetry insert failed: ${(err as Error).message}`);
}
}
+9 -2
View File
@@ -1,6 +1,7 @@
import { randomBytes, randomUUID } from "node:crypto";
import type { FastifyInstance } from "fastify";
import { eq, devices, setupState, type Db } from "@parking/db";
import { pulseBarrier } from "../relay-pulse.js";
import {
hasPreconditions,
hasPushConfig,
@@ -507,7 +508,7 @@ export async function setupRoutes(
return reply.code(400).send({ error: `device ${id} is not a controller` });
}
const cfg = (row.config ?? {}) as Record<string, unknown>;
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number }[]) : [];
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number; direction?: string }[]) : [];
if (!relays.some((r) => r.relay === relay)) {
return reply.code(400).send({ error: `controller ${id} has no relay ${relay}` });
}
@@ -545,8 +546,14 @@ export async function setupRoutes(
});
const startedAt = Date.now();
const relayDir = relays.find((r) => r.relay === relay)?.direction;
try {
await device.pulseOpen(relay);
await pulseBarrier(db, req.log, device, { controller: row, relay }, {
direction: relayDir === "entry" || relayDir === "exit" ? relayDir : "both",
identity: `relay-test:${id}:${relay}`,
source: "relay-test",
operator,
});
} catch (err) {
// The failure we're testing for (relay unreachable, wrong password). The open is
// already signed; report the pulse failure, don't 500.
+4 -2
View File
@@ -12,6 +12,7 @@ import {
import { registry, type AccessControlDevice } from "@parking/devices";
import { reasonPayload, type PlanTimeframes, type ReasonCode } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import { pulseBarrier } from "./relay-pulse.js";
import { printWindowChargeNotice } from "./booth-print.js";
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
import type { EventLog } from "./event-log.js";
@@ -410,8 +411,9 @@ export class SubscriptionFlow {
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
const access = this.#buildAccess(resolved.controller);
if (access) await access.pulseOpen(resolved.relay);
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
if (access) {
await pulseBarrier(this.#db, this.#logger, access, resolved, { direction: dir, identity: carKey, source: "subscription" });
} else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
this.#fireSnapshot(dir, carKey);
+76 -6
View File
@@ -153,7 +153,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
const timeXml = (localTime: string) =>
reply(
200,
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00DST01:00:00</timeZone></Time>`,
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00</timeZone></Time>`,
);
const HOST_NOW = "2026-07-07T12:00:00+02:00";
@@ -166,11 +166,11 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
it("in-sync camera: reads, does NOT set", async () => {
digestRequest.mockResolvedValueOnce(timeXml("2026-07-07T12:00:10+02:00"));
const r = await cam().syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: 10, synced: false });
expect(r).toEqual({ driftSeconds: 10, synced: false, zoneChanged: false, timeZone: "CST-2:00:00" });
expect(digestRequest).toHaveBeenCalledTimes(1); // GET only
});
it("1970 camera: PUTs manual time with the host instant, echoing the camera's timeZone", async () => {
it("1970 camera: PUTs manual time with the host instant and the site's fixed-offset zone", async () => {
digestRequest
.mockResolvedValueOnce(timeXml("1970-01-01T03:12:44+01:00"))
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
@@ -182,7 +182,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
expect(put.path).toBe("/ISAPI/System/time");
expect(put.body).toContain("<timeMode>manual</timeMode>");
expect(put.body).toContain(`<localTime>${HOST_NOW}</localTime>`);
expect(put.body).toContain("<timeZone>CST-2:00:00DST01:00:00</timeZone>"); // echoed, never invented
expect(put.body).toContain("<timeZone>CST-2:00:00</timeZone>"); // the host's current offset, never the camera's DST rule
});
it("unparseable camera time = infinite drift → syncs", async () => {
@@ -190,7 +190,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
.mockResolvedValueOnce(reply(200, "<Time><localTime>garbage</localTime></Time>"))
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
const r = await cam().syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: null, synced: true });
expect(r).toMatchObject({ driftSeconds: null, synced: true });
});
it("a failed set surfaces as an error (monitor logs it, backstop retries)", async () => {
@@ -277,7 +277,7 @@ describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wa
.mockResolvedValueOnce(reply(200, "Error\r\nBad Request!"))
.mockResolvedValueOnce(reply(200, "OK"));
const r = await (await cam()).syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: null, synced: true });
expect(r).toMatchObject({ driftSeconds: null, synced: true });
});
it("a 200 whose body is not OK is still a failed set (Dahua's 'Error' convention)", async () => {
@@ -294,3 +294,73 @@ describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wa
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 401");
});
});
// --- Hikvision clock sync: the zone is the host's FIXED current offset -------------
// park-2 2026-10-09: both cameras sat on the factory CST-8 (Beijing) — instant right,
// OSD six hours off — and this firmware ignores the DST rule in a POSIX zone string. So
// the sync rewrites the zone to the site's current fixed offset and re-sends the clock
// with it; a camera already on the right zone with small drift is left alone.
const { hikvisionFixedZone } = await import("./camera.js");
function timeXml(localTime: string, timeZone: string) {
return (
`<?xml version="1.0" encoding="UTF-8"?><Time version="2.0"><timeMode>manual</timeMode>` +
`<localTime>${localTime}</localTime><timeZone>${timeZone}</timeZone></Time>`
);
}
function xmlReply(status: number, body: string): DigestGetResult {
return { status, contentType: "application/xml", body: Buffer.from(body) };
}
function putCalls() {
return digestRequest.mock.calls
.map((c) => c[0] as { method: string; path: string; body?: string })
.filter((c) => c.method === "PUT");
}
describe("hikvisionFixedZone", () => {
it("inverts the sign the POSIX way and keeps minutes", () => {
expect(hikvisionFixedZone("2026-10-09T19:01:08+02:00")).toBe("CST-2:00:00");
expect(hikvisionFixedZone("2026-12-09T18:01:08+01:00")).toBe("CST-1:00:00");
expect(hikvisionFixedZone("2026-10-09T09:01:08-05:30")).toBe("CST+5:30:00");
expect(hikvisionFixedZone("2026-10-09T17:01:08+00:00")).toBe("CST0:00:00");
});
it("refuses a host time without an offset", () => {
expect(() => hikvisionFixedZone("2026-10-09T19:01:08")).toThrow(/utc offset/);
});
});
describe("hikvision syncClock — zone", () => {
it("rewrites a factory CST-8 zone even when the instant is right", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean; timeZone?: string; driftSeconds: number | null }> };
// Same instant as the host (17:01:08Z), shown in Beijing time.
digestRequest
.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-10T01:01:08+08:00", "CST-8:00:00")))
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: true, zoneChanged: true, timeZone: "CST-2:00:00", driftSeconds: 0 });
const puts = putCalls();
expect(puts).toHaveLength(1);
expect(puts[0].path).toBe("/ISAPI/System/time");
expect(puts[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
expect(puts[0].body).toContain("<localTime>2026-10-09T19:01:08+02:00</localTime>");
});
it("leaves a camera on the right zone with small drift alone", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
digestRequest.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-09T19:01:20+02:00", "CST-2:00:00")));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: false, zoneChanged: false });
expect(putCalls()).toHaveLength(0);
});
it("re-sets the clock (same zone) when drift exceeds the threshold", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
digestRequest
.mockResolvedValueOnce(xmlReply(200, timeXml("1970-01-01T08:00:00+02:00", "CST-2:00:00")))
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: true, zoneChanged: false });
expect(putCalls()[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
});
});
+41 -11
View File
@@ -189,15 +189,40 @@ class HttpCamera implements CameraDevice {
// ANPR pushes. So the host (the site's time authority — offline-first, no NTP
// dependency) re-syncs the camera over the same Digest-auth ISAPI used for
// snapshots. The device monitor calls this at the offline→ready edge (the
// power-restored moment) + a daily backstop. See wiki/entities/lpr-camera.md.
// power-restored moment), a daily backstop, and whenever the site's UTC offset
// changes (DST). See wiki/entities/lpr-camera.md.
//
// TIME ZONE: the OSD shows the camera's LOCAL time = instant + its `timeZone` setting.
// park-2 (2026-10-09) ran both cameras on the factory CST-8 (Beijing): the instant was
// right, the burned-in time six hours off, and a correct-instant sync never touched it.
// This firmware (DS-2CD1047G3H) also ignores the DST rule in a POSIX-style zone string
// ("CET-1:00:00DST01:00:00,M3.5.0/02:00:00,M10.5.0/03:00:00" was accepted, echoed back,
// and NOT applied — OSD stayed on +01:00 in October). So the host owns DST too: the zone
// is written as a FIXED offset equal to the site's CURRENT offset ("CST-2:00:00" in summer,
// "CST-1:00:00" in winter — Hikvision's inverted POSIX sign) and rewritten at the next
// sync after the site's offset changes. The abbreviation is cosmetic (the camera renames
// whatever we send to "CST").
/** The Hikvision `timeZone` string for a FIXED offset equal to `localIso`'s UTC offset:
* "+02:00" → "CST-2:00:00", "-05:30" → "CST+5:30:00", "+00:00" → "CST0:00:00". */
export function hikvisionFixedZone(localIso: string): string {
const m = localIso.match(/([+-])(\d{2}):(\d{2})$/);
if (!m) throw new Error(`syncClock: host time has no utc offset: ${localIso}`);
const hours = Number(m[2]);
const minutes = m[3];
if (hours === 0 && minutes === "00") return "CST0:00:00";
// POSIX (and Hikvision) sign is inverted: east of UTC is negative.
const sign = m[1] === "+" ? "-" : "+";
return `CST${sign}${hours}:${minutes}:00`;
}
class HikvisionCamera extends HttpCamera {
/**
* Read the camera clock; when it drifts more than `maxDriftSec` from `localIso`
* (the site's wall-clock now, WITH utc offset), set it via
* PUT /ISAPI/System/time. The camera's own `timeZone` string is echoed back
* verbatim — we correct the CLOCK, never fight the tz/DST config; `localIso`'s
* explicit offset makes the instant unambiguous regardless of that config.
* Read the camera clock + zone. Rewrite the zone when it is not the site's current
* fixed offset (see above); otherwise set the clock only when it drifts more than
* `maxDriftSec` from `localIso` (the site's wall-clock now, WITH utc offset). The PUT
* always carries both: `localIso`'s explicit offset makes the instant unambiguous
* regardless of the zone the camera applies to it.
*/
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
const read = await this.deviceRequest("GET", "/ISAPI/System/time");
@@ -207,6 +232,8 @@ class HikvisionCamera extends HttpCamera {
const xml = read.body.toString("utf8");
const cameraTime = xml.match(/<localTime>([^<]+)<\/localTime>/)?.[1]?.trim() ?? null;
const timeZone = xml.match(/<timeZone>([^<]+)<\/timeZone>/)?.[1]?.trim() ?? "";
const wantZone = hikvisionFixedZone(localIso);
const zoneChanged = timeZone !== wantZone;
// Drift: parse both sides as instants. A camera reply without a UTC offset (or
// otherwise unparseable) can't be trusted → treat as infinite drift and sync.
@@ -215,21 +242,24 @@ class HikvisionCamera extends HttpCamera {
const driftSeconds = Number.isFinite(cameraMs)
? Math.round(Math.abs(hostMs - cameraMs) / 1000)
: null;
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false };
if (!zoneChanged && driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false, zoneChanged: false, timeZone };
}
const body =
`<?xml version="1.0" encoding="UTF-8"?>` +
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
(timeZone ? `<timeZone>${timeZone}</timeZone>` : "") +
`<timeZone>${wantZone}</timeZone>` +
`</Time>`;
const put = await this.deviceRequest("PUT", "/ISAPI/System/time", body);
if (put.status !== 200) {
throw new Error(`clock set failed: HTTP ${put.status}`);
}
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
return { driftSeconds, synced: true };
stubLog(
this.driverId,
`clock synced (was ${driftSeconds ?? "unparseable"}s off${zoneChanged ? `; zone ${timeZone || "unset"} → ${wantZone}` : ""})`,
);
return { driftSeconds, synced: true, zoneChanged, timeZone: wantZone };
}
}
+7 -1
View File
@@ -203,8 +203,14 @@ export interface ClockSyncResult {
/** Camera-vs-host drift in whole seconds at check time; null = the camera's
* reply was unparseable (treated as infinite drift → sync). */
readonly driftSeconds: number | null;
/** True when the camera clock was actually set (drift exceeded the threshold). */
/** True when the camera clock was actually set (drift exceeded the threshold, or the
* zone was rewritten — the clock is always re-sent with a zone change). */
readonly synced: boolean;
/** True when the camera's time-ZONE setting was rewritten to the site's current UTC
* offset (Hikvision only; see HikvisionCamera.syncClock). */
readonly zoneChanged?: boolean;
/** The camera's zone string after the call (Hikvision only), for the log line. */
readonly timeZone?: string;
}
/** Optional capability: a device whose clock the HOST can read + set. Hikvision
+8 -2
View File
@@ -14,8 +14,14 @@ diagnostics, and live booth status — **not** anti-fraud.
## What lands here
- **Relays/barriers:** relay fired/released, pulseOpen issued (the *device-side* echo; the
authoritative `barrier_open_command` is a signed ledger event).
- **Relays/barriers:** every `pulseOpen` issued from business logic — kind `relay`, detail
`{driverId, relay, direction, identity, source, operator?, ok, error?, tookMs}` — success **and**
failure, written by `apps/server/src/relay-pulse.ts` (`pulseBarrier`, the ONE pulse path: entry
button/operator mint, reader + booth exits, subscription opens, manual exits, the setup relay
test). Also an info log line `relay pulse: exit relay 2 on dingtian <id> ← booth <identity> by
<operator>`. The *device-side* echo; the authoritative record of WHY is the signed ledger event
appended before the pulse. Built 2026-10-09 after a park-2 "barrier opened by itself" claim took
ledger + snapshots to settle because pulses were only logged when they *failed*.
- **Printers:** paper-out / near-end / cover-open / cutter / offline (already polled —
[[printer-status-monitoring]]).
- **Cameras:** reachable/offline, snapshot success/failure ([[lpr-camera]]).
+53 -12
View File
@@ -2,7 +2,7 @@
type: concept
tags: [parking, camera, anpr, subscription, lane, vision]
sources: []
updated: 2026-06-22
updated: 2026-10-11
status: open
---
@@ -32,6 +32,12 @@ here is built on that, and on the camera's hard limits.
event log): while a car MOVES, `active` repeats ~1–3 s apart; while it sits MOTIONLESS, gaps stretch
to ~15–25 s. Crucially the camera has **~no dwell lag** — it goes silent within ~1 s of the car
leaving (last event 16:15:17 vs car-left ~16:15:30).
- **Every push is an independent event — nothing is "held".** Re-confirmed on park-2 (2026-10-11,
2780 pushes over one day, both cameras): every push is `VMD`/`active` with `activePostCount=1`;
median gap 1.2 s while a car moves; never an `inactive`. So the camera does NOT open an event and
release it 30 s later — a second car entering while the first is still there produces its own
pushes. The 30 s figures in this system are OURS (`LANE_BUSY_TTL_MS`, `ANPR_POLL_MAX_MS`). Any
blindness to a second car is in the bridge, not the camera — see the 2026-10-11 block below.
## 1. Lane busy/free (BUILT)
@@ -53,16 +59,16 @@ nothing** (never blocks a ticket or opens a barrier; the standing rule).
**As built:** `hikvision-alarm.ts`, on a `vehicle`/non-`inactive` push from an `anpr`-opted-in
camera, hands the deviceId to `AnprBridge.onVehicleDetected()` (fire-and-forget, never awaited on the
camera's 200). The bridge: debounce (camera-level, pre-snapshot) → `captureSnapshot` (fresh pull, via
the reused `snapshot.ts buildCamera`) → `vision.analyze` → entry confidence floor
(`VISION_ENTRY_MIN_CONFIDENCE`, 0.85) → normalize plate → **`subscriptionFlow.match()` (match BEFORE
emit)** → if a subscriber, `deviceEvents.emitRead({kind:"plate"})`; if not, record an advisory
`anpr-skip` device_event and stop. The existing `onRead → ReadDispatcher → SubscriptionFlow.run()`
camera's 200). The bridge: `captureSnapshot` (fresh pull, via the reused `snapshot.ts buildCamera`) →
`vision.analyze` → entry confidence floor (`VISION_ENTRY_MIN_CONFIDENCE`, 0.85) → normalize plate →
**`subscriptionFlow.match()` (match BEFORE emit)** → if a subscriber, debounce **per plate** →
`deviceEvents.emitRead({kind:"plate"})`; if not, record an advisory `anpr-skip` device_event (once per
plate per loop) and go on. The existing `onRead → ReadDispatcher → SubscriptionFlow.run()`
then does the gated entry/exit + barrier open. Constructed in `server.ts` (the flows were reordered
above the hik-alarm registration so the bridge can take `subscriptionFlow`). Fail-soft throughout —
any snapshot/vision error degrades to the subscriber's card/QR, never throws into the push handler.
Two new env knobs: `VISION_ENTRY_MIN_CONFIDENCE` (0.85), `ANPR_DEBOUNCE_MS` (12_000). Covered by
`anpr-entry.test.ts` + `hikvision-alarm.test.ts` wiring.
Two new env knobs: `VISION_ENTRY_MIN_CONFIDENCE` (0.85), `ANPR_DEBOUNCE_MS` (12_000, keyed by plate
since 2026-10-11). Covered by `anpr-entry.test.ts` + `hikvision-alarm.test.ts` wiring.
**Toggles — two levels (the auto-open is optional).** ANPR auto entry/exit can be turned off without
losing plate recognition:
@@ -83,9 +89,10 @@ losing plate recognition:
> low-confidence misread (observed live on the exit lane: `'111'`@0.20, `'AE18671'`@0.19 …, while
> the manual `test-anpr` on the SAME stopped car read `AA890XX`@1.00). The car then STOPS at the
> barrier waiting for it to open — the stationary, well-framed moment the test reads at ~100%. So
> the bridge now **pulls a FRESH frame every `ANPR_POLL_MS` (1000) and re-runs ANPR until one clears
> the floor, or `ANPR_POLL_WINDOW_MS` (8000) elapses** (car drove off / non-subscriber → give up
> cleanly). One loop per camera (`#polling` set) so the ~1Hz alarm re-fires JOIN it, not spawn N;
> the bridge now **pulls a FRESH frame every `ANPR_POLL_MS` (was 1000; 0 = back-to-back since
> 2026-10-11) and re-runs ANPR until one clears the floor, or `ANPR_POLL_WINDOW_MS` (8000) elapses**
> (car drove off / non-subscriber → give up cleanly). *(Superseded in part by the 2026-10-11 block
> below: the loop no longer stops at the first confident plate.)* One loop per camera (`#polling` set) so the ~1Hz alarm re-fires JOIN it, not spawn N;
> each tick is a fresh `camera.captureSnapshot` (NOT `captureSnapshotShared`, whose TTL would
> re-serve the same bad frame). VERIFIED on hardware: 7 garbage approach frames → `AA890XX`@0.999
> at the barrier → signed `vehicle_exit`. This is what made subscriber **auto-exit** actually work
@@ -106,6 +113,39 @@ losing plate recognition:
> *now*, not the car that started it. (Knobs: `ANPR_POLL_MS`, `ANPR_POLL_WINDOW_MS`,
> `ANPR_POLL_MAX_MS`.)
> **READ EVERY FRAME, SETTLE EVERY PLATE, DEBOUNCE PER PLATE (2026-10-11).** Three defects in the
> loop above, found by measuring park-2 (i5-9500, two `DS-2CD1043G2-LIU`, 48 h of logs):
>
> 1. **The fixed 1 s sleep was the bottleneck, not the hardware.** A main-stream pull is ~0.1 s and a
> `/analyze` ~0.25 s on the booth, so each attempt cost ~0.35 s of work plus a 1 s sleep: one frame
> per ~1.35 s while the host CPU sat under 3 %. Readable moments (a stop at the barrier, a gap in
> headlight glare) are short and were missed between ticks. **Now:** pulls are back-to-back
> (`ANPR_POLL_MS` is a *floor*, default 0) → ~3 frames/s per camera, strictly serial. NOT parallel
> threads: the camera's picture endpoint is single-threaded (4 concurrent GETs → two HTTP 503,
> measured), and the vision service runs inference synchronously on its event loop (4 concurrent
> `/analyze` → each 1.03 s, fully serialised). Two active cameras still queue behind each other in
> the recognizer; making `/analyze` non-blocking (thread pool / 2 workers) is the next step if that
> shows up. Of 557 give-ups in 48 h, 178 had seen a plate below the floor — the ceiling of what
> faster sampling can rescue (~6 % of detections); 379 never saw a plate in any frame.
> 2. **The loop stopped at the first confident plate, then a CAMERA-level debounce dropped every
> push for 12 s.** A tailgater in that window was never looked at: 40 of 57 plate-driven opens had
> a push land 4–12 s after the read. **Now:** the loop runs while pushes keep sliding the deadline
> (or to the hard cap); each confident plate is *settled once per loop* (emitted / `anpr-skip` /
> declined), and the loop goes on — a second car behind the first is read by the same loop. The
> debounce is keyed `deviceId:plate` only; nothing is keyed by camera. The fleet-sub correctness
> argument for the debounce holds unchanged: the same car is the same plate.
> 3. **Credential race, per subscriber.** The mid-poll card/QR guard used to abort the whole loop on
> the first sighted subscriber. It is now per subscription: open-count baselined at first sighting
> of each plate, checked when that plate settles; a moved count declines that plate only.
>
> Side effects: the PASS sample (for the [[vision-review-outbox]]) is one per *plated car* in the loop
> plus one for a plateless loop — before, one per loop however many cars. `ANPR_POLL_WINDOW_MS=0` is
> now honoured (one frame per push; it used to fall back to 8 s silently). Logs: a below-floor plate
> text logs at info once per loop then debug; every loop ends with one `loop done — N frame(s) in M
> ms, P plate(s), E emitted` line. Still open from the same measurement: 59 % of give-ups ended after
> 7–8 frames because the camera went quiet (a motionless car stops re-firing) — extending the window
> when a weak plate has been seen is a candidate follow-up. Tests: `anpr-entry.test.ts` (20).
The goal (narrowed deliberately — see Rejected below): **a subscriber's plate, read by the lane
camera, admits them through the same gated flow a QR/card scan uses.** Scope was cut to subscribers
ONLY — no queue segmentation, no per-car tracking, no make/model, no ticket-button gating.
@@ -137,7 +177,8 @@ snapshot → `vision.analyze` → if a plate clears a **HIGH** confidence floor
present; emitting a read every second would drive REPEAT entries (a fleet sub opens a 2nd
occurrence; a single-car sub spams "already inside") or, on an exit camera, repeat exits
(`sub.refused.noSession` after the first, and FIFO could phantom-close another occurrence). So the
same plate on the same camera within ~10–15 s = ONE credential presentation.
same plate on the same camera within ~10–15 s = ONE credential presentation. (Keyed by PLATE —
the camera-level stamp that also existed until 2026-10-11 made the lane blind to the next car.)
- NB: a direction-bound camera does NOT flip entry↔exit on repeat reads (the barrier's direction
fixes the verb), so the earlier "flip-flop" fear was wrong — but repeat-same-direction is still
bad. Debounce stands.
+21 -7
View File
@@ -231,14 +231,28 @@ Built: the HOST is the site's time authority (offline-first — no NTP infra dep
device monitor re-syncs each Hikvision camera over the same Digest-auth ISAPI used for snapshots:
- **Trigger:** the camera's **offline → ready transition** (exactly the power-restored moment) +
a **24h backstop**; the attempt timestamp is stamped BEFORE the async call, so a failing camera
retries at backstop cadence, never every 8s poll.
- **Mechanics** (`HikvisionCamera.syncClock`): `GET /ISAPI/System/time`, parse `localTime`; drift ≤
60s → leave alone. Beyond that → `PUT /ISAPI/System/time` with `timeMode=manual`, the site's
a **24h backstop** + **the site's UTC-offset edge** (a DST switch, checked every poll from
`localIsoWithOffset(siteTz)`); the attempt timestamp is stamped BEFORE the async call, so a
failing camera retries at backstop cadence, never every 8s poll.
- **Mechanics** (`HikvisionCamera.syncClock`): `GET /ISAPI/System/time`, parse `localTime` and
`timeZone`. The wanted zone is the site's **current offset as a fixed zone**
(`hikvisionFixedZone`: `+02:00` → `CST-2:00:00`, `+01:00` → `CST-1:00:00`; Hikvision's inverted
POSIX sign; the abbreviation is cosmetic — the camera renames whatever is sent to `CST`). Zone
differs → `PUT /ISAPI/System/time` with `timeMode=manual`, the wanted zone, and the site's
wall-clock now WITH explicit utc offset (`localIsoWithOffset(siteTz)`, e.g.
`2026-07-07T15:30:22+02:00` — the offset makes the instant unambiguous), and the camera's own
`timeZone` string **echoed back verbatim** (we correct the clock, never fight its tz/DST config).
An unparseable camera reply counts as infinite drift → sync.
`2026-07-07T15:30:22+02:00` — the offset makes the instant unambiguous whatever zone the
camera applies). Zone right and drift ≤ 60s → leave alone; drift beyond → the same PUT. An
unparseable camera reply counts as infinite drift → sync. The result carries `zoneChanged` +
`timeZone`; the monitor logs a zone rewrite at **warn**.
- **Why the host owns the zone (2026-10-09, park-2):** both cameras ran the **factory `CST-8:00:00`
(Beijing)** — the instant was right, so the drift check never fired, while the OSD burned into
every snapshot read **six hours ahead** of the booth (the operator's "barrier opened by itself"
claim was argued against camera footage stamped 21:45 for a 15:45 event). The earlier design
"echo the camera's zone verbatim" could never fix that. And this firmware (DS-2CD1047G3H)
**ignores the DST rule in a POSIX zone string**: `CET-1:00:00DST01:00:00,M3.5.0/02:00:00,M10.5.0/03:00:00`
was accepted and echoed back, but `localTime` and the OSD stayed on +01:00 in October. Hence a
fixed offset rewritten by the host at each DST edge, not a camera-side rule. Applied by hand to
both park-2 cameras the same day (`PUT` with `CST-2:00:00`); the deploy keeps it so.
- **Visibility:** a sync after a big jump (>1h — the power-cut signature) logs at **warn**
(persisted to app_logs); small corrections log info. Failures log warn.
- **Scope:** Hikvision only (`isClockSyncable` capability guard); the Dahua driver's CGI has no
+32
View File
@@ -3496,3 +3496,35 @@ prompt: Cancel aborts, empty proceeds; en/sq texts say optional. [[forgiven-exit
User trimmed the Albanian copy ("Too much fal, falur, falje") and asked for the same in
English: buttons, dialog, results, live-feed reasons, shift figures, the printed Z line and the
signed English fallback now say manual exit; identifiers unchanged. [[forgiven-exit]] §Wording.
## [2026-10-09] incident | park-2 "barrier opened by itself" — it was a manual exit on an empty lane
Operator claimed the exit barrier opened for an unknown car at ~15:50. Ledger + snapshots: the
only server-commanded open was a Dalje Manuale at 15:45:19 (admin account, exit lane empty in
its snapshot); the 15:50 van got no command, no plate, no card. CCTV confirmed. 18 manual exits
that day, all as `admin`, no reason — prepaid cards get "no open session" at the exit readers.
Exposed: pulses logged only on failure; no loop/arm input on the exit side; camera OSD +6 h.
## [2026-10-09] built | Every relay pulse logged + echoed to device_events (kind `relay`)
`pulseBarrier` (apps/server/src/relay-pulse.ts) is now the one pulse path for all six callers;
info line per pulse with relay/controller/direction/identity/source/operator, and a device_events
row for success and failure. [[device-events]] updated.
## [2026-10-09] built | Hikvision clock sync now owns the time ZONE (fixed offset, host-rewritten at DST)
park-2 cameras sat on factory CST-8 (instant right, OSD six hours off, so the drift-only sync
never fired); the G3H firmware ignores the DST rule in a POSIX zone string. `syncClock` writes
the site's current offset as a fixed zone; the monitor re-syncs at the site's UTC-offset edge.
Both park-2 cameras set by hand the same day. [[lpr-camera]] §Clock sync.
## [2026-10-11] built | ANPR bridge reads every frame, settles every plate, debounces per plate
Measured park-2 (i5-9500): pull ~0.1 s, analyze ~0.25 s, host idle — the loop's fixed 1 s sleep was
the limit (1 frame/1.35 s). The camera is single-threaded (4 parallel GETs → 2×503) and `/analyze`
serialises (4 parallel → 1.03 s each), so no threads: back-to-back serial pulls (~3 fps/camera,
`ANPR_POLL_MS` now a floor, default 0). The loop no longer breaks on the first confident plate and the
12 s CAMERA-level debounce is gone (40 of 57 plate opens had a push dropped in that blind window) —
each plate is settled once per loop, debounce keyed `deviceId:plate`, credential-race guard per
subscriber, pass sample per plated car. Also re-confirmed the camera event model: 2780 pushes, all
`activePostCount=1`, median 1.2 s apart, never `inactive` — nothing is held for 30 s on the camera
side. `anpr-entry.ts`, `anpr-entry.test.ts` (20), [[lane-presence-and-anpr-entry]] updated.