diff --git a/apps/server/src/read-dispatch-debounce.test.ts b/apps/server/src/read-dispatch-debounce.test.ts new file mode 100644 index 0000000..4ae3a6c --- /dev/null +++ b/apps/server/src/read-dispatch-debounce.test.ts @@ -0,0 +1,119 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { devices, deviceEvents as deviceEventsTable, ledgerEvents, subscriptionCredentials, subscriptions, type Db } from "@parking/db"; +import { createTestDb } from "@parking/db/testing"; +import { ReadDispatcher, readDebounceMs, DEFAULT_READ_DEBOUNCE_MS } from "./read-dispatch.js"; +import { ExitFlow } from "./exit-flow.js"; +import { SubscriptionFlow } from "./subscription-flow.js"; +import type { DeviceReadEvent } from "./device-events.js"; +import { makeLog, silentLogger } from "./test-helpers.js"; + +// SAME-CODE DEBOUNCE at the dispatcher (2026-10-11): the same value from the same reader +// inside the reader's `debounceMs` window is ONE presentation — the first verdict is +// replayed, nothing is signed twice, the repeat lands in device_events as telemetry. +// Born at park-2: the DT-008 reported one card twice 560 ms apart; the permit flow opened +// two sessions and pulsed the barrier twice. Every lane, every credential kind. + +let db: Db; + +function seed(readerCfg: Record, direction: "entry" | "exit" = "exit"): ReadDispatcher { + ({ db } = createTestDb()); + db.insert(devices).values({ + id: "ctl", + category: "access", + driverId: "stub-access", + config: { relays: [{ relay: 1, direction }] }, + enabled: true, + }).run(); + db.insert(devices).values({ + id: "reader", + category: "reader", + driverId: "dingtian-qr-reader", + config: { serial: "H05MA5B0", controllerId: "ctl", relay: 1, ...readerCfg }, + enabled: true, + }).run(); + const log = makeLog(db); + return new ReadDispatcher(db, new ExitFlow(db, log, silentLogger()), new SubscriptionFlow(db, log, silentLogger()), silentLogger()); +} + +function read(value: string, opts: { kind?: DeviceReadEvent["kind"]; channel?: DeviceReadEvent["channel"] } = {}): DeviceReadEvent { + return { + driverId: "dingtian-qr-reader", + deviceId: "reader", + value, + kind: opts.kind ?? "qr", + ...(opts.channel ? { channel: opts.channel } : {}), + at: new Date().toISOString(), + }; +} + +const ledger = () => db.select().from(ledgerEvents).all(); +const debounced = () => + db.select().from(deviceEventsTable).all() + .map((r) => r.detail as { debounced?: boolean; value?: string; sinceMs?: number; replayedAccepted?: boolean }) + .filter((d) => d.debounced === true); + +describe("readDebounceMs", () => { + it("defaults to 5000 when the reader has no value; honours numbers and form strings; 0 = off", () => { + expect(readDebounceMs({})).toBe(DEFAULT_READ_DEBOUNCE_MS); + expect(readDebounceMs({ debounceMs: "" })).toBe(5000); + expect(readDebounceMs({ debounceMs: 2500 })).toBe(2500); + expect(readDebounceMs({ debounceMs: "800" })).toBe(800); + expect(readDebounceMs({ debounceMs: 0 })).toBe(0); + expect(readDebounceMs({ debounceMs: "nope" })).toBe(0); + }); +}); + +describe("read-dispatch same-code debounce", () => { + it("a repeat of the same unknown ticket at exit signs ONE refusal, replays the verdict, logs telemetry", async () => { + const d = seed({}); // default window + const first = await d.dispatch(read("00000000000")); // Luhn-valid, no session → refused + signed + const second = await d.dispatch(read("00000000000")); + expect(ledger()).toHaveLength(1); // not a second red row for the same scan + expect(second).toEqual(first); // same verdict → same beep + expect(debounced()).toHaveLength(1); + expect(debounced()[0]).toMatchObject({ value: "00000000000", replayedAccepted: false }); + }); + + it("a double-read SUBSCRIBER card at ENTRY opens ONE occurrence and the repeat is accepted (replayed)", async () => { + const d = seed({}, "entry"); + db.insert(subscriptions).values({ id: "s1", status: "active", quantity: 1, period: "month" }).run(); + db.insert(subscriptionCredentials).values({ id: "c1", subscriptionId: "s1", kind: "rf", value: "3F3AFC" }).run(); + const first = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" })); + const second = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" })); + expect(first.accepted).toBe(true); + expect(second.accepted).toBe(true); // the card WAS read; beep ok, but no second entry + expect(ledger().filter((e) => e.type === "vehicle_entry")).toHaveLength(1); + expect(debounced()).toHaveLength(1); + }); + + it("a DIFFERENT code inside the window is not debounced", async () => { + const d = seed({}); + await d.dispatch(read("00000000000")); + await d.dispatch(read("00000000026")); // another Luhn-valid shape + expect(ledger()).toHaveLength(2); + expect(debounced()).toHaveLength(0); + }); + + it("the window comes from the reader's config and expires", async () => { + const d = seed({ debounceMs: 30 }); + await d.dispatch(read("00000000000")); + await new Promise((r) => setTimeout(r, 45)); + await d.dispatch(read("00000000000")); // outside the 30ms window → a fresh decision + expect(ledger()).toHaveLength(2); + expect(debounced()).toHaveLength(0); + }); + + it("debounceMs = 0 turns it off", async () => { + const d = seed({ debounceMs: 0 }); + await d.dispatch(read("00000000000")); + await d.dispatch(read("00000000000")); + expect(ledger()).toHaveLength(2); + }); + + it("a repeat arriving while the first read is still deciding gets the SAME decision", async () => { + const d = seed({}); + const [a, b] = await Promise.all([d.dispatch(read("00000000000")), d.dispatch(read("00000000000"))]); + expect(b).toEqual(a); + expect(ledger()).toHaveLength(1); + }); +}); diff --git a/apps/server/src/read-dispatch.ts b/apps/server/src/read-dispatch.ts index 03dd856..baa768c 100644 --- a/apps/server/src/read-dispatch.ts +++ b/apps/server/src/read-dispatch.ts @@ -5,7 +5,7 @@ import type { DeviceReadEvent, ReadOutcome } from "./device-events.js"; import type { ExitFlow } from "./exit-flow.js"; import { validateTicketCode } from "./entry-flow.js"; import type { SubscriptionFlow } from "./subscription-flow.js"; -import { relayForDevice } from "./device-resolve.js"; +import { relayForDevice, type ResolvedRelay } from "./device-resolve.js"; // Routes a credential read (ticket scan / plate / card) to the right flow. A read // can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the @@ -35,12 +35,44 @@ import { relayForDevice } from "./device-resolve.js"; // - ANY read on a CONFIRMED RF channel (a physically present card, enrolled or // not, is a real event — RF is never sun noise), // - plates (different population; never shape-filtered here). +// +// SAME-CODE DEBOUNCE (2026-10-11, park-2). The DT-008 reported one card TWICE 560 ms +// apart; the permit flow opened two sessions on the same permit and pulsed the barrier +// twice. Any reader can double-read (a card held a beat too long, a QR re-decoded while +// the hand moves), and at exit a second scan of a ticket inside its grace period would +// sign a noSession refusal for a car that just left. So the SAME value from the SAME +// reader within the reader's `debounceMs` (Setup → reader; default 5000; 0 = off) is one +// presentation: the first verdict is REPLAYED (same beep, no second decision, nothing +// signed twice) and the repeat is kept as unsigned telemetry. Every lane, every kind +// (card / QR / ticket / plate) — the ANPR bridge debounces plates itself, longer. + +/** Default same-code debounce when a reader's config has none (ms). */ +export const DEFAULT_READ_DEBOUNCE_MS = 5000; + +interface ReaderConfig { + readonly debounceMs?: number | string | null; + readonly [k: string]: unknown; +} + +/** The reader's debounce window: its config value (the Setup form may store a string), + * else the default; 0 (or a negative/garbage value coerced to 0) disables. */ +export function readDebounceMs(config: unknown): number { + const v = (config as ReaderConfig | null)?.debounceMs; + if (v == null || v === "") return DEFAULT_READ_DEBOUNCE_MS; + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; +} export class ReadDispatcher { readonly #db: Db; readonly #exit: ExitFlow; readonly #subscription: SubscriptionFlow; readonly #logger: FastifyBaseLogger; + /** Recent reads keyed `deviceId:kind:value` → when last seen + the FIRST verdict (a + * promise, so a repeat arriving while the first is still deciding gets that same + * decision). `at` slides on each repeat: a card held against the reader stays one + * presentation for as long as it keeps re-reading. */ + readonly #recent = new Map }>(); constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) { this.#db = db; @@ -59,6 +91,34 @@ export class ReadDispatcher { return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" }; } + // Same code, same reader, inside the window → replay the first verdict. Checked + // BEFORE matching so a repeat never reaches a flow (no second entry, no second exit, + // no refusal anomaly for a car that was just admitted). + const debounceMs = readDebounceMs(reader.config); + const key = `${e.deviceId}:${e.kind}:${e.value}`; + const now = Date.now(); + const prev = this.#recent.get(key); + if (debounceMs > 0 && prev && now - prev.at < debounceMs) { + const sinceMs = now - prev.at; + prev.at = now; + this.#logger.info( + `read debounced: '${e.value}' (${e.kind}) again on ${e.deviceId} after ${sinceMs}ms (window ${debounceMs}ms) — first verdict replayed`, + ); + void prev.outcome.then((o) => this.#recordDebounced(e, sinceMs, debounceMs, o)); + return prev.outcome; + } + const outcome = this.#decide(resolved, e); + if (debounceMs > 0) { + this.#recent.set(key, { at: now, outcome }); + if (this.#recent.size > 512) { + for (const [k, r] of this.#recent) if (now - r.at >= debounceMs) this.#recent.delete(k); + } + } + return outcome; + } + + /** The actual routing of a FRESH read (not a debounced repeat). */ + async #decide(resolved: ResolvedRelay, e: DeviceReadEvent): Promise { const sub = this.#subscription.match(e); if (sub) { return this.#subscription.run(resolved, e, sub); @@ -86,6 +146,34 @@ export class ReadDispatcher { return this.#exit.handleAt(resolved, e); } + /** Unsigned telemetry for a debounced repeat — auditable in device_events (the double + * read is still a fact about the hardware), out of the signed feed. */ + #recordDebounced(e: DeviceReadEvent, sinceMs: number, debounceMs: number, replayed: ReadOutcome): void { + try { + this.#db + .insert(deviceEventsTable) + .values({ + id: randomUUID(), + deviceId: e.deviceId, + category: "reader", + kind: "read", + detail: { + debounced: true, + value: e.value, + readKind: e.kind, + ...(e.channel ? { channel: e.channel } : {}), + sinceMs, + debounceMs, + replayedAccepted: replayed.accepted, + }, + occurredAt: e.at, + }) + .run(); + } catch (err) { + this.#logger.error(`debounced-read telemetry insert failed: ${(err as Error).message}`); + } + } + /** Unsigned telemetry for a filtered read — auditable in device_events, out of the * signed feed. Mirrors the entry flow's suppressed-press pattern. */ #recordUnrecognized(e: DeviceReadEvent): void { diff --git a/packages/devices/src/drivers/reader.ts b/packages/devices/src/drivers/reader.ts index 1e582fb..e1fc7d7 100644 --- a/packages/devices/src/drivers/reader.ts +++ b/packages/devices/src/drivers/reader.ts @@ -8,7 +8,7 @@ import type { ReaderDevice, ReaderEvent, } from "../interfaces.js"; -import type { DeviceConfig, DiscoverableDriver, DiscoveredDevice, ReaderDriver } from "../registry.js"; +import type { ConfigField, DeviceConfig, DiscoverableDriver, DiscoveredDevice, ReaderDriver } from "../registry.js"; import { hostField, portField, stubLog } from "./common.js"; import { QR_CARD_INPUT_FORMATS, @@ -72,6 +72,20 @@ class StubReader implements ReaderDevice { } } +/** Same-code debounce, applied HOST-SIDE by the read dispatcher (apps/server read-dispatch.ts) + * to every reader regardless of lane or credential kind: the same value from the same reader + * within this window is ONE presentation — the first verdict is replayed (same beep), nothing + * is signed twice. Born 2026-10-11 at park-2: the DT-008 reported one card twice 560 ms apart + * and the permit flow opened two sessions and pulsed the barrier twice. 0 disables. */ +export const debounceField: ConfigField = { + key: "debounceMs", + label: "Same-code debounce (ms)", + type: "number", + required: false, + default: 5000, + help: "A repeat of the same card/QR/ticket on this reader within this window counts as the same presentation (first verdict replayed, no second entry/exit). 0 = off.", +}; + export const wiegandReaderDriver: ReaderDriver = { id: "wiegand-reader", category: "reader", @@ -85,6 +99,7 @@ export const wiegandReaderDriver: ReaderDriver = { { value: "26", label: "Wiegand 26" }, { value: "34", label: "Wiegand 34" }, ] }, + debounceField, ], create: (c) => new StubReader("wiegand-reader", c), }; @@ -96,7 +111,7 @@ export const tcpipReaderDriver: ReaderDriver = { description: "Network RF/optical reader seen only by the host; host decides and commands the relay.", transports: ["tcp-ip"], - configFields: [hostField, portField(9000)], + configFields: [hostField, portField(9000), debounceField], create: (c) => new StubReader("tcpip-reader", c), }; @@ -297,6 +312,7 @@ export const dingtianQrReaderDriver: ReaderDriver & DiscoverableDriver = { required: false, help: "The reader's IP on the device VLAN. With it, save sets the reader to HTTP mode pointing at this booth and the monitor pings it. Blank = configure the reader manually; no liveness.", }, + debounceField, ], discover: discoverDingtianReaders, create: (c) => new DingtianQrReader("dingtian-qr-reader", c), diff --git a/wiki/entities/dingtian-dt008-reader.md b/wiki/entities/dingtian-dt008-reader.md index f92bf2d..15ea09a 100644 --- a/wiki/entities/dingtian-dt008-reader.md +++ b/wiki/entities/dingtian-dt008-reader.md @@ -2,7 +2,7 @@ type: entity tags: [parking, hardware, readers, qr, dingtian] sources: [dingtian-dt008, dingtian-qr-linux-tool] -updated: 2026-10-08 +updated: 2026-10-11 status: open --- @@ -168,6 +168,28 @@ not in our DB — re-apply after any factory reset/swap): the two **output prefi the server's expected `Q:`/`K:`), and **`Card Input format` (currently `6H`)** — it defines the UID shape we enroll; changing it later silently orphans every enrolled card. +## Same-code debounce at the dispatcher (park-2, 2026-10-11) + +The reader can report ONE presentation TWICE. Seen live on park-2 the evening the relay-pulse logging +went in: the entry reader (`HC009E84`) pushed card `3F3AFC` at 16:25:38.119Z and again at 16:25:38.679Z +(560 ms apart); the permit flow opened **two** sessions on the same permit and the barrier was pulsed +**twice**. The 24 h before showed 2 entry + 2 exit opens within 2 s of the previous one, so it is not a +one-off. A card held a beat too long or a QR re-decoded while the hand moves does the same, and at exit +a repeat scan of a ticket inside its grace period would sign a `noSession` refusal for a car that just +left — a red row for nobody (same alarm-fatigue problem as the phantom decodes below). + +**Fix (host-side, every reader, every lane, every credential kind):** `ReadDispatcher` keeps the recent +reads keyed `deviceId:kind:value`; the same value from the same reader inside the reader's +**`debounceMs`** window is one presentation — the FIRST verdict is **replayed** (the reader beeps the +same way, no second decision, nothing signed twice) and the repeat is kept as unsigned +`device_events` telemetry (`debounced: true`, `sinceMs`, `replayedAccepted`). The window slides on +each repeat (a card that keeps re-reading stays one presentation). A repeat that arrives while the +first read is still deciding awaits that same decision. The window is a **per-reader Setup field** +(`debounceMs`, "Same-code debounce (ms)", default **5000**, `0` = off) on all three reader drivers +(`packages/devices/src/drivers/reader.ts` `debounceField`); readers configured before the field +existed get the default. Plates are not affected in practice — the ANPR bridge debounces them itself +for longer ([[lane-presence-and-anpr-entry]]). Tests: `read-dispatch-debounce.test.ts`. + ## ⚠️ Phantom optical decodes from sunlight patterns (park-buzi, 2026-07-04) With the site EMPTY (pre-opening, verified live + by snapshot), the **exit reader diff --git a/wiki/log.md b/wiki/log.md index 0141e88..8b8645b 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -3528,3 +3528,10 @@ each plate is settled once per loop, debounce keyed `deviceId:plate`, credential 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. + +## [2026-10-11] built | Same-code read debounce at the dispatcher (per-reader `debounceMs`, default 5000) +park-2 double-read: the DT-008 reported one card twice 560 ms apart → two permit sessions, two barrier +pulses (caught by the new relay-pulse log on deploy day). `ReadDispatcher` now treats the same value +from the same reader inside the reader's `debounceMs` as one presentation: first verdict replayed, +repeat → unsigned telemetry, nothing signed twice. Every lane and credential kind. Setup field on all +reader drivers. [[dingtian-dt008-reader]] updated; `read-dispatch-debounce.test.ts` (7).