39 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
julian a86af4eb20 bump(resources): park-2 to stage-2ac26b5 (exit tile is the manual-exit control)
Build & push images / images (push) Successful in 3m22s
2026-10-09 09:24:00 +02:00
julian 2ac26b5825 feat(booth): the exit lane light is the manual-exit control — two tiles, Hyrje and Dalje Manuale
Build & push images / images (push) Successful in 3m20s
BarrierLight gains onOpen/opening (not presence-gated). For an operator with
barrier:create + own shift the exit tile is labelled 'manual exit', clickable and
opens the manual-exit dialog while still showing the lane state; for everyone else it
stays the plain 'Dalje' light. The separate ghost button is removed. Wiki as-built note.
2026-10-09 09:17:16 +02:00
julian 3f903cdbdd bump(resources): park-2 to stage-ffcf0d3 (manual-exit wording)
Build & push images / images (push) Successful in 3m12s
2026-10-09 09:06:25 +02:00
julian ffcf0d3eda fix(i18n): update Albanian translations for manual exit functionality
Build & push images / images (push) Successful in 3m7s
2026-10-09 09:02:59 +02:00
julian e3b3a636e2 fix(i18n): update wording for manual exit in English and Albanian translations
Build & push images / images (push) Successful in 3m10s
2026-10-09 08:46:34 +02:00
julian 55c9c33432 bump(resources): park-2 to stage-82e5833 (manual-exit dialog + wording)
Build & push images / images (push) Successful in 3m15s
2026-10-09 08:41:41 +02:00
julian 82e5833e4e feat(exit): manual-exit dialog + wording — styled modal replaces window.prompt; copy says 'manual exit' / 'dalje manuale'
Build & push images / images (push) Successful in 3m13s
- BoothScreen: the no-ticket open uses the app's Modal (explainer, optional reason,
  red confirm; Enter confirms, Escape/Cancel abort) instead of a browser prompt.
- en/sq: forgive/forgiven/forgone wording dropped from every user-facing string
  (buttons, dialog, results, live-feed reasons, shift figures); Albanian edited by the
  user, English aligned. Printed Z line is 'Dalje manuale (N)'. The signed English
  fallback sentences follow. Identifiers (exit.forgiven, forgoneMinor, barrier:create)
  unchanged.
- wiki: forgiven-exit §Wording, shift, log.
2026-10-09 08:37:44 +02:00
julian 2e98167dba bump(resources): park-2 to stage-a761398 (forgiven exit; pass samples)
Build & push images / images (push) Successful in 3m3s
2026-10-09 08:19:52 +02:00
julian a761398301 feat(exit): forgiven exit — open the exit barrier with no payment (barrier:create)
Build & push images / images (push) Successful in 3m23s
The owner (or any role the owner grants barrier:create) lets a car out for free.
Exit side only. Every use is signed, attributed, photographed and on the operator's
Z-report; the shift's cash/card/drawer are untouched by construction.

- shared: resource 'barrier' + permission 'barrier:create'; reason codes
  exit.forgiven / exit.forgiven.noSession; LedgerPayload.forgoneMinor.
- pay-station: forgive() signs a $0 payment carrying the quoted fee as forgoneMinor
  (no tender), refuses a ticket with module charge lines (a wash is not forgiven).
- exit-flow: reopenBarrier(..., { forgiven }) bypasses the walk-back check and stamps
  the forgiven reason on the anomaly + vehicle_exit; forgiveExitNoSession() for a car
  with no ticket (anomaly under forgiven:<id> + exit snapshot + pulse). Relay driving
  shared in #pulseExit.
- route POST /api/barrier/forgive { identity?, note? }: barrier:create + open shift;
  the reason is optional (an empty note is signed as '(no reason given)').
- shift-service: forgoneTotalMinor + forgoneCount on the report/summary/signed
  shift_z_report (only when > 0), print line 'Dalje të falura (N)'.
- web: 'Forgive & open' in the pay/exit modal for an open transient that owes money;
  'Forgive & open exit' on the booth header for the no-ticket case; forgone line on
  the X-report, close confirm and history; en/sq. Prints nothing.
- tests: exit-flow, pay-station, shift-service, HTTP route (403 without the
  permission, 409 no shift, empty note accepted, ledger sequence, report figures).
- wiki: decisions/forgiven-exit.md (decision + as-built), booth-exit-flow, shift,
  index, log.
2026-10-09 08:14:36 +02:00
julian 5d247a5729 bump(resources): park-2 to stage-30a1180 (trial: pass samples for every detected car)
Build & push images / images (push) Successful in 4m11s
2026-10-08 19:36:25 +02:00
julian 30a1180108 feat(review): sample every detected car, not only ticketed entries
Build & push images / images (push) Successful in 5m20s
The entry stream for the reviewer was fed from the session-tied read only (ticket
printed / exit signed). park-2 ran an afternoon with its barriers up: hundreds of
camera vehicle pushes, zero tickets, zero samples.

- anpr-entry: keep the best-framed vehicle of each poll loop (highest body-type
  confidence with a box), store that frame as a snapshot (identity pass:<id>, no
  session) and emit a vehicle read with the camera id — plate or no plate. One
  sample per detection, fire-and-forget, never on the ANPR path.
- snapshot.ts: normalizedBoxes() shared by the session-tied read and the bridge;
  vehicle reads now carry deviceId.
- review-outbox: sampleEntry(deviceId) dedups per camera for 30 s so the pass
  sample and a ticket entry's read (same car, seconds apart) go once.
- wiki: outbox page (entry stream, troubleshooting checklist for 'nothing arrives':
  the month-long silence was a missing Netbird policy, not code), park-2 camera
  port-forward procedure (site-device-installation §7), log.
2026-10-08 19:30:03 +02:00
julian 354de04a3d bump(resources): all stacks to stage-32b4d9e (CI tags with the push head; stage-1167e27 was never built)
Build & push images / images (push) Successful in 8m24s
2026-10-08 17:36:52 +02:00
julian 32b4d9e92b bump(resources): all stacks to stage-1167e27 (the fc93db7 build failed on lint; same content plus the test fix)
Build & push images / images (push) Successful in 3m40s
2026-10-08 16:15:32 +02:00
julian 1167e27b1d fix(vision): wrap the health-filter test lines (ruff E501 broke the image build) 2026-10-08 16:15:27 +02:00
julian f4e5c5037b bump(resources): park-buzi, park-2, park-lab and wash-collector to stage-fc93db7 (log noise cut; DT-008 discovery + auto-config)
Build & push images / images (push) Failing after 27s
2026-10-08 16:11:57 +02:00
julian fc93db73c2 fix(logs): silence health probes, one line per request, demote per-event chatter to debug
Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, 60 of them the Docker
HEALTHCHECK's /health logged as "incoming request" + "request completed"; 160 vision lines,
143 of them uvicorn access lines for GET /health (Docker's probe + the booth server's footer
chip polling every 8 s). Levels were never the problem — all of it was info.

- server: /health route logLevel "silent"; disableRequestLogging + an onResponse hook that
  logs one line "METHOD url → status Nms". That flag also stops Fastify's default error
  handler from logging handler errors, so an onError hook logs 5xx with the stack
  (fastify 5.8.5 lib/error-handler.js checks the same flag). Pinned by request-logging.test.ts.
- vision: a logging.Filter on uvicorn.access drops /health access lines (tested).
- devices: stubLog gains a level; the per-snapshot "captureSnapshot (N bytes)" line is
  debug; the hik-alarm HIT line is debug (ACCEPTED/REJECTED carry everything).
  LOG_LEVEL=debug restores all of it. Wiki: app-logs §Noise cut.
2026-10-08 16:06:39 +02:00
julian 44f757ee37 docs(wiki): memo on discovery mechanisms for cameras, printers and the relay (SADP/ONVIF probed on the lab VLAN); park-2 readers switched to HTTP from the wizard 2026-10-08 15:51:45 +02:00
julian b00182d95d bump(resources): park-2 to stage-b7efa08 (DT-008 reader discovery + auto-config in the wizard)
Build & push images / images (push) Successful in 2m54s
2026-10-08 15:22:51 +02:00
julian b7efa081ec feat(devices): DT-008 reader discovery + auto-configuration over the vendor UDP protocol
Build & push images / images (push) Successful in 3m7s
The Dingtian DT-008's Windows-only config tool speaks a small binary UDP protocol
(reader :24680 unicast get/set, :24582 broadcast search/set-network), reversed in
wiki/raw/dingtian_qr_linux (PROTOCOL.md + dingtian_qr.py, copied to scripts/). Reading
park-2's readers with it from the booth found both in WG26 output mode — the "beeps but
captures nothing" enrolment failure: they never pushed HTTP at all.

The app now speaks the protocol itself (packages/devices dingtian-qr-config.ts, Node dgram,
host-network container) and the dingtian-qr-reader driver uses it:
- discover(): first driver to implement the wizard's Scan capability; rows show serial, IP,
  output mode, current server target, card format, firmware.
- preconditions: output type must be HTTP (fixable — save switches it); typed serial must
  equal the reported one and the reader must answer on UDP (both block the save).
- configureInputPush(): set-network the reader's server to this booth's IP + listen port,
  confirmed by polling (the reader applies it without an ack and is silent for seconds).
- usesPushAuth=false: the scan GET carries no credentials, so no push secret is stored.
- a reader saved without an IP warns instead of failing (legacy vendor-tool setup).

Verified on the bench unit: WG26→HTTP, target 8080→8081→8080, struct byte-identical after.
15 protocol tests against a fake reader + 17 adapter tests. Wiki: device-discovery,
first-run-setup, dingtian-dt008-reader, site-device-installation §2 (SSH procedure; the
"needs a Windows laptop" claim withdrawn), new source page dingtian-qr-linux-tool.
2026-10-08 15:22:33 +02:00
julian 08351a09bf chore(deploy): stack ports as env variables; park-lab moves to art-docker-station
Build & push images / images (push) Successful in 2m56s
art-docker-station already serves :80, so the lab stack could not come up there.
HTTP_PORT (Caddy listen), SERVER_PORT (host-net server + advertised device push
port) and VISION_HOST_PORT (vision loopback publish) now flow from the stack env
through docker-compose.prod.yml; the Caddyfile reads {$HTTP_PORT:80} and
{$SERVER_PORT:3000}. Unset = the old :80 -> :3000 / 8089 layout, so booths are
unchanged. park-lab: server = art-docker-station, ports 8080 / 3100 / 8189.

Verified: caddy validate + adapt (with env -> :8080 / 127.0.0.1:3100, without
-> :80 / :3000) and docker compose config with the lab values. Wiki:
container-deployment §proxy, fleet-deployment-komodo §park-lab, log.
2026-10-08 11:00:04 +02:00
julian 4593a397dd fix(devices): Dahua snapshot channel is 1-based; add Dahua clock sync; wiki page for the bench IPC-HFW2549T
Build & push images / images (push) Successful in 3m25s
The dahua driver decremented the wizard's channel on the belief the CGI is
0-based. On real hardware (IPC-HFW2549T-AS-IL, fw V2.880, 2026-09-17)
snapshot.cgi?channel=0 answers HTTP 400 and channel=1 returns the 2880x1620
JPEG — so every Dahua assignment sat at degraded "HTTP 400". The channel is
now sent as entered (clamped >= 1) and the URL is pinned in camera.test.ts.

DahuaCamera.syncClock reads global.cgi getCurrentTime and, past the drift
limit, writes setCurrentTime with the host's naive local wall time (no offset):
the OSD burned into snapshots must match the booth clock; the camera's tz/DST
config is left alone. Verified live: a 2h-off set, set back, 1s drift -> no
write. The device monitor picks it up via isClockSyncable unchanged.

Wiki: new entities/dahua-ipc-hfw2549t.md (endpoint table, verbatim
eventManager attach parts — VideoMotion Start/Stop, VideoMotionInfo,
TimeChange — RealUTC is the camera's belief of UTC, 5-strike login lockout,
unit not factory-fresh); lpr-camera Dahua bullet corrected; runbook §3 Dahua
paragraph; index + log. The server-side attach-stream subscriber is not built.
2026-10-08 08:03:50 +02:00
julian 4d1d245680 docs(wiki): DT-008 card-technology findings, box leaflet source, install checklist; add scripts/reader-sink.py
Two DT-008 units read disjoint card sets (park-buzi 125 kHz, lab unit 13.56 MHz only)
although the box leaflet claims EM-ID + M1 + ISO 14443A/B + 15693 in one unit; recorded as
unresolved with the EM4100 test that settles it (open question #18). Phone taps give a
random 08… UID per tap, so phones are never RF credentials; 6H keeps the first three UID
bytes reversed. Runbook §2 gains the tool's Setting-tab layout, a capability-identification
checklist and the per-technology parameter table. reader-sink.py is a stdlib bench sink
answering the push with the SDK verdict and Connection: close.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-17 09:47:40 +02:00
julian 5afdcc78ae chore(komodo): park-lab posts review crops as booth-lab; collector lists its token
Build & push images / images (push) Successful in 2m48s
Own pseudonymous id and own secret (wash_review_token_booth_lab), never a real
booth's, so bench crops stay separable per booth on the collector and can be
labelled unusable. Fleet page row updated.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-16 10:55:21 +02:00
julian e3de7800e5 bump(resources): wash-collector to stage-73bfc1d (collector DB migration, trainer 500 replies)
Build & push images / images (push) Successful in 2m48s
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-16 10:40:36 +02:00
julian 73bfc1d9b9 chore(komodo): park-buzi joins the review outbox as booth-1; collector lists its token
Build & push images / images (push) Successful in 5m44s
Park-buzi posts entry crops to the collector under a PSEUDONYMOUS id (booth-1,
not the site name — the crops leave the site) with its own secret
(wash_review_token_booth_buzi, a Core-only name). The collector's booth-token
list gains the pair. The collector TAG is unchanged here: bump it to the build
that carries the schema migration once CI has produced it, and deploy the
collector before park-buzi.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-16 10:33:47 +02:00
julian f4b806a538 fix(collector,trainer): migrate an existing collector DB on open; trainer handlers answer 500 JSON
The reviewer host's collector.sqlite was created by an earlier build, before the
`kind` column. CREATE TABLE IF NOT EXISTS shapes only a new database, so every query
naming the column failed: the collector's /health (container unhealthy), every
booth ingest, and the trainer's readiness — whose stdlib server printed the
traceback and dropped the socket, which the collector could only render as
"trainer not reachable: fetch failed". Nine days like that.

- CollectorDb.#migrate(): PRAGMA table_info against the list of columns added
  since the first deploy; ALTER TABLE ADD COLUMN for each missing one (all
  nullable or defaulted). Append to that list whenever a column joins the CREATE.
  Test replays the original schema: health, ingest, stats, a legacy row reads
  back with the defaults.
- Trainer Handler._guarded(): any unexpected exception → 500 JSON naming it,
  never a dropped connection; /health keeps answering. Test drives readiness
  against an old-schema DB.
- The collector's training status proxy includes the trainer's error text.

Wiki: the incident and the schema rule (vision-review-outbox), what the message
means (bodytype-classifier-training), log. Deploy: the new collector migrates on
start; nothing manual.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-16 10:33:47 +02:00
julian fe3b12a60d bump(resources): park-buzi, park-2 and park-lab to stage-88f9c53 (K200L status parser fix)
Build & push images / images (push) Successful in 2m58s
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 13:00:14 +02:00
julian 88f9c53fda fix(devices): K200L status parser reads a fault's Yes, which the board wraps in <FONT color=#ff0000>
Build & push images / images (push) Successful in 2m55s
First live run on park-lab with the cover open reported "unexpected status page
(missing coverOpen, paperEnd, offline)" — exactly the three fault cells. The board
writes a fault as <FONT color=#ff0000>Yes</FONT> and a clear row as a bare padded
No; the parser accepted only tag-free cells. Cell text is now read with inner tags
stripped (row-anchored match). Tests pin the verbatim captured markup plus other
shapes. Live after the fix: degraded "cover open, paper out, printer off-line";
cover closed → ready.

Wiki: the markup on the K200L page; Periphery "not loaded after reboot" (unit never
enabled → `systemctl --user enable --now periphery`) as a §7a gotcha in the
provisioning runbook; log.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 12:57:58 +02:00
julian e8cb057082 bump(resources): update TAG to stage-4a02e5f for all booth synchronizations
Build & push images / images (push) Successful in 2m47s
2026-09-09 12:41:15 +02:00
julian 4a02e5fed3 docs(wiki): site device installation — the field runbook for what to know before the booth
Build & push images / images (push) Successful in 2m50s
Per device (Dingtian relay board, DT-008 readers, Hikvision G3H camera, radar,
K200L / Rongta / Cashino printers): factory address and login, the tool needed,
what the wizard configures by itself on assign vs what is done by hand on the
device, how to verify, and the traps already paid for (unauthenticated Dingtian
CGI + session_en brick, duplicate reader IP, reader settings lost on reset, sub
stream mandatory, Alarm Server after assign + Vehicle target filter, close the
camera web UI, radar idle level, "Test" only probes a printer). Bring list, the
10.0.10.x address plan beside each factory address, the on-site order of work,
and the gaps still unrecorded. Linked from appliance-provisioning and the K200L
page; log entries for the day.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 12:34:59 +02:00
julian 552d87d75b feat(devices): K200L printer driver — live cover/paper status from the J-Speed LAN board
The park-buzi printer is a K200L (Xprinter/ICS XP-K200L; its LAN board and USB
descriptor call it "POS-80"). Its board serves the Rongta's five-row status table
under /prt_status.htm — but the reply carries no HTTP status line or headers, which
node:http rejects, so the Rongta driver could never read it and the unit was filed
in July as "no status page → generic driver" (reachability only).

New `k200l` driver (printer-k200l.ts): prints through the generic ESC/POS device
(same bytes, TCP 9100 or usblp) and reads the page over a raw socket, tolerant of
both the headerless and a proper HTTP reply. Mapping mirrors the Rongta: board
unreachable → offline; page not understood → degraded, never ready; any fault →
degraded naming it; USB → reachability floor. The Rongta driver is untouched.
Tests replay the captured headerless page (devices suite 76). Live against the
lab unit: ready; with the cover open the board reports cover open, paper out,
off-line.

Wiki: new k200l-printer entity (names, network setup from factory
192.168.123.100, board quirks, status page, what it means for park-buzi — over
USB the app never saw cover/paper state at all), cross-links on the Rongta,
status-monitoring, USB-transport and WSL-networking pages (parking-net pinned to
eth1 while the LAN NIC is eth0), index.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 12:34:59 +02:00
julian 7e21cf057e chore(komodo): park-lab stack for the printer bench; wiki: cover-open bug bench result
Build & push images / images (push) Successful in 3m3s
park-lab re-added to resources.toml for the reproduction box: copied from park-2 then
corrected — the copy carried park-2's review outbox (collector URL, booth-2 id, booth-2's
token), which would have fed the training pool under a booth's identity; removed, the
outbox is off on the bench. Pinned to the booth's stage-2d9bb15, comments say what the
lab is for.

Wiki, printer-usb-transport: the failing printer identified (USB 1fc9:2016 "POS-80", NXP
controller, no brand in the descriptor); attached to WSL via usbipd and cover-cycled — no
disconnect, no re-enumeration, so the stale /dev/usb bind-mount hypothesis is falsified
for this unit; the next discriminator is the monitor's offline detail text on park-buzi
(EBUSY / open timeout / EIO). WSL caveat: Microsoft's kernel lacks CONFIG_USB_PRINTER.
fleet-deployment-komodo: park-lab row updated. Log: both entries of the day.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 10:19:18 +02:00
julian 4fd175e0e4 docs(wiki): subscription recurring billing + party ledger — design only
Subscription page: the one-window model can't express prepaid/postpaid, calendar or
anniversary anchoring, grace or an expiry notice; and renewal is OFF-BOOK today (a PUT
that appends no payment — the same hole closed for the first sale on 2026-06-20).
Designed: plan billing rule, per-day pricing so both anchors share one formula, open-
ended agreement, subscription_periods where each period is a ledger charge and a renewal
= paying the next period, one subscriptionAccess() gate function, expiry notice derived
not stored.

New decision page party-ledger: a counterparty sub-ledger for who-owes-whom across
modules — parties + signed charge / settlement / write_off events, balance derived never
stored, aging + statements + CSV; lands postpaid subscriptions, hotel guest-nights,
fleet washes on account, supplier/utility bills. Sub-ledger only: no bookkeeping, a
statement is not a fiscal invoice, parties per appliance. validation-sponsorship's
sponsor table marked superseded; open-questions #17; index.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-09 10:19:09 +02:00
julian 535244209a docs(wiki): seed-admin on a booth — container-name pattern, prompting form, idempotence, re-seed after a reset
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-07 15:06:19 +02:00
julian 0845e87ddd bump(resources): park-2 and wash-collector to stage-2d9bb15
Build & push images / images (push) Successful in 2m48s
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-07 14:57:47 +02:00
julian 2d9bb15d4c fix(db): reset-db categorises the Car Wash tables and role_jobs — the drift guard refused every reset on a booth carrying them
Build & push images / images (push) Successful in 2m47s
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-07 14:37:49 +02:00
98 changed files with 7342 additions and 364 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/
+8 -2
View File
@@ -7,9 +7,15 @@
# TLS later: replace `:80` with the real hostname (e.g. `parksystems.msai.al`), uncomment
# Caddy's :443 in docker-compose.prod.yml, and Caddy auto-provisions HTTPS. For a private
# CA / internal cert, use `tls /path/cert.pem /path/key.pem`.
:80 {
#
# PORTS ARE ENV-DRIVEN (2026-10-08): HTTP_PORT (listen, default 80) and SERVER_PORT (upstream,
# default 3000) come from docker-compose.prod.yml, which takes them from the stack env. A booth
# leaves both unset and gets :80 → :3000 exactly as before. A SHARED host (the lab stack moved
# onto art-docker-station, whose :80 belongs to another service) sets HTTP_PORT=8080 etc. in the
# Komodo stack env — nothing here or in the image changes. See wiki/decisions/container-deployment.md.
:{$HTTP_PORT:80} {
encode gzip
# Host network (prod): the server runs on the host's net namespace (to reach the booth LAN /
# device VLAN), so reach it over loopback, not the compose service name `server`.
reverse_proxy 127.0.0.1:3000
reverse_proxy 127.0.0.1:{$SERVER_PORT:3000}
}
+43
View File
@@ -151,3 +151,46 @@ describe("config", () => {
expect(() => parseBoothTokens("nocolon")).toThrow(/bad pair/);
});
});
describe("schema migration", () => {
it("opens a database created before the `kind` column and adds the missing columns, so ingest and stats work", async () => {
// art-docker-station, 2026-09-16: the volume's DB predated `kind`; CREATE TABLE IF NOT
// EXISTS left it alone, and /health, every ingest and the trainer's readiness failed
// with "no such column: kind". Replay: a file with the ORIGINAL column set.
const { default: Database } = await import("better-sqlite3");
const file = path.join(dir, "old.sqlite");
const old = new Database(file);
old.exec(`CREATE TABLE items (
id TEXT PRIMARY KEY, booth TEXT NOT NULL, order_ref TEXT NOT NULL, at TEXT NOT NULL,
service TEXT NOT NULL, vision_class TEXT NOT NULL, vision_confidence REAL NOT NULL,
image_width INTEGER NOT NULL, image_height INTEGER NOT NULL, plate_blurred INTEGER NOT NULL,
image_path TEXT NOT NULL, received_at TEXT NOT NULL, review_label TEXT, reviewed_at TEXT, reviewer TEXT)`);
old.prepare(
"INSERT INTO items (id, booth, order_ref, at, service, vision_class, vision_confidence, image_width, image_height, plate_blurred, image_path, received_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
).run("legacy-1", "booth-7", "o-0", "2026-09-01T00:00:00.000Z", "Standard", "suv", 0.8, 100, 100, 1, "crops/legacy-1.jpg", "2026-09-01T00:00:00.000Z");
old.close();
const legacy = await buildCollector({ host: "127.0.0.1", port: 0, dataDir: dir, boothTokens: TOKENS, reviewer: REVIEWER, trainerUrl: null }, { dbFile: file });
await legacy.ready();
try {
const health = await legacy.inject({ method: "GET", url: "/health" });
expect(health.statusCode).toBe(200);
expect(health.json()).toMatchObject({ ok: true, booths: 1, pending: 1 });
const { body, type } = multipart({ meta: JSON.stringify(meta({ item: "item-new" })) }, JPEG);
const r = await legacy.inject({ method: "POST", url: "/ingest", headers: { authorization: `Bearer ${TOKENS.get("booth-7")!}`, "content-type": type }, payload: body });
expect(r.statusCode).toBe(201);
const stats = await legacy.inject({ method: "GET", url: "/api/stats", headers: { authorization: basic } });
expect(stats.statusCode).toBe(200);
// The legacy row reads back with the defaults the new columns carry.
const cols = new Database(file, { readonly: true }).prepare("PRAGMA table_info(items)").all() as { name: string }[];
expect(cols.map((c) => c.name)).toEqual(expect.arrayContaining(["kind", "operator_ref", "operator_classes", "vision_category_id", "downgraded"]));
const legacyRow = new Database(file, { readonly: true }).prepare("SELECT kind, operator_classes, downgraded FROM items WHERE id = 'legacy-1'").get() as Record<string, unknown>;
expect(legacyRow).toEqual({ kind: "wash", operator_classes: "[]", downgraded: 0 });
} finally {
await legacy.close();
}
});
});
+12 -1
View File
@@ -253,7 +253,18 @@ export async function buildCollector(cfg: CollectorConfig, opts: { dbFile?: stri
try {
const get = async (p: string) => {
const r = await fetch(trainer + p, { signal: AbortSignal.timeout(15_000) });
if (!r.ok) throw new Error(`${p} → HTTP ${r.status}`);
if (!r.ok) {
// Surface the trainer's own error text (its handlers answer 500 JSON), so the
// reviewer reads "no such column: kind", not just a status code.
const detail = await r.text().then((t) => {
try {
return String((JSON.parse(t) as { error?: unknown }).error ?? t);
} catch {
return t;
}
}, () => "");
throw new Error(`${p} → HTTP ${r.status}${detail ? `: ${detail.slice(0, 300)}` : ""}`);
}
return r.json() as Promise<Record<string, unknown>>;
};
const [health, readiness, versions, jobs] = await Promise.all([get("/health"), get("/readiness"), get("/versions"), get("/jobs")]);
+33
View File
@@ -71,6 +71,39 @@ export class CollectorDb {
CREATE INDEX IF NOT EXISTS items_pending ON items (reviewed_at, received_at);
CREATE INDEX IF NOT EXISTS items_booth ON items (booth, received_at);
`);
this.#migrate();
}
/** Columns added after the first deploy, with the DDL that adds them to an EXISTING
* table. `CREATE TABLE IF NOT EXISTS` above only shapes a NEW database; a volume that
* was created by an earlier build keeps its old columns, and every query naming a new
* one then fails ("no such column: kind" — art-docker-station, 2026-09-16: the
* collector's /health, every ingest, and the trainer's readiness all broke on a DB
* from before `kind`). Each entry must be addable to a populated table, i.e. nullable
* or carrying a DEFAULT. Append here whenever a column joins the CREATE above. */
static readonly #ADDED_COLUMNS: ReadonlyArray<readonly [name: string, ddl: string]> = [
["kind", "TEXT NOT NULL DEFAULT 'wash'"],
["operator_ref", "TEXT NOT NULL DEFAULT ''"],
["operator_category_id", "TEXT NOT NULL DEFAULT ''"],
["operator_category_name", "TEXT NOT NULL DEFAULT ''"],
["operator_classes", "TEXT NOT NULL DEFAULT '[]'"],
["vision_category_id", "TEXT"],
["downgraded", "INTEGER NOT NULL DEFAULT 0"],
];
/** Bring an existing `items` table up to the current column set (idempotent). */
#migrate(): void {
const present = new Set(
(this.#db.prepare("PRAGMA table_info(items)").all() as { name: string }[]).map((c) => c.name),
);
for (const [name, ddl] of CollectorDb.#ADDED_COLUMNS) {
if (!present.has(name)) this.#db.exec(`ALTER TABLE items ADD COLUMN ${name} ${ddl}`);
}
}
/** The current column names of `items` (for tests and diagnostics). */
columns(): string[] {
return (this.#db.prepare("PRAGMA table_info(items)").all() as { name: string }[]).map((c) => c.name);
}
close(): void {
+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
+167 -26
View File
@@ -1,10 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db } from "@parking/db";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
import { deviceEvents, type DeviceReadEvent, type VehicleReadEvent } from "./device-events.js";
import { silentLogger } from "./test-helpers.js";
import type { VisionClient, VisionResult } from "./vision-client.js";
import type { VisionClient, VisionResult, VisionVehicle } from "./vision-client.js";
import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js";
// The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a
@@ -14,7 +14,12 @@ import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js
// Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub
// (no registry, no network). The factory returns a fresh shot each call.
const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg" }));
const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg", capturedAt: new Date().toISOString() }));
// The pass sample's box normalisation (needs a real JPEG header in prod) — stubbed so a
// test can hand the bridge a vehicle box, or none.
const { normalizedBoxes } = vi.hoisted(() => ({
normalizedBoxes: vi.fn(async (): Promise<{ vehicleBox: unknown; plateBox: unknown }> => ({ vehicleBox: null, plateBox: null })),
}));
// The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in
// snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this
// suite stays focused on the bridge's own match/debounce/emit logic.
@@ -22,6 +27,9 @@ vi.mock("./snapshot.js", () => ({
buildCamera: () => ({ captureSnapshot }),
captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) =>
camera.captureSnapshot(ctx as never),
// Storage re-encode is sharp's business (snapshot.test.ts); here the bytes pass through.
encodeForStorage: async (shot: { bytes: Buffer; contentType: string }) => ({ bytes: shot.bytes, contentType: shot.contentType }),
normalizedBoxes,
}));
// Import AFTER the mock is registered.
@@ -31,11 +39,14 @@ let db: Db;
beforeEach(() => {
({ db } = createTestDb());
captureSnapshot.mockClear();
normalizedBoxes.mockReset();
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";
});
@@ -74,17 +85,18 @@ function seedCamera(opts: { anpr?: boolean; anprAutoTrigger?: boolean } = {}): s
return camId;
}
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null). */
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number } = {}): VisionClient {
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null), and
* optionally a vehicle (body type + box) the way the vehicle stage reports it. */
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number; vehicle?: VisionVehicle } = {}): VisionClient {
const enabled = opts.enabled ?? true;
const result: VisionResult | null =
opts.plate == null
opts.plate == null && opts.vehicle == null
? null
: {
plate: { text: opts.plate, confidence: opts.confidence ?? 0.99 },
plate: opts.plate == null ? null : { text: opts.plate, confidence: opts.confidence ?? 0.99 },
plates: [],
lowConfidence: false,
vehicle: null,
vehicle: opts.vehicle ?? null,
modelVersion: "test",
tookMs: 1,
};
@@ -96,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[]> {
@@ -122,6 +150,79 @@ async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]>
return got;
}
/** Capture vehicle-read (pass sample) events during `fn`, waiting for the bridge's
* fire-and-forget recording to land. */
async function captureVehicleReads(fn: () => Promise<void>, expectCount: number): Promise<VehicleReadEvent[]> {
const got: VehicleReadEvent[] = [];
const off = deviceEvents.onVehicleRead((e) => got.push(e));
try {
await fn();
if (expectCount > 0) await vi.waitFor(() => expect(got).toHaveLength(expectCount));
else await new Promise((r) => setTimeout(r, 20));
} finally {
off();
}
return got;
}
describe("AnprBridge pass sample — every detected car, ticket or not", () => {
const VEHICLE: VisionVehicle = { bodyType: "car", confidence: 0.91, bbox: { x1: 10, y1: 10, x2: 200, y2: 120 } };
const BOX = { x1: 0.1, y1: 0.1, x2: 0.5, y2: 0.6 };
it("stores the frame + emits a vehicle read with NO plate at all (barriers up: no ticket, no session)", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ vehicle: VEHICLE }), fakeSubFlow(null), silentLogger());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 1);
const read = got[0]!;
expect(read).toMatchObject({ direction: "entry", deviceId: cam, read: { bodyType: "car", confidence: 0.91, box: BOX, plateBox: null } });
expect(read.identity).toBe(`pass:${read.read.snapshotId}`);
const row = db.select().from(snapshots).where(eq(snapshots.id, read.read.snapshotId!)).get();
expect(row).toMatchObject({ direction: "entry", deviceId: cam, identity: read.identity, contentType: "image/jpeg" });
});
it("is ONE sample per 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());
let reads: DeviceReadEvent[] = [];
const got = await captureVehicleReads(async () => {
reads = await captureReads(() => bridge.onVehicleDetected(cam));
}, 1);
expect(reads).toHaveLength(1); // the subscriber's plate read still goes out
expect(got[0]!.read.plateBox).toEqual({ x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 }); // for the crop's blur
expect(db.select().from(snapshots).all()).toHaveLength(1);
});
it("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());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 0);
expect(got).toEqual([]);
expect(db.select().from(snapshots).all()).toHaveLength(0);
});
});
describe("AnprBridge", () => {
it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => {
const cam = seedCamera({ anpr: false });
@@ -184,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));
@@ -232,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 () => {
@@ -275,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 () => {
+191 -118
View File
@@ -1,21 +1,31 @@
import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db, type DeviceRow } from "@parking/db";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db, type DeviceRow } from "@parking/db";
import type { Snapshot } from "@parking/devices";
import type { FastifyBaseLogger } from "fastify";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
import { directionOf, type FlowDirection } from "./device-resolve.js";
import { buildCamera } from "./snapshot.js";
import { buildCamera, encodeForStorage, normalizedBoxes } from "./snapshot.js";
import type { SubscriptionFlow } from "./subscription-flow.js";
import type { VisionClient } from "./vision-client.js";
import type { VisionClient, VisionResult } from "./vision-client.js";
// The ANPR "bridge": a subscriber's plate, read from the lane camera, admits them through
// the 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 +
@@ -25,7 +35,8 @@ import type { VisionClient } 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 {
@@ -45,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
@@ -69,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
@@ -97,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
@@ -143,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;
@@ -172,134 +184,195 @@ 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;
/** 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);
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);
// 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 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;
if (!vehicle) return;
const { vehicleBox, plateBox } = await normalizedBoxes(best.shot.bytes, best.r);
if (!vehicleBox) return;
const stored = await encodeForStorage(best.shot, this.#logger);
const id = randomUUID();
const identity = `pass:${id}`;
this.#db
.insert(snapshots)
.values({ id, direction, deviceId, identity, contentType: stored.contentType, bytes: stored.bytes, capturedAt: best.shot.capturedAt })
.run();
// plateBox whenever the detector saw a plate, confident or not: it is what the
// review crop blurs — privacy, not identity.
deviceEvents.emitVehicleRead({
identity,
direction,
deviceId,
read: { bodyType: vehicle.bodyType, confidence: vehicle.confidence, snapshotId: id, box: vehicleBox, plateBox },
});
this.#logger.debug(`anpr-bridge: pass sample ${id} '${vehicle.bodyType}' (${vehicle.confidence.toFixed(3)}) from ${deviceId}`);
} catch (err) {
this.#logger.warn(`anpr-bridge: pass sample failed for ${deviceId}: ${(err as Error).message}`);
}
}
/** Advisory telemetry: a plate was read at the lane but matched no subscription. Not a
+3
View File
@@ -114,6 +114,9 @@ export interface PlateRecognizedEvent {
export interface VehicleReadEvent {
readonly identity: string;
readonly direction: "entry" | "exit";
/** The camera that took the frame, so a listener can tell "same car, two reads seconds
* apart" (the bridge's pass sample + the ticket entry's read) from two cars. */
readonly deviceId?: string;
readonly read: VehicleRead;
}
+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`);
+38
View File
@@ -111,6 +111,44 @@ describe("exitForBooth — valid exit signs the vehicle_exit", () => {
});
});
describe("forgiven exit (wiki/decisions/forgiven-exit.md)", () => {
function payments(identity: string) {
return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all().filter((r) => r.type === "payment");
}
it("ticketed car: $0 payment carrying the forgone fee, then the exit is signed with the forgiven reason", async () => {
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 });
await enter("T1", minutesAgo(90)); // 2 increments → 20000 owed
const f = await pay.forgive("T1", { operator: "owner", note: "regular customer, printer jammed" });
expect(f).toMatchObject({ ok: true, forgoneMinor: 20000 });
const p = payments("T1");
expect(p).toHaveLength(1);
expect(p[0]!.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" });
expect((p[0]!.payload as { reason: string }).reason).toContain("regular customer, printer jammed");
// Even with a 0-minute walk-back grace, the forgiven re-open goes through.
const r = await exit.reopenBarrier("T1", "owner", { forgiven: { note: "regular customer, printer jammed", forgoneMinor: 20000, currency: "ALL" } });
expect(r.ok).toBe(true);
expect(exitsSigned("T1")).toHaveLength(1);
expect(exitsSigned("T1")[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven" });
expect(anomalies("manual exit by owner")).toHaveLength(1);
expect(anomalies("manual exit by owner")[0]!.payload).toMatchObject({ forgiven: true, forgoneMinor: 20000, operator: "owner" });
// The plain unpaid re-open path is still refused for the NEXT unpaid car.
await enter("T2", minutesAgo(90));
expect((await exit.reopenBarrier("T2", "owner")).ok).toBe(false);
});
it("no session: a signed anomaly under a fresh forgiven:<id> ref, no exit, no payment", async () => {
const r = await exit.forgiveExitNoSession("owner", "came in while the barriers were up");
expect(r.ok).toBe(true);
const a = anomalies("no ticket / no session");
expect(a).toHaveLength(1);
expect(a[0]!.identity).toMatch(/^forgiven:/);
expect(a[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", forgiven: true, operator: "owner" });
expect(db.select().from(ledgerEvents).all().filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0);
});
});
describe("reopenBarrier — no unpaid re-open", () => {
it("refuses to re-open an unpaid transient session", async () => {
seedTariff(db, { pricePerIncrementMinor: 10000 });
+112 -25
View File
@@ -1,5 +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";
@@ -63,6 +65,14 @@ export type BoothReopenResult =
| { ok: false; reason: string }
| { ok: true; opened: boolean; reason?: string };
/** A forgiven exit's audit facts (wiki/decisions/forgiven-exit.md): the operator's
* mandatory free-text note and the fee the $0 payment just waived. */
export interface ForgivenExit {
readonly note: string;
readonly forgoneMinor: number;
readonly currency: string;
}
/** Minimum ANPR confidence for a plate to participate in swap reconciliation, both for the
* exiting read and the matched open session's entry read. Below this, the read is advisory-
* only and never triggers a swap warning (a fuzzy read must not block a legit car). */
@@ -201,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") };
@@ -234,9 +249,10 @@ export class ExitFlow {
* second exit (that would double-count occupancy): anomaly only, as before.
* See wiki/concepts/booth-exit-flow.md.
*/
async reopenBarrier(identity: string, operator?: string): Promise<BoothReopenResult> {
async reopenBarrier(identity: string, operator?: string, opts?: { forgiven?: ForgivenExit }): Promise<BoothReopenResult> {
const id = identity.trim();
if (!id) return { ok: false, reason: "ticket id required" };
const forgiven = opts?.forgiven ?? null;
const view = this.#sessionFor(id);
if (!view) return { ok: false, reason: "no session for ticket" };
@@ -251,7 +267,10 @@ export class ExitFlow {
const paid = view.paidAt != null;
const withinGrace =
paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
if (!view.subscription && (!paid || !withinGrace)) {
// FORGIVEN exit (barrier:create): the $0 payment carrying the forgone fee was just
// signed by PayStation.forgive(); the walk-back check is moot (and a 0-minute grace
// tariff must not refuse it). The audit lives on the anomaly + exit below.
if (!forgiven && !view.subscription && (!paid || !withinGrace)) {
return {
ok: false,
reason: paid ? "walk-back grace expired — take a top-up payment first" : "session not paid — no barrier open without payment",
@@ -269,9 +288,10 @@ export class ExitFlow {
type: "anomaly",
identity: id,
payload: {
...reasonPayload("exit.manualOpen"),
...(forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : reasonPayload("exit.manualOpen")),
source: "booth",
barrierReopen: true,
...(forgiven ? { forgiven: true, forgoneMinor: forgiven.forgoneMinor, currency: forgiven.currency } : {}),
...(operator ? { operator } : {}),
},
});
@@ -280,34 +300,92 @@ export class ExitFlow {
// session leaves the active list + occupancy settles. Skip when already exited
// (no double-count). Recorded as a human-intervention exit for the audit trail.
if (view.open) {
await this.#signExit(id, "manual");
await this.#signExit(id, "manual", forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : undefined);
this.#closeSessionCache(id);
this.#fireExitSnapshot(id);
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
}
if (!resolved) {
this.#logger.warn(`barrier re-open for ${id}: no exit relay configured`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
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}` : ""}`);
}
const access = this.#buildAccess(resolved.controller);
if (!access) {
this.#logger.warn(`barrier re-open for ${id}: exit controller would not build`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
}
try {
await access.pulseOpen(resolved.relay);
} catch (err) {
this.#logger.error(`barrier re-open pulseOpen failed (${id}): ${(err as Error).message}`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
}
this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
return { ok: true, opened: true };
return r;
} finally {
this.#inFlight.delete(key);
}
}
/**
* FORGIVEN exit for a car with NO ticket / no session (it came in while the barriers
* were up, lost everything, …). Nothing to forgive and nothing to close: a signed,
* attributed anomaly with the exit snapshot as evidence, then the pulse. The anomaly's
* identity is a fresh `forgiven:<id>` ref so the live feed can show its snapshot.
* See wiki/decisions/forgiven-exit.md.
*/
async forgiveExitNoSession(operator: string, note: string): Promise<BoothReopenResult> {
const key = "forgive:nosession";
if (this.#inFlight.has(key)) return { ok: false, reason: "a forgiven open is already in progress" };
this.#inFlight.add(key);
try {
const ref = `forgiven:${randomUUID()}`;
const resolved = firstRelayByDirection(this.#db, "exit");
await this.#log.append({
type: "anomaly",
identity: ref,
payload: {
...reasonPayload("exit.forgiven.noSession", { operator, note: note || "(no reason given)" }),
source: "booth",
barrierReopen: true,
forgiven: true,
operator,
},
});
this.#fireExitSnapshot(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 {
this.#inFlight.delete(key);
}
}
/** 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,
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") };
}
const access = this.#buildAccess(resolved.controller);
if (!access) {
this.#logger.warn(`${label}: exit controller would not build`);
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
}
try {
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") };
}
return { ok: true, opened: true };
}
#forgivenParams(operator: string | undefined, f: ForgivenExit): Record<string, string | number> {
return { operator: operator ?? "?", forgone: (f.forgoneMinor / 100).toFixed(2), currency: f.currency, note: f.note || "(no reason given)" };
}
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
* read dispatcher from the reader's binding, which has ruled out a subscription match). */
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
@@ -411,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);
@@ -422,7 +505,11 @@ export class ExitFlow {
/** Append the signed vehicle_exit. `source`: "ticket" (booth/reader), "lpr" (plate),
* or "manual" (a human-intervention barrier re-open that closes an open session —
* see reopenBarrier). */
async #signExit(identity: string, source: "ticket" | "lpr" | "manual" = "ticket"): Promise<void> {
async #signExit(
identity: string,
source: "ticket" | "lpr" | "manual" = "ticket",
reason?: ReturnType<typeof reasonPayload>,
): Promise<void> {
await this.#log.append({
type: "vehicle_exit",
direction: "exit",
@@ -430,7 +517,7 @@ export class ExitFlow {
identity,
payload: {
sessionRef: identity,
...(source === "manual" ? reasonPayload("exit.manualOpen") : {}),
...(reason ?? (source === "manual" ? reasonPayload("exit.manualOpen") : {})),
},
});
}
+1 -1
View File
@@ -23,7 +23,7 @@ export const carwashModule: ServerModule = {
// training material (the gate view, no order attached). The core announces the read;
// the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set.
const offVehicleRead = deviceEvents.onVehicleRead((e) => {
if (e.direction === "entry" && outbox.sampleEntry()) void outbox.enqueueEntry(e.read);
if (e.direction === "entry" && outbox.sampleEntry(e.deviceId)) void outbox.enqueueEntry(e.read);
});
app.addHook("onClose", async () => offVehicleRead());
app.addHook("onClose", async () => outbox.stop());
@@ -6,7 +6,7 @@ import type { FastifyInstance } from "fastify";
import { deviceEvents as deviceEventBus } from "../../device-events.js";
import { buildServer } from "../../server.js";
import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js";
import { EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
import { ENTRY_DEDUP_MS, EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
// The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred
// vehicle crop + the operator's choice, queued off the intake path, drained one-way with
@@ -165,6 +165,20 @@ describe("queue + drain", () => {
const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn);
expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]);
expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off
// Per-camera dedup: the bridge's pass sample and the ticket entry's read, seconds
// apart from the same camera, are ONE car — the second is skipped and not counted.
vi.useFakeTimers();
try {
const every = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 1 }, fetchFn);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry("cam-a")).toBe(false);
expect(every.sampleEntry("cam-b")).toBe(true); // another camera = another car
vi.advanceTimersByTime(ENTRY_DEDUP_MS + 1);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry()).toBe(true); // camera unknown → no dedup
} finally {
vi.useRealTimers();
}
expect(await sampler.enqueueEntry(read)).toBe(true);
const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!;
expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } });
@@ -63,6 +63,9 @@ const CROP_MARGIN = 0.08;
/** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks
* should not resurface a fortnight of crops in one burst. */
export const EXPIRE_DAYS = 14;
/** Two entry reads from the same camera closer than this are one car (the ANPR bridge's
* per-detection pass sample, then the ticket entry's session-tied read ~seconds later). */
export const ENTRY_DEDUP_MS = 30_000;
/** Backoff: 1 min · 2^attempts, capped. */
const BACKOFF_BASE_MS = 60_000;
const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000;
@@ -166,6 +169,9 @@ export class ReviewOutbox {
#timer: NodeJS.Timeout | null = null;
#draining = false;
#entrySeen = 0;
/** Last entry sample per camera: the bridge's pass sample and the ticket entry's read are
* the SAME car seconds apart — one goes, the other is skipped (and not counted). */
readonly #lastEntryByDevice = new Map<string, number>();
constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) {
this.#db = db;
@@ -202,9 +208,15 @@ export class ReviewOutbox {
/** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted
* in-process, so "1 in 5" is exactly that across a booth's day. */
sampleEntry(): boolean {
sampleEntry(deviceId?: string): boolean {
const n = this.#cfg?.entrySample ?? 0;
if (n <= 0) return false;
if (deviceId) {
const now = Date.now();
const last = this.#lastEntryByDevice.get(deviceId);
if (last != null && now - last < ENTRY_DEDUP_MS) return false;
this.#lastEntryByDevice.set(deviceId, now);
}
this.#entrySeen += 1;
return this.#entrySeen % n === 0;
}
+18
View File
@@ -28,6 +28,24 @@ async function enter(identity: string, enteredAt: string, payload?: Record<strin
await log.append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: enteredAt, payload: payload ?? null });
}
describe("PayStation.forgive (forgiven exit)", () => {
it("signs a $0 payment with the quoted fee as forgoneMinor and marks the session paid", async () => {
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
await enter("T1", minutesAgo(90));
const r = await pay.forgive("T1", { operator: "owner", note: "lost ticket, known customer" });
expect(r).toEqual({ ok: true, forgoneMinor: 20000, currency: expect.any(String) });
const ev = db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, "T1")).all().find((e) => e.type === "payment")!;
expect(ev.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" });
expect((ev.payload as { tender?: string }).tender).toBeUndefined(); // nothing was tendered
expect(pay.lookup("T1").paidAt).not.toBeNull();
});
it("throws like quote() for an unknown ticket", async () => {
seedTariff(db);
await expect(pay.forgive("nope", { operator: "owner", note: "x" })).rejects.toThrow(NoOpenSessionError);
});
});
describe("PayStation.quote", () => {
it("throws NoOpenSessionError for an unknown ticket", () => {
seedTariff(db);
+48 -1
View File
@@ -1,5 +1,5 @@
import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db";
import { BOOTH_TILL, priceSession, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared";
import { BOOTH_TILL, priceSession, reasonPayload, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import type { EventLog } from "./event-log.js";
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
@@ -373,6 +373,53 @@ export class PayStation {
return { amountMinor, currency: q.currency };
}
/**
* FORGIVEN EXIT (wiki/decisions/forgiven-exit.md): the owner lets a ticketed car out
* with no money. Signs a ZERO-amount payment that carries the fee the car owed as
* `forgoneMinor`, so the shift's cash/card/drawer are untouched by construction while
* the Z-report shows the forgone amount as its own line; the exit that follows closes
* the ticket (no reuse). Refused when the quote carries module charge lines (a wash on
* the ticket): parking is forgiven, a wash is not — settle it first. Throws
* NoOpenSessionError / NoTariffError like `quote()`.
*/
async forgive(
identity: string,
opts: { operator: string; note: string },
): Promise<{ ok: true; forgoneMinor: number; currency: string } | { ok: false; reason: string }> {
const q = this.quote(identity);
if (q.chargesMinor > 0) {
return { ok: false, reason: "ticket carries a module charge (e.g. a wash) — settle it first; only parking can be forgiven" };
}
await this.#log.append({
type: "payment",
source: "manual",
identity,
payload: {
sessionRef: identity,
amountMinor: 0,
forgoneMinor: q.amountMinor,
currency: q.currency,
till: BOOTH_TILL,
tariffVersionId: q.tariffVersionId,
graceExitMin: q.graceExitMin,
operator: opts.operator,
...reasonPayload("exit.forgiven", {
operator: opts.operator,
forgone: (q.amountMinor / 100).toFixed(2),
currency: q.currency,
note: opts.note || "(no reason given)",
}),
},
});
try {
this.#db.update(sessions).set({ state: "paid" }).where(eq(sessions.id, identity)).run();
} catch (err) {
this.#logger.error(`session-cache mark-paid failed for ${identity}: ${(err as Error).message}`);
}
this.#logger.warn(`FORGIVEN exit for ${identity} by ${opts.operator}: ${q.amountMinor} ${q.currency} waived — ${opts.note}`);
return { ok: true, forgoneMinor: q.amountMinor, currency: q.currency };
}
/**
* One-read session view for the booth pay/exit modal: entry/exit times, paid
* state, amount owed now, and walk-back-grace status. Read-only — folds the
+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}`);
}
}
+78
View File
@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { buildServer } from "./server.js";
// Request logging shape (2026-10-08 noise cut, wiki/concepts/app-logs.md §Noise cut):
// - /health logs NOTHING (Docker probes it every 30 s — it was half a quiet booth's log),
// - every other request logs ONE line "METHOD url → status Nms" (not pino's two),
// - a handler failure still logs the error with its stack, because
// `disableRequestLogging` also silences Fastify's default error-handler logging.
// The logger's stream is process.stdout (pinoDbStream tees warn+ into app_logs), so
// capture stdout writes and look at the JSON lines.
const lines: Record<string, unknown>[] = [];
let restore: (() => void) | null = null;
function captureStdout() {
const spy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
for (const l of text.split("\n")) {
if (!l.trim()) continue;
try {
lines.push(JSON.parse(l));
} catch {
/* non-JSON stdout noise — ignore */
}
}
return true;
}) as typeof process.stdout.write);
restore = () => spy.mockRestore();
}
afterEach(() => {
restore?.();
restore = null;
lines.length = 0;
});
const msgs = () => lines.map((l) => String(l.msg ?? ""));
describe("request logging", () => {
it("/health is silent; other requests log exactly one line; 5xx keeps the error", async () => {
const t = createTestDb();
captureStdout();
// vitest.config forces LOG_LEVEL=silent for every test; this one needs the real level.
const prevLevel = process.env.LOG_LEVEL;
process.env.LOG_LEVEL = "info";
const app = await buildServer({ db: t.db });
process.env.LOG_LEVEL = prevLevel;
app.get("/boom", async () => {
throw new Error("kaboom");
});
await app.ready();
try {
lines.length = 0; // drop startup lines
expect((await app.inject({ method: "GET", url: "/health" })).statusCode).toBe(200);
expect(msgs().filter((m) => m.includes("/health"))).toEqual([]);
expect((await app.inject({ method: "GET", url: "/api/nope" })).statusCode).toBe(404);
const notFound = msgs().filter((m) => m.includes("/api/nope"));
expect(notFound).toHaveLength(1);
expect(notFound[0]).toMatch(/^GET \/api\/nope → 404 \d+ms$/);
expect(msgs().some((m) => /incoming request|request completed/.test(m))).toBe(false);
expect((await app.inject({ method: "GET", url: "/boom" })).statusCode).toBe(500);
const boom = lines.filter((l) => String(l.msg).includes("/boom"));
// one error line (with the err object) + the one-line request summary
expect(boom.map((l) => [l.level, String(l.msg).replace(/\d+ms/, "Nms")])).toEqual([
["error", "GET /boom failed: kaboom"],
["info", "GET /boom → 500 Nms"],
]);
expect((boom[0]!.err as { message?: string })?.message).toBe("kaboom");
} finally {
await app.close();
t.close();
}
});
});
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { createTestDb } from "@parking/db/testing";
import { ledgerEvents, eq, type Db } from "@parking/db";
import { buildServer } from "../server.js";
import { login, makeLog, minutesAgo, seedTariff, seedUser } from "../test-helpers.js";
// HTTP integration for the FORGIVEN exit (wiki/decisions/forgiven-exit.md): the route is
// gated on `barrier:create` (admin by default, grantable per role), needs an open shift
// and a reason, and signs a $0 payment carrying the forgone fee + the exit. Drives the
// REAL app over a fresh in-memory DB via app.inject.
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
});
afterEach(async () => {
await app.close();
close();
});
async function as(opts: { username: string; roleId?: string; permissions?: Parameters<typeof seedUser>[1]["permissions"] }) {
const { username, password } = await seedUser(db, opts);
const { cookie, csrf } = await login(app, username, password);
return { cookie, "x-csrf-token": csrf };
}
async function enter(identity: string) {
await makeLog(db).append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: minutesAgo(90), payload: null });
}
function events(identity: string) {
return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all();
}
describe("POST /api/barrier/forgive", () => {
it("is refused without barrier:create (an operator who can take payment but was not granted it)", async () => {
const h = await as({ username: "op", roleId: "operator", permissions: ["payment:create", "session:read", "shift:create"] });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
await enter("T1");
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "friend" } });
expect(r.statusCode).toBe(403);
expect(events("T1").map((e) => e.type)).toEqual(["vehicle_entry"]);
});
it("a role the owner granted barrier:create can forgive; the reason is optional; a shift must be open", async () => {
const h = await as({ username: "trusted", roleId: "senior", permissions: ["payment:create", "session:read", "shift:create", "shift:read", "barrier:create"] });
await enter("T1");
// No shift yet → the money-path gate refuses.
let r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "x" } });
expect(r.statusCode).toBe(409);
expect(r.json()).toMatchObject({ code: "no_shift" });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
// Forgiven: $0 payment with the fee as forgone, then the exit. No relay configured →
// ok:true, opened:false with the open-by-hand reason (the ledger side is complete).
r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "known customer, lost ticket" } });
expect(r.statusCode).toBe(200);
expect(r.json()).toMatchObject({ ok: true, opened: false, forgoneMinor: 20000 });
const types = events("T1").map((e) => e.type);
expect(types).toEqual(["vehicle_entry", "payment", "anomaly", "vehicle_exit"]);
const payment = events("T1").find((e) => e.type === "payment")!;
expect(payment.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "trusted", reasonCode: "exit.forgiven" });
// The Z-report carries it as its own line, and the takings stay at zero.
const rep = (await app.inject({ method: "GET", url: "/api/shift/report", headers: h })).json() as Record<string, unknown>;
expect(rep).toMatchObject({ cashTotalMinor: 0, cardTotalMinor: 0, forgoneTotalMinor: 20000, forgoneCount: 1 });
});
it("no ticket, no reason: admin opens the exit for a car with no session → anomaly only, readable sentence", async () => {
const h = await as({ username: "boss", roleId: "admin" });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: {} });
expect(r.statusCode).toBe(200);
const all = db.select().from(ledgerEvents).all();
const anomaly = all.find((e) => e.type === "anomaly")!;
expect(anomaly.identity).toMatch(/^forgiven:/);
expect(anomaly.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", operator: "boss" });
expect((anomaly.payload as { reason: string }).reason).toContain("(no reason given)");
expect(all.filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0);
});
});
+5 -3
View File
@@ -159,9 +159,11 @@ export async function hikvisionAlarmRoutes(
const contentType = String(req.headers["content-type"] ?? "");
const raw: Buffer = Buffer.isBuffer(req.body) ? (req.body as Buffer) : Buffer.from("");
const summary = summarize(raw.toString("utf8"));
// Log EVERY hit immediately (method + ip + size), before any guard — so even a probe
// that gets rejected is visible in the dev log the instant it arrives.
app.log.info(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
// Log EVERY hit immediately (method + ip + size), before any guard — so under
// LOG_LEVEL=debug even a probe that gets rejected is visible the instant it arrives.
// debug, not info: every accepted hit is followed by the ACCEPTED line (which carries
// all of this plus the verdict) and every rejected one by the REJECTED warn.
app.log.debug(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
// Guard: must be a known hikvision device with alarm-push enabled, posting from its
// configured host IP. Source-IP is the primary guard on the LAN (like the Dingtian).
+32
View File
@@ -60,6 +60,7 @@ export async function payRoutes(
const guard = requirePermission("payment:create");
const readGuard = requirePermission("session:read");
const voidGuard = requirePermission("event:void");
const forgiveGuard = requirePermission("barrier:create");
// Money-path gate: a shift must be open site-wide before any payment/exit/voucher/
// re-open is processed, so every taking is attributed to a shift (one operator's
@@ -144,6 +145,37 @@ export async function payRoutes(
},
);
// FORGIVEN exit (wiki/decisions/forgiven-exit.md): an operator holding barrier:create
// lets a car out with NO money. With a ticket: PayStation.forgive signs a $0 payment
// carrying the forgone fee (never in cash/card), then the human-intervention re-open
// signs the exit + pulses. Without a ticket: anomaly + snapshot + pulse. A free-text
// reason is OPTIONAL (user, 2026-10-09 — the signature + snapshot + Z-report line are
// the accountability); an open shift is required so it lands on someone's Z-report.
// Prints nothing.
app.post<{ Body: { identity?: string; note?: string } }>(
"/api/barrier/forgive",
{ preHandler: [forgiveGuard, requireShift] },
async (req, reply) => {
const note = (req.body?.note ?? "").trim();
const identity = (req.body?.identity ?? "").trim();
const operator = req.user?.username ?? "?";
if (!identity) {
const r = await exitFlow.forgiveExitNoSession(operator, note);
if (!r.ok) return reply.code(409).send({ error: r.reason });
return reply.code(200).send(r);
}
try {
const f = await payStation.forgive(identity, { operator, note });
if (!f.ok) return reply.code(409).send({ error: f.reason });
const r = await exitFlow.reopenBarrier(identity, operator, { forgiven: { note, forgoneMinor: f.forgoneMinor, currency: f.currency } });
if (!r.ok) return reply.code(409).send({ error: r.reason });
return reply.code(200).send({ ...r, forgoneMinor: f.forgoneMinor, currency: f.currency });
} catch (err) {
return mapError(reply, err);
}
},
);
// Cancel (void) a wrongly-printed transient ticket. Appends a SIGNED `void` event
// referencing the entry, with the operator + a REQUIRED reason — the entry itself is
// never edited/deleted (append-only). The session projection folds the void to CLOSED,
+47 -27
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,
@@ -191,31 +192,44 @@ async function configureDevice(
if (hasPushConfig(device)) {
const host = String(config.host ?? "");
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
const pushHost = backendIp ?? backendIpForDevice(host);
if (!pushHost) {
return {
error: {
code: 400,
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
},
};
if (!host) {
// Only reachable for a push device whose host is OPTIONAL (the DT-008 reader:
// scans resolve by serial, the IP is what lets us configure it). Nothing to talk
// to → save, but say so: the reader must then be set up by hand.
hardenWarnings.push(
"no IP given — the reader was NOT configured: set its output type to HTTP and its server to this booth with the vendor tool (or add its IP here and save again)",
);
} else {
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
const pushHost = backendIp ?? backendIpForDevice(host);
if (!pushHost) {
return {
error: {
code: 400,
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
},
};
}
const pushUser = "dingtian";
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
// (longer is silently truncated → auth mismatch), so keep it short.
const pushPassword = randomBytes(12).toString("hex");
await device.configureInputPush({
host: pushHost,
port: backendPort(),
pathBase: `/api/devices/${driverId}/${id}/input`,
auth: { user: pushUser, password: pushPassword },
});
// A device whose push carries no credentials (the DT-008 scan GET) has no use
// for these — don't persist a secret nothing checks.
if (device.usesPushAuth !== false) {
fullConfig.pushUser = pushUser;
fullConfig.pushPassword = pushPassword;
}
// Record the backend IP the device was told to push to — lets us detect
// a later mismatch if the host's IP changes.
fullConfig.backendIp = pushHost;
}
const pushUser = "dingtian";
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
// (longer is silently truncated → auth mismatch), so keep it short.
const pushPassword = randomBytes(12).toString("hex");
await device.configureInputPush({
host: pushHost,
port: backendPort(),
pathBase: `/api/devices/${driverId}/${id}/input`,
auth: { user: pushUser, password: pushPassword },
});
fullConfig.pushUser = pushUser;
fullConfig.pushPassword = pushPassword;
// Record the backend IP the device was told to push to — lets us detect
// a later mismatch if the host's IP changes.
fullConfig.backendIp = pushHost;
}
} catch (err) {
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
@@ -231,7 +245,7 @@ export async function setupRoutes(
eventLog?: EventLog | null,
): Promise<void> {
registerBuiltinDrivers();
setDeviceLogSink((line) => app.log.info(line));
setDeviceLogSink((line, level) => app.log[level](line));
// Device setup is site administration — it changes which hardware the site runs
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
@@ -494,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}` });
}
@@ -532,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.
+22 -1
View File
@@ -82,6 +82,25 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
formatters: { level: (label) => ({ level: label }) },
stream: pinoDbStream(logService, process.stdout),
},
// ONE line per request (the onResponse hook below) instead of Fastify's default
// "incoming request" + "request completed" pair — on a quiet booth the pair was
// most of the log. NB: with this flag Fastify's default error handler ALSO stops
// logging handler errors, so the onError hook below re-adds that for 5xx.
disableRequestLogging: true,
});
// Request log, one line: method, url, status, elapsed. Routes declared with
// `logLevel: "silent"` (the /health probe) are skipped because `req.log` is theirs.
app.addHook("onResponse", async (req, reply) => {
req.log.info(`${req.method} ${req.url} → ${reply.statusCode} ${Math.round(reply.elapsedTime)}ms`);
});
// Handler failures (5xx) keep their stack in the log — disableRequestLogging would
// otherwise swallow them (fastify/lib/error-handler.js checks the same flag).
app.addHook("onError", async (req, _reply, err) => {
// onError runs BEFORE the error handler sets the reply status, so the reply still
// says 200 here; an error without its own statusCode is a 500 by definition.
const code = (err as { statusCode?: number }).statusCode ?? 500;
if (code >= 500) req.log.error({ err }, `${req.method} ${req.url} failed: ${err.message}`);
});
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
@@ -109,7 +128,9 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// Unauthenticated liveness probe. `app` lets a client (the desktop ConnectScreen
// test — apps/web/src/lib/backend-config.ts) tell THIS server apart from any
// other service that happens to answer on the address the operator typed.
app.get("/health", async () => ({ status: "ok", app: "parking-system" }));
// `logLevel: "silent"`: Docker's HEALTHCHECK hits this every 30 s; logging each
// probe was half of a quiet booth's output (park-2, 2026-10-08).
app.get("/health", { logLevel: "silent" }, async () => ({ status: "ok", app: "parking-system" }));
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
await authRoutes(app, db);
+27 -2
View File
@@ -34,12 +34,14 @@ afterEach(() => close());
/** Append a signed payment with source-split flags, as the booth/pay paths do. */
async function payment(
amountMinor: number,
opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean } = {},
opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean; forgoneMinor?: number } = {},
) {
await log.append({
type: "payment", source: "manual", identity: "T",
payload: {
sessionRef: "T", amountMinor, currency: "ALL", tender: opts.tender ?? "cash",
sessionRef: "T", amountMinor, currency: "ALL",
// A forgiven exit's $0 payment carries no tender (nothing was tendered).
...(opts.forgoneMinor != null ? { forgoneMinor: opts.forgoneMinor } : { tender: opts.tender ?? "cash" }),
...(opts.subscriptionSale ? { subscriptionSale: true } : {}),
...(opts.subscriptionWindowCharge ? { subscriptionWindowCharge: true } : {}),
},
@@ -74,6 +76,29 @@ describe("single-open invariant", () => {
});
});
describe("forgiven exits on the Z-report", () => {
it("a $0 forgiven payment adds nothing to cash/card/drawer and is reported as its own line", async () => {
await shift.open("alice");
await payment(10000); // a real ticket, cash
await payment(0, { forgoneMinor: 25000 });
await payment(0, { forgoneMinor: 5000 });
const r = shift.currentReport()!;
expect(r.cashTotalMinor).toBe(10000);
expect(r.cardTotalMinor).toBe(0);
expect(r.ticketTotalMinor).toBe(10000);
expect(r.forgoneTotalMinor).toBe(30000);
expect(r.forgoneCount).toBe(2);
expect(r.discountTotalMinor).toBe(0); // not a merchant validation
expect(r.expectedDrawerMinor).toBe(r.openingFloatMinor + 10000);
const closed = await shift.close("alice");
expect(closed).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2, cashTotalMinor: 10000 });
const hist = shift.listShifts();
expect(hist[0]).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2 });
});
});
describe("takings split by source", () => {
it("separates subscription sales, out-of-window charges, and transient tickets", async () => {
await shift.open("alice");
+27
View File
@@ -71,6 +71,8 @@ export interface ShiftSummary {
readonly subscriptionSalesMinor: number;
readonly subscriptionWindowMinor: number;
readonly discountTotalMinor: number;
readonly forgoneTotalMinor: number;
readonly forgoneCount: number;
readonly chargesByModuleMinor: ChargesByModule;
readonly openingFloatMinor: number;
readonly cashAddedMinor: number;
@@ -105,6 +107,10 @@ export interface ShiftReport {
/** Merchant-validation DISCOUNT total given away in the window (leakage — the
* cash/card figures above are already NET of it). See validation-discounts.md. */
readonly discountTotalMinor: number;
/** FORGIVEN exits (wiki/decisions/forgiven-exit.md): fees waived by an operator holding
* barrier:create, and how many. $0 payments — never inside cash/card; its own line. */
readonly forgoneTotalMinor: number;
readonly forgoneCount: number;
/** Module charges settled on this till's payments (a booth-paid wash), by module. */
readonly chargesByModuleMinor: ChargesByModule;
// --- Drawer (physical cash till; carries across shifts) ---
@@ -266,6 +272,8 @@ export class ShiftService {
subscriptionSalesMinor?: number;
subscriptionWindowMinor?: number;
discountTotalMinor?: number;
forgoneTotalMinor?: number;
forgoneCount?: number;
chargesByModuleMinor?: ChargesByModule;
openingFloatMinor?: number;
cashAddedMinor?: number;
@@ -302,6 +310,9 @@ export class ShiftService {
(pl.cashTotalMinor ?? 0) + (pl.cardTotalMinor ?? 0) - (pl.subscriptionTotalMinor ?? 0),
// Merchant-validation leakage (added 2026-07-13). Old reports lack it → 0.
discountTotalMinor: pl.discountTotalMinor ?? 0,
// Forgiven exits (added 2026-10-08). Old reports lack it → 0.
forgoneTotalMinor: pl.forgoneTotalMinor ?? 0,
forgoneCount: pl.forgoneCount ?? 0,
// Module charges on the ticket (added 2026-09-06). Old reports lack it → none.
chargesByModuleMinor: pl.chargesByModuleMinor ?? {},
openingFloatMinor: pl.openingFloatMinor ?? 0,
@@ -599,6 +610,10 @@ export class ShiftService {
// Merchant-validation leakage: Σ discountMinor across the window's payments. The
// tender totals are already NET; this is the "given away" figure beside them.
let discountTotalMinor = 0;
// Forgiven exits: $0 payments whose `forgoneMinor` is the fee waived. Not money —
// the tender sums above add 0 for them; this is the "let out for free" figure.
let forgoneTotalMinor = 0;
let forgoneCount = 0;
// Module charges folded into this till's payments (chargeLines on a booth payment),
// summed by owning module. Part of cash/card; NOT ticket money.
const chargesByModuleMinor: ChargesByModule = {};
@@ -617,6 +632,10 @@ export class ShiftService {
else if (pl.subscriptionWindowCharge === true) subscriptionWindowMinor += amt;
// (else → transient ticket; derived below as total − subscription)
if (typeof pl.discountMinor === "number") discountTotalMinor += pl.discountMinor;
if (typeof pl.forgoneMinor === "number") {
forgoneTotalMinor += pl.forgoneMinor;
forgoneCount += 1;
}
for (const l of pl.chargeLines ?? []) {
if (typeof l.amountMinor !== "number" || !l.module) continue;
chargesByModuleMinor[l.module] = (chargesByModuleMinor[l.module] ?? 0) + l.amountMinor;
@@ -682,6 +701,8 @@ export class ShiftService {
subscriptionSalesMinor,
subscriptionWindowMinor,
discountTotalMinor,
forgoneTotalMinor,
forgoneCount,
chargesByModuleMinor,
openingFloatMinor,
cashAddedMinor,
@@ -723,6 +744,8 @@ export class ShiftService {
subscriptionSalesMinor,
subscriptionWindowMinor,
discountTotalMinor,
forgoneTotalMinor,
forgoneCount,
chargesByModuleMinor,
openingFloatMinor,
cashAddedMinor,
@@ -748,6 +771,8 @@ export class ShiftService {
subscriptionSalesMinor,
subscriptionWindowMinor,
discountTotalMinor,
// Forgiven exits — only when any happened (older payloads stay identical).
...(forgoneCount > 0 ? { forgoneTotalMinor, forgoneCount } : {}),
// Only when a module charged in the window (older slips/payloads stay identical).
...(Object.keys(chargesByModuleMinor).length ? { chargesByModuleMinor } : {}),
openingFloatMinor,
@@ -806,6 +831,8 @@ export class ShiftService {
// Merchant-validation leakage — printed only when the shift actually gave any
// (older slips stay byte-identical). The takings above are already NET of it.
...(r.discountTotalMinor > 0 ? [`Zbritje (validime): ${money(r.discountTotalMinor)} ${cur}`] : []),
// Forgiven exits — fees waived by an operator; $0 payments, NOT in the takings.
...(r.forgoneCount > 0 ? [`Dalje manuale (${r.forgoneCount}): ${money(r.forgoneTotalMinor)} ${cur}`] : []),
"",
"-- Arka --",
`Gjëndje fillestare: ${money(r.openingFloatMinor)} ${cur}`,
+25 -12
View File
@@ -2,12 +2,12 @@ import { randomUUID } from "node:crypto";
import sharp from "sharp";
import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
import { registry, type CameraDevice, type Snapshot } from "@parking/devices";
import { reasonPayload } from "@parking/shared";
import { reasonPayload, type NormBox } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
import { deviceEvents } from "./device-events.js";
import type { EventLog } from "./event-log.js";
import type { VisionClient } from "./vision-client.js";
import type { VisionClient, VisionResult } from "./vision-client.js";
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
@@ -171,23 +171,16 @@ async function recognizePlate(
// Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a
// downscaled copy — see reencodeForStorage), so the wash's review crop can cut the
// vehicle out of whatever copy survives and blur the plate inside it.
const frame = await frameSize(shot.bytes);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined) =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
const boxes = await normalizedBoxes(shot.bytes, result);
// The vehicle's body type (advisory; the wash desk's category suggestion — see
// venue-modules.md §Vehicle category). Rides the plate's read row when there is one,
// else a row of its own: a car with an unreadable plate is still a car of some class.
const vehicleBox = norm(result.vehicle?.bbox);
const vehicleBox = boxes.vehicleBox;
const vehicle = result.vehicle
? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) }
: {};
const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase();
const plateBox = plate ? norm(result.plate?.bbox) : null;
const plateBox = plate ? boxes.plateBox : null;
if (!plate && !result.vehicle) return; // nothing trustworthy to record
db.insert(deviceEventsTable)
.values({
@@ -216,6 +209,7 @@ async function recognizePlate(
deviceEvents.emitVehicleRead({
identity,
direction,
deviceId,
read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox },
});
}
@@ -241,6 +235,25 @@ function clamp01(v: number): number {
return Math.max(0, Math.min(1, v));
}
/** The vehicle's and the plate's boxes as FRACTIONS of the analysed frame (null when the
* stage found none or the frame size is unreadable). Fractions, so the box fits the
* downscaled stored copy the wash's review crop is cut from. Shared by the session-tied
* recognition above and the ANPR bridge's per-car pass sample (anpr-entry.ts). */
export async function normalizedBoxes(
bytes: Buffer,
result: VisionResult,
): Promise<{ vehicleBox: NormBox | null; plateBox: NormBox | null }> {
const frame = await frameSize(bytes);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined): NormBox | null =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
return { vehicleBox: norm(result.vehicle?.bbox), plateBox: norm(result.plate?.bbox) };
}
/** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */
async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {
try {
+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);
+36
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
import sqlite3
import threading
import urllib.error
import urllib.request
@@ -109,3 +110,38 @@ def test_train_job_then_versions_and_report(api) -> None: # type: ignore[no-unt
code, job2 = call("POST", "/jobs", {"kind": "evaluate", "version": "vapi"})
wait_idle(Handler.jobs)
assert call("GET", f"/jobs/{job2['id']}")[1]["status"] == "done"
def test_a_handler_error_is_a_500_json_reply_not_a_dropped_connection(tmp_path: Path) -> None:
"""A collector DB from before the `kind` column (art-docker-station, 2026-09-16): readiness
raised sqlite3.OperationalError, the stdlib server printed the traceback and closed the
socket, and the collector could only say "trainer not reachable: fetch failed". The
handler must answer 500 JSON naming the error instead."""
old = tmp_path / "old"
old.mkdir()
con = sqlite3.connect(old / "collector.sqlite")
con.executescript(
"CREATE TABLE items (id TEXT PRIMARY KEY, booth TEXT NOT NULL, order_ref TEXT NOT NULL,"
" at TEXT NOT NULL, service TEXT NOT NULL, vision_class TEXT NOT NULL,"
" vision_confidence REAL NOT NULL, image_width INTEGER NOT NULL, image_height INTEGER NOT NULL,"
" plate_blurred INTEGER NOT NULL, image_path TEXT NOT NULL, received_at TEXT NOT NULL,"
" review_label TEXT, reviewed_at TEXT, reviewer TEXT)"
)
con.commit()
con.close()
Handler.jobs = Jobs(old, tmp_path / "out", "https://example.invalid/pkg", "tok")
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
try:
req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/readiness")
with pytest.raises(urllib.error.HTTPError) as ei:
urllib.request.urlopen(req, timeout=10)
assert ei.value.code == 500
body = json.loads(ei.value.read())
assert "no such column: kind" in body["error"]
# /health does not touch the DB and still answers.
with urllib.request.urlopen(f"http://127.0.0.1:{httpd.server_address[1]}/health", timeout=10) as r:
assert r.status == 200
finally:
httpd.shutdown()
httpd.server_close()
+21 -1
View File
@@ -309,6 +309,26 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(raw)
def do_GET(self) -> None: # noqa: N802
self._guarded(self._get)
def do_POST(self) -> None: # noqa: N802
self._guarded(self._post)
def _guarded(self, handler: Any) -> None:
"""Run a handler; an unexpected exception becomes a 500 JSON reply instead of a
dropped connection (the stdlib server would print the traceback and close the
socket, which the collector could only report as "fetch failed" — 2026-09-16,
a collector DB from before the `kind` column)."""
try:
handler()
except Exception as exc: # noqa: BLE001 — anything: the reply must be a reply
sys.stderr.write(f"[trainer.serve] {self.command} {self.path}: {type(exc).__name__}: {exc}\n")
try:
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
except Exception: # noqa: BLE001 — headers already sent; nothing left to do
pass
def _get(self) -> None:
path = self.path.split("?", 1)[0]
j = self.jobs
if path == "/health":
@@ -336,7 +356,7 @@ class Handler(BaseHTTPRequestHandler):
else:
self._json(404, {"error": "not found"})
def do_POST(self) -> None: # noqa: N802
def _post(self) -> None:
if self.path.split("?", 1)[0] != "/jobs":
self._json(404, {"error": "not found"})
return
+22
View File
@@ -49,3 +49,25 @@ def test_analyze_rejects_empty_body() -> None:
headers={"content-type": "application/octet-stream"},
)
assert res.status_code == 400
def test_health_access_log_lines_are_dropped() -> None:
import logging
from vision_service.app import DropHealthAccessLog
flt = DropHealthAccessLog()
access = logging.getLogger("uvicorn.access")
# uvicorn's access record: '%s - "%s %s HTTP/%s" %d' with (client, method, path, version, status)
fmt = '%s - "%s %s HTTP/%s" %d'
def record(method: str, path: str) -> logging.LogRecord:
args = ("127.0.0.1:1", method, path, "1.1", 200)
return access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, args, None)
health = record("GET", "/health")
analyze = record("POST", "/analyze")
assert flt.filter(health) is False
assert flt.filter(analyze) is True
# The filter is installed on the live logger at import.
assert any(isinstance(f, DropHealthAccessLog) for f in access.filters)
+18
View File
@@ -8,6 +8,7 @@ advisory, never the sole authority. See wiki/entities/opencv-anpr-service.md.
from __future__ import annotations
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
@@ -34,6 +35,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan)
class DropHealthAccessLog(logging.Filter):
"""Drop uvicorn access-log lines for GET /health.
The probe is hit every 30 s by Docker's HEALTHCHECK and every 8 s by the booth
server's footer chip; on a quiet booth those lines were ~90 % of this container's
output (park-2, 2026-10-08). /analyze and everything else still log.
"""
def filter(self, record: logging.LogRecord) -> bool:
return "/health" not in record.getMessage()
# uvicorn applies its logging config before importing the app, so a filter added here
# survives; dictConfig replaces handlers, not a logger's filters.
logging.getLogger("uvicorn.access").addFilter(DropHealthAccessLog())
# Typed accessors over the untyped `app.state` (so mypy --strict sees the real types).
def _recognizer(request: Request) -> Recognizer:
rec: Recognizer = request.app.state.recognizer
+73
View File
@@ -6,6 +6,7 @@ import {
boothExit,
can,
fetchSiteConfig,
forgiveExit,
lookupSession,
openShift,
paySession,
@@ -61,6 +62,12 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
const { user } = rootRoute.useRouteContext();
const canVoid = can(user, "event:void");
const [voiding, setVoiding] = useState(false); // reason prompt revealed
// FORGIVEN exit (barrier:create; wiki/decisions/forgiven-exit.md): let the car out with
// NO payment. The fee owed is signed as forgone on a $0 payment — on the shift report
// as its own line, never as cash. Reason optional; nothing printed.
const canForgivePerm = can(user, "barrier:create");
const [forgiving, setForgiving] = useState(false); // reason prompt revealed
const [forgiveNote, setForgiveNote] = useState("");
// Plate-swap: set when boothExit returns swap_suspected. Holds the detail for the warning
// panel; the operator must consciously "Override & release". See plate-reconciliation.md.
const [swap, setSwap] = useState<{ plate: string; otherIdentity: string; otherEnteredAt: string | null } | null>(null);
@@ -150,6 +157,31 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
// session (a subscription is closed via its own flow; a paid ticket is a refund). The
// server enforces all of this too; the UI just hides the action when it can't apply.
const canCancel = !!(canVoid && shiftReady && s?.found && s.open && !isSubscription && !alreadyPaid);
// Forgivable = an OPEN transient that owes money now (unpaid, or an overstay top-up).
// A paid-within-grace car takes the plain re-open; a subscriber the assist path.
const canForgive = !!(canForgivePerm && shiftReady && s?.found && s.open && !isSubscription && (!alreadyPaid || isOverstay));
async function handleForgiveExit() {
const note = forgiveNote.trim(); // optional
setError(null);
setPhase("finishing");
try {
const r = await forgiveExit(identity, note);
const amount = formatMoney(r.forgoneMinor ?? 0, r.currency ?? s?.currency ?? "");
setResult(
r.opened
? t("pay.exitForgiven", { amount })
: t("pay.exitForgivenNotOpened", { amount, reason: r.reason ?? t("booth.openManually") }),
);
void qc.invalidateQueries({ queryKey: qk.events });
void qc.invalidateQueries({ queryKey: qk.occupancy });
void qc.invalidateQueries({ queryKey: qk.activeSessions });
setPhase("done");
} catch (e) {
setError((e as Error).message);
setPhase("error");
}
}
async function handleVoidTicket() {
const reason = voidReason.trim();
@@ -556,6 +588,26 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
</div>
)}
{/* Forgiven-exit reason prompt (revealed by the "Forgive & open" button).
Free text, OPTIONAL. Signs a $0 payment carrying the forgone fee, then
the exit + barrier pulse. Nothing is printed. */}
{forgiving && phase !== "done" && (
<div className="rounded-term border border-term-red/50 bg-term-red/5 px-3 py-2">
<div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-term-red">
{t("pay.forgiveTitle")}
</div>
<div className="mt-1 text-[0.75rem] text-term-text">
{t("pay.forgiveHint", { amount: formatMoney(s?.amountMinor ?? 0, s?.currency ?? "") })}
</div>
<input
className="input mt-2 w-full"
value={forgiveNote}
onChange={(e) => setForgiveNote(e.target.value)}
placeholder={t("pay.forgiveReasonPlaceholder")}
/>
</div>
)}
{/* PLATE-SWAP warning: the exiting plate is already inside under another
ticket. A prominent, deliberate hold — the operator must consciously
override to release. See wiki/concepts/plate-reconciliation.md. */}
@@ -661,6 +713,16 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
{t("pay.assistOpenReveal")}
</button>
)
) : forgiving ? (
// Forgiven-exit confirm (reason prompt is shown above).
<button
type="button"
onClick={handleForgiveExit}
disabled={phase === "finishing"}
className="btn btn-danger btn-lg"
>
{phase === "finishing" ? t("pay.forgiving") : t("pay.confirmForgive")}
</button>
) : voiding ? (
// Cancel-ticket confirm (reason prompt is shown above).
<button
@@ -684,6 +746,17 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose
{t("pay.cancelTicket")}
</button>
)}
{/* Forgive the fee and open the exit (barrier:create only). Reveals
the reason prompt above. */}
{canForgive && (
<button
type="button"
onClick={() => setForgiving(true)}
className="btn btn-ghost btn-sm text-term-red"
>
{t("pay.forgiveExit")}
</button>
)}
{swap ? (
// Plate-swap held → the only forward action is a conscious
// override (re-submit with override:true; payment already taken).
+79 -6
View File
@@ -1,12 +1,13 @@
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js";
import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, forgiveExit, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js";
import { rootRoute } from "./router.js";
import { qk } from "./lib/query.js";
import { useLiveStore } from "./lib/live-store.js";
import { useShift } from "./lib/use-shift.js";
import { useScanner } from "./lib/use-scanner.js";
import { Modal } from "./ui/Modal.js";
import { Panel } from "./ui/Panel.js";
import { StatusDot } from "./ui/StatusDot.js";
import { BoothPayModal } from "./BoothPayModal.js";
@@ -130,6 +131,8 @@ function BarrierLight({
issuing,
bypassRadar,
bypassCamera,
onOpen,
opening,
}: {
label: string;
busy: boolean;
@@ -141,6 +144,11 @@ function BarrierLight({
/** Admin bypass of a faulty device: a bypassed signal counts as present (server re-checks). */
bypassRadar?: boolean;
bypassCamera?: boolean;
/** When set (exit light + barrier:create + own shift), clicking opens the manual-exit
* dialog — NOT presence-gated (the car may be anywhere in the lane, or the lane may be
* empty while the operator prepares). The light keeps showing the lane state. */
onOpen?: () => void;
opening?: boolean;
}) {
const { t } = useTranslation();
// Blink only when the radar sees something the camera hasn't confirmed.
@@ -151,14 +159,15 @@ function BarrierLight({
const radarOk = radar || !!bypassRadar;
const cameraOk = busy || !!bypassCamera;
const canIssue = !!onIssue && radarOk && cameraOk && !issuing;
const clickable = !!onIssue && radarOk && cameraOk;
const clickable = (!!onIssue && radarOk && cameraOk) || !!onOpen;
const onClick = canIssue ? onIssue : onOpen && !opening ? onOpen : undefined;
return (
<div
className={`flex items-center gap-2 rounded-term border px-3 py-2 ${blinking ? "lane-blink" : solid} ${
clickable ? "cursor-pointer hover:brightness-125" : ""
}`}
title={clickable ? t("booth.issueEntryTitle") : label}
onClick={canIssue ? onIssue : undefined}
title={onOpen ? t("booth.forgiveExitTitle") : clickable ? t("booth.issueEntryTitle") : label}
onClick={onClick}
role={clickable ? "button" : undefined}
>
{/* Barrier glyph: a post + an arm. `currentColor` follows the (possibly blinking) state. */}
@@ -170,7 +179,7 @@ function BarrierLight({
<div className="leading-tight">
<div className="text-[0.625rem] uppercase tracking-wider text-term-muted">{label}</div>
<div className="text-xs font-bold">
{issuing ? "…" : clickable ? t("booth.issueEntry") : busy ? "●" : blinking ? "◐" : "○"}
{issuing || opening ? "…" : onIssue && clickable ? t("booth.issueEntry") : busy ? "●" : blinking ? "◐" : "○"}
</div>
</div>
</div>
@@ -216,6 +225,28 @@ function LaneIndicators() {
if (window.confirm(t("booth.issueEntryConfirm"))) issue.mutate();
}
// FORGIVEN exit for a car with NO ticket (barrier:create; wiki/decisions/forgiven-exit.md):
// signed anomaly + exit snapshot + pulse, no money, nothing printed. A small styled
// dialog (same chrome as every other form) asks for an OPTIONAL reason, then confirms.
const canForgive = can(user, "barrier:create") && shiftOpen && isMine;
const [forgiveOpen, setForgiveOpen] = useState(false);
const [forgiveNote, setForgiveNote] = useState("");
const forgive = useMutation({
mutationFn: (note: string) => forgiveExit(null, note),
onSuccess: (r) => {
setForgiveOpen(false);
setForgiveNote("");
setMsg({ ok: r.opened, text: r.opened ? t("booth.forgiveExitOk") : t("booth.forgiveExitNotOpened", { reason: r.reason ?? "" }) });
void qc.invalidateQueries({ queryKey: qk.events });
setTimeout(() => setMsg(null), 5000);
},
onError: (e) => {
setForgiveOpen(false);
setMsg({ ok: false, text: (e as Error).message });
setTimeout(() => setMsg(null), 5000);
},
});
return (
<div className="flex items-center gap-2">
<BarrierLight
@@ -227,7 +258,49 @@ function LaneIndicators() {
bypassRadar={site?.bypassPresenceRadar ?? false}
bypassCamera={site?.bypassPresenceCamera ?? false}
/>
<BarrierLight label={t("booth.laneExit")} busy={lanes?.exit ?? false} radar={radar?.exit ?? false} />
{/* The exit light IS the manual-exit control for whoever may use it (barrier:create +
own shift): same chrome as the entry light, still showing the lane state, labelled
"manual exit" and clickable. For everyone else it is the plain exit lane light. */}
<BarrierLight
label={canForgive ? t("booth.forgiveExit") : t("booth.laneExit")}
busy={lanes?.exit ?? false}
radar={radar?.exit ?? false}
onOpen={canForgive ? () => setForgiveOpen(true) : undefined}
opening={forgive.isPending}
/>
{/* Forgiven-exit dialog (no ticket): what it does, an optional reason, a deliberate red
confirm. Enter in the field confirms; Escape / ✕ / Cancel abort. */}
<Modal open={forgiveOpen} onClose={() => setForgiveOpen(false)} title={t("booth.forgiveDialogTitle")} width="max-w-md">
<form
onSubmit={(e) => {
e.preventDefault();
if (!forgive.isPending) forgive.mutate(forgiveNote.trim());
}}
className="flex flex-col gap-3"
>
<div className="rounded-term border border-term-red/50 bg-term-red/5 px-3 py-2 text-[0.75rem] text-term-text">
{t("booth.forgiveDialogBody")}
</div>
<label className="flex flex-col gap-1 text-[0.6875rem] uppercase tracking-wider text-term-muted">
{t("booth.forgiveDialogReason")}
<input
className="input w-full normal-case tracking-normal"
value={forgiveNote}
onChange={(e) => setForgiveNote(e.target.value)}
placeholder={t("booth.forgiveDialogReasonPlaceholder")}
autoFocus
/>
</label>
<div className="flex items-center justify-end gap-2">
<button type="button" onClick={() => setForgiveOpen(false)} className="btn btn-ghost btn-sm">
{t("common.cancel")}
</button>
<button type="submit" disabled={forgive.isPending} className="btn btn-danger">
{forgive.isPending ? t("booth.forgiveDialogWorking") : t("booth.forgiveDialogConfirm")}
</button>
</div>
</form>
</Modal>
{msg && (
<span className={`text-[0.6875rem] ${msg.ok ? "text-term-green" : "text-term-red"}`}>{msg.text}</span>
)}
+10 -2
View File
@@ -855,7 +855,7 @@ function DeviceForm({
{scanning ? t("setup.scanning") : t("setup.scan")}
</button>
{scanError && <span className="ml-2 text-[0.75rem] text-term-red">{scanError}</span>}
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noControllersFound")}</p>}
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noDevicesFound")}</p>}
{found && found.length > 0 && (
<ul className="mt-2 list-none p-0">
{found.map((d) => (
@@ -865,7 +865,15 @@ function DeviceForm({
</button>
<strong className="text-term-text">{d.label}</strong>
<HealthBadge status={d.health.status} />
{d.info?.firmware && <span className="text-term-muted"> · fw {d.info.firmware}</span>}
{/* Whatever the driver reports (firmware; for a reader its output mode +
current push target — so a reader still in WG26 or pointing at another
server is visible BEFORE it is assigned). */}
{d.info &&
Object.entries(d.info).map(([k, v]) => (
<span key={k} className="text-term-muted">
{" "}· {k} {v}
</span>
))}
</li>
))}
</ul>
+7
View File
@@ -174,6 +174,13 @@ function CloseShiftConfirm({
part is broken out below it; subscription SALES is not (it's the remainder). */}
<span />
<ConfirmFigure label={t("shift.srcSubWindow")} value={fmt(x.subscriptionWindowMinor)} sub />
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
{(x.forgoneCount ?? 0) > 0 && (
<>
<ConfirmFigure label={t("shift.srcForgone", { count: x.forgoneCount })} value={fmt(x.forgoneTotalMinor ?? 0)} />
<span />
</>
)}
</>
)}
</div>
+18
View File
@@ -92,6 +92,8 @@ function useCurrentShifts(): { current: CurrentShift[]; tills: TillId[]; workabl
subscriptionSalesMinor: x.subscriptionSalesMinor,
subscriptionWindowMinor: x.subscriptionWindowMinor,
chargesByModuleMinor: x.chargesByModuleMinor,
forgoneTotalMinor: x.forgoneTotalMinor,
forgoneCount: x.forgoneCount,
openingFloatMinor: x.openingFloatMinor,
cashAddedMinor: x.cashAddedMinor,
cashRemovedMinor: x.cashRemovedMinor,
@@ -409,6 +411,10 @@ function ShiftActivityLog({
<Figure label={t("shifts.srcSubscriptions")} value={money(shift.subscriptionTotalMinor, cur)} />
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
<Figure label={t("shifts.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
{(shift.forgoneCount ?? 0) > 0 && (
<Figure label={t("shifts.srcForgone", { count: shift.forgoneCount })} value={money(shift.forgoneTotalMinor ?? 0, cur)} />
)}
<ChargeFigures charges={shift.chargesByModuleMinor} cur={cur} />
<Figure label={t("shifts.openingFloat")} value={money(shift.openingFloatMinor, cur)} />
<Figure label={t("shifts.cashTaken")} value={money(shift.cashTotalMinor, cur)} />
@@ -471,6 +477,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
<span />
<Figure label={t("shift.srcSubWindow")} value={money(report.subscriptionWindowMinor, report.currency)} sub />
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
{(report.forgoneCount ?? 0) > 0 && (
<Figure label={t("shift.srcForgone", { count: report.forgoneCount })} value={money(report.forgoneTotalMinor ?? 0, report.currency)} />
)}
</div>
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
<Figure label={t("shift.cash")} value={money(report.cashTotalMinor, report.currency)} />
@@ -498,6 +508,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
<span />
<Figure label={t("shift.srcSubWindow")} value={money(shift.subscriptionWindowMinor, cur)} sub />
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
{(shift.forgoneCount ?? 0) > 0 && (
<Figure label={t("shift.srcForgone", { count: shift.forgoneCount })} value={money(shift.forgoneTotalMinor ?? 0, cur)} />
)}
</div>
<div className="mt-2 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-2">
<Figure label={t("shift.cash")} value={money(shift.cashTotalMinor, cur)} />
@@ -540,6 +554,10 @@ function TakingsModal({ till, onClose }: { till: TillId; onClose: () => void })
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
<span />
<Figure label={t("shift.srcSubWindow")} value={money(x.subscriptionWindowMinor, x.currency)} sub />
{/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */}
{(x.forgoneCount ?? 0) > 0 && (
<Figure label={t("shift.srcForgone", { count: x.forgoneCount })} value={money(x.forgoneTotalMinor ?? 0, x.currency)} />
)}
</div>
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 border-t border-term-border pt-1">
<Figure label={t("shift.cash")} value={money(x.cashTotalMinor, x.currency)} />
+14
View File
@@ -1102,6 +1102,10 @@ export interface ShiftSourceSplit {
/** Module money that rode this till's tickets (a booth-paid wash), by module id.
* Inside cash+card, OUTSIDE the ticket bucket. Absent on pre-2026-09 reports. */
chargesByModuleMinor?: Partial<Record<string, number>>;
/** Forgiven exits (wiki/decisions/forgiven-exit.md): fees an operator waived, and how
* many. $0 payments — NOT inside cash/card. Absent on pre-2026-10 reports. */
forgoneTotalMinor?: number;
forgoneCount?: number;
}
export interface ShiftReport extends ShiftSourceSplit {
@@ -1448,6 +1452,16 @@ export function reopenBarrier(identity: string): Promise<{ ok: true; opened: boo
return apiFetch("/api/barrier/reopen", { method: "POST", body: JSON.stringify({ identity }) });
}
/** FORGIVEN exit (barrier:create): open the exit with NO payment. With a ticket the fee
* owed is signed as forgone on a $0 payment; with `identity` null the car has no
* session (anomaly + snapshot + pulse). `note` is the mandatory reason. Prints nothing. */
export function forgiveExit(
identity: string | null,
note: string,
): Promise<{ ok: true; opened: boolean; reason?: string; forgoneMinor?: number; currency?: string }> {
return apiFetch("/api/barrier/forgive", { method: "POST", body: JSON.stringify({ ...(identity ? { identity } : {}), note }) });
}
/** Take payment for a session → signed payment event. `overrideMinor` sets an
* operator amount (lost ticket / dispute). */
export function paySession(
+25 -3
View File
@@ -317,6 +317,16 @@ export const en: Catalog = {
issueEntryTitle: "Issue an entry ticket & open the barrier (physical button broken)",
issueEntryConfirm: "A vehicle is at the entry. Issue an entry ticket and open the barrier?",
issueEntryOk: "Entry ticket {{ticket}} issued.",
forgiveExit: "Manual Exit",
forgiveExitTitle: "Open the exit barrier for a car with NO ticket — no money, signed and flagged",
forgiveExitOk: "Exit opened manually, no payment.",
forgiveExitNotOpened: "Recorded, but the barrier did not open: {{reason}}",
forgiveDialogTitle: "Manual exit",
forgiveDialogBody: "Opens the EXIT barrier for a car with no ticket. No money is taken and nothing is printed; the open is signed under your name with the exit camera's snapshot and shows on your shift report.",
forgiveDialogReason: "Reason (optional)",
forgiveDialogReasonPlaceholder: "e.g. came in while the barriers were up…",
forgiveDialogConfirm: "Open exit — no payment",
forgiveDialogWorking: "opening…",
exitedGrace: "exited · grace",
exitedGraceLeft: "exited · {{time}}",
exitedGraceTitle: "Paid and exited — barrier not confirmed; waiting out the grace period.",
@@ -419,6 +429,8 @@ export const en: Catalog = {
"exit.open.failed": "Exit recorded, but the barrier did not open — open manually",
"exit.freeGrace": "Free entry-grace (no charge)",
"exit.manualOpen": "Manual barrier open (human intervention)",
"exit.forgiven": "Manual exit by {{operator}} — fee of {{forgone}} {{currency}}, no payment: {{note}}",
"exit.forgiven.noSession": "Manual exit by {{operator}} — no ticket / no session: {{note}}",
"exit.plateSwapSuspected": "Possible ticket swap — plate {{plate}} is already inside under ticket {{otherIdentity}}",
"exit.plateSwapOverride": "Operator {{operator}} released a suspected ticket-swap exit (plate {{plate}}, also open under {{otherIdentity}})",
"sub.refused.notFound": "Subscription refused — not found",
@@ -532,9 +544,9 @@ export const en: Catalog = {
unbound: "unbound",
noDrivers: "No drivers registered.",
chooseDevice: "Choose a device…",
scan: "Scan for controllers",
scan: "Scan the LAN",
scanning: "Scanning…",
noControllersFound: "No controllers found on the LAN.",
noDevicesFound: "No devices found on the LAN (the booth and the device must share the device VLAN).",
usbNoneFound: "No USB printer found (/dev/usb/lpN) — check cable/power; the path can be typed manually.",
usbSavedMissing: "saved — not present now",
use: "Use",
@@ -553,7 +565,7 @@ export const en: Catalog = {
chooseAddress: "Choose an address…",
onDeviceSubnet: "— on device subnet",
noNicOnSubnet: "⚠ no NIC on the device's subnet — the device may not reach the backend",
backendIpHint: "The address this device will POST input events to.",
backendIpHint: "The address this device will push its events/scans to.",
relaysTitle: "Relays on this controller",
relaysHint:
"Each relay opens one barrier. Set its direction; for transient entry, set which input terminal the entry button is wired to.",
@@ -991,6 +1003,7 @@ export const en: Catalog = {
srcSubscriptions: "Subscriptions:",
srcOnTicket: "{{module}} (on ticket):",
srcSubWindow: "out-of-window",
srcForgone: "Manual exits ({{count}}):",
drawerSection: "— Drawer —",
openingFloat: "Opening cash:",
cashTaken: "Daily takings:",
@@ -1039,6 +1052,7 @@ export const en: Catalog = {
srcTickets: "Tickets",
srcSubscriptions: "Subscriptions",
srcSubWindow: "out-of-window",
srcForgone: "Manual exits ({{count}})",
expectedDrawer: "Expected drawer",
filterFrom: "From",
filterTo: "To",
@@ -1246,6 +1260,14 @@ export const en: Catalog = {
confirmCancelTicket: "Confirm cancellation",
cancelling: "cancelling…",
ticketCancelled: "Ticket cancelled.",
forgiveExit: "Open manually",
forgiveTitle: "Open this exit manually",
forgiveHint: "Lets the car out with NO payment. The fee owed ({{amount}}) is recorded as a manual exit on your shift report, not as money. A reason is optional; nothing is printed.",
forgiveReasonPlaceholder: "Reason (optional)…",
confirmForgive: "Confirm — open exit, no payment",
forgiving: "opening…",
exitForgiven: "Manual exit — {{amount}}, barrier opened.",
exitForgivenNotOpened: "Manual exit — {{amount}}, barrier did not open: {{reason}}",
noSnapshots: "no snapshots",
loadingSnapshots: "loading snapshots…",
snapEntry: "entry",
+25 -3
View File
@@ -319,6 +319,16 @@ export const sq = {
issueEntryTitle: "Lësho një biletë hyrjeje & hap barrierën (butoni fizik i prishur)",
issueEntryConfirm: "Një automjet është te hyrja. Të lëshohet një biletë hyrjeje dhe të hapet barriera?",
issueEntryOk: "Bileta e hyrjes {{ticket}} u lëshua.",
forgiveExit: "Dalje Manuale",
forgiveExitTitle: "Hap barrierën e daljes manualisht — pa pagesë",
forgiveExitOk: "Dalja u hap manualisht, pa pagesë.",
forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}",
forgiveDialogTitle: "Hapje manuale",
forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me foton e kamerës së daljes dhe shfaqet në raportin e turnit tënd.",
forgiveDialogReason: "Arsyeja (opsionale)",
forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…",
forgiveDialogConfirm: "Hap daljen — pa pagesë",
forgiveDialogWorking: "duke hapur…",
exitedGrace: "doli · në afat",
exitedGraceLeft: "doli · {{time}}",
exitedGraceTitle: "Paguar dhe dalur — barriera nuk u konfirmua; po pret afatin kohor.",
@@ -422,6 +432,8 @@ export const sq = {
"exit.open.failed": "Dalja u regjistrua, por barriera nuk u hap — hape manualisht",
"exit.freeGrace": "Periudhë pa pagesë në hyrje (pa tarifë)",
"exit.manualOpen": "Hapje manuale e barrierës (ndërhyrje njerëzore)",
"exit.forgiven": "Dalje manuale nga {{operator}} — tarifa {{forgone}} {{currency}}: {{note}}",
"exit.forgiven.noSession": "Dalje manuale nga {{operator}} — pa biletë / pa seancë: {{note}}",
"exit.plateSwapSuspected": "Mundësi ndërrimi biletash — targa {{plate}} është tashmë brenda me biletën {{otherIdentity}}",
"exit.plateSwapOverride": "Operatori {{operator}} lëshoi një dalje me dyshim ndërrimi biletash (targa {{plate}}, edhe e hapur me {{otherIdentity}})",
"sub.refused.notFound": "Abonimi u refuzua — nuk u gjet",
@@ -540,9 +552,9 @@ export const sq = {
// Device form.
noDrivers: "Asnjë drejtues i regjistruar.",
chooseDevice: "Zgjidh një pajisje…",
scan: "Skano për kontroller",
scan: "Skano LAN-in",
scanning: "Duke skanuar…",
noControllersFound: "Asnjë kontroller në LAN.",
noDevicesFound: "Asnjë pajisje në LAN (kabina dhe pajisja duhet të jenë në të njëjtin VLAN).",
usbNoneFound: "Nuk u gjet asnjë printer USB (/dev/usb/lpN) — kontrollo kabllon/ushqimin; rruga mund të shkruhet me dorë.",
usbSavedMissing: "i ruajtur — jo i pranishëm tani",
use: "Përdor",
@@ -561,7 +573,7 @@ export const sq = {
chooseAddress: "Zgjidh një adresë…",
onDeviceSubnet: "— në subnetin e pajisjes",
noNicOnSubnet: "⚠ asnjë NIC në subnetin e pajisjes — pajisja mund të mos arrijë backend-in",
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet e hyrjes.",
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet/skanimet.",
// Relay editor.
relaysTitle: "Relet në këtë kontroller",
relaysHint:
@@ -1004,6 +1016,7 @@ export const sq = {
srcSubscriptions: "Abonime:",
srcOnTicket: "{{module}} (në biletë):",
srcSubWindow: "jashtë orarit",
srcForgone: "Dalje manuale ({{count}}):",
drawerSection: "— Arka —",
openingFloat: "Arka fillestare:",
cashTaken: "Xhiro ditore:",
@@ -1052,6 +1065,7 @@ export const sq = {
srcTickets: "Bileta",
srcSubscriptions: "Abonime",
srcSubWindow: "jashtë orarit",
srcForgone: "Dalje manuale ({{count}})",
expectedDrawer: "Gjëndje arke",
// Filter (admin only).
filterFrom: "Nga",
@@ -1262,6 +1276,14 @@ export const sq = {
confirmCancelTicket: "Konfirmo anulimin",
cancelling: "duke anuluar…",
ticketCancelled: "Bileta u anulua.",
forgiveExit: "Hap Manualisht",
forgiveTitle: "Hap manualisht këtë dalje",
forgiveHint: "E lë automjetin të dalë PA pagesë. Shuma e detyruar ({{amount}}) regjistrohet si dalje manuale në raportin e turnit, jo si para. Arsyeja është opsionale; nuk printohet asgjë.",
forgiveReasonPlaceholder: "Arsyeja (opsionale)…",
confirmForgive: "Konfirmo — hap daljen, pa pagesë",
forgiving: "duke hapur…",
exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.",
exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}",
// snapshots
noSnapshots: "asnjë foto",
loadingSnapshots: "duke ngarkuar fotot…",
+13 -3
View File
@@ -18,6 +18,13 @@ services:
# Host network: Caddy listens on the host's :80 and proxies the host-net server on
# 127.0.0.1:3000. (No `ports:` mapping — host mode publishes directly.)
network_mode: host
# PORTS (2026-10-08). On a booth nothing is set and the defaults apply (:80 → :3000). On a
# SHARED host — the lab stack runs on art-docker-station, whose :80 is another service's —
# the stack env sets HTTP_PORT / SERVER_PORT / VISION_HOST_PORT and every binding follows.
# The Caddyfile reads these two as {$HTTP_PORT:80} / {$SERVER_PORT:3000}.
environment:
HTTP_PORT: ${HTTP_PORT:-80}
SERVER_PORT: ${SERVER_PORT:-3000}
# host mode is mutually exclusive with a named network; the base file doesn't attach proxy,
# so nothing to null here (server does — see below).
volumes:
@@ -45,9 +52,12 @@ services:
# host mode is mutually exclusive with a named network — detach the base file's `parking`
# attachment (compose errors otherwise: "network_mode and networks cannot both be set").
networks: !reset []
# Listens on :3000 directly on the host (Caddy proxies it). Loopback to vision:
# Listens on SERVER_PORT (default 3000) directly on the host (Caddy proxies it); the same
# value is what net.ts advertises as the device push port. Loopback to vision on the host
# port vision publishes (VISION_HOST_PORT, default 8089):
environment:
VISION_URL: http://127.0.0.1:8089
PORT: ${SERVER_PORT:-3000}
VISION_URL: http://127.0.0.1:${VISION_HOST_PORT:-8089}
# NB: NO `sysctls:` here. net.ipv4.ping_group_range is a per-netns sysctl; under host net
# there is no separate namespace, and runc REFUSES it ("not allowed in host network
# namespace"). Reader liveness ping uses the HOST's setting instead — the booth host must
@@ -95,7 +105,7 @@ services:
environment:
VISION_RECOGNIZER: fast_alpr
ports:
- "127.0.0.1:8089:8089"
- "127.0.0.1:${VISION_HOST_PORT:-8089}:8089"
# ≈2 months (see the server note): vision logs less — 20 MB × 10 = 200 MB ceiling.
logging:
driver: json-file
+67 -4
View File
@@ -49,11 +49,20 @@ REGISTRY=git.infra.msai.al/mca/parking_solution
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
# exists as the pointer; we deploy the sha, not the mover.
TAG=stage-8fa66c9
TAG=stage-32b4d9e
COOKIE_SECURE=0
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
MODULES_ENTITLED=parking,validation
# Car Wash review outbox (wiki/concepts/vision-review-outbox.md): the collector's ingest URL
# on the Netbird overlay, this booth's PSEUDONYMOUS id (never the site name — the crops leave
# the site), and its token — the SAME secret the wash-collector stack lists under that id.
CARWASH_REVIEW_URL=http://docker-station.nb.infra:8090/ingest
CARWASH_REVIEW_BOOTH_ID=booth-1
CARWASH_REVIEW_TOKEN=[[wash_review_token_booth_buzi]]
# Also send ENTRY reads as training material (gate view, no wash): 1 = every entry (storage
# and bandwidth are not the limit; review what you have time for). N = one in N. 0 = off.
CARWASH_REVIEW_ENTRY_SAMPLE=1
VISION_ENABLED=1
# Desktop app WS handshake: Origin is tauri://localhost (set explicitly by
# platform-ws.ts, since the native WS plugin has no page context to auto-attach
@@ -85,7 +94,7 @@ REGISTRY=git.infra.msai.al/mca/parking_solution
# Staging booth: pinned immutable stage-<sha>. After each promotion (merge dev → stage, CI builds
# :stage-<sha>), bump this to the new sha and re-sync/deploy from Core. The moving `:stage` tag
# exists as the pointer; we deploy the sha, not the mover.
TAG=stage-dbbb051
TAG=stage-2ac26b5
COOKIE_SECURE=0
# Venue modules this site is ENTITLED to (vendor decision; the site admin activates within
# this set in Setup → Site). Unset = every registered module. See wiki/decisions/venue-modules.md.
@@ -110,6 +119,60 @@ EVENT_SIGNING_KEY=[[park_2_event_signing_key]]
BACKUP_KEY=[[park_2_backup_key]]
"""
##############################################################################
# Stack — the LAB BENCH (not a booth): a spare Linux box with the field printer and
# whatever device is under investigation, so a booth bug can be reproduced on the booth's
# exact image before touching a real site. Same compose files + pinned TAG as the staging
# booths. Review outbox under its OWN id (booth-lab) — never a
# booth's identity, so bench crops stay separable on the collector. Its own secrets. See wiki/decisions/fleet-deployment-komodo.md.
##############################################################################
[[stack]]
name = "park-lab"
[stack.config]
server = "art-docker-station"
git_provider = "git.infra.msai.al"
git_account = "komodo"
repo = "mca/parking_solution"
branch = "stage"
file_paths = [
"docker-compose.yml",
"docker-compose.prod.yml"
]
registry_provider = "git.infra.msai.al"
registry_account = "komodo"
environment = """
REGISTRY=git.infra.msai.al/mca/parking_solution
# Lab: pinned to the SAME stage-<sha> as the booth whose bug is being reproduced (bump
# alongside it). A lab may float, but a reproduction must run the booth's exact image.
TAG=stage-32b4d9e
# The lab stack runs on art-docker-station (2026-10-08), a SHARED host: :80 is another service's
# and :3000 / :8089 may be too. These three move every host binding (Caddy listen, host-net
# server, vision loopback publish); the UI is then http://<station>:8080/. Booth stacks leave
# them unset and keep :80 → :3000. See docker-compose.prod.yml + Caddyfile.
HTTP_PORT=8080
SERVER_PORT=3100
VISION_HOST_PORT=8189
COOKIE_SECURE=0
# Entitled to Car Wash too, so the wash-desk printer role and till can be exercised on the bench.
MODULES_ENTITLED=parking,carwash
# Review outbox ON for the bench too, under its OWN pseudonymous id (booth-lab) and its own
# secret — never a real booth's — so lab crops are separable on the collector (per-booth stats,
# the export's booth column) and the reviewer can label bench junk "unusable".
CARWASH_REVIEW_URL=http://docker-station.nb.infra:8090/ingest
CARWASH_REVIEW_BOOTH_ID=booth-lab
CARWASH_REVIEW_TOKEN=[[wash_review_token_booth_lab]]
CARWASH_REVIEW_ENTRY_SAMPLE=1
VISION_ENABLED=1
# Desktop app WS handshake: Origin is tauri://localhost (set explicitly by
# platform-ws.ts, since the native WS plugin has no page context to auto-attach
# one). Linux may also send http://tauri.localhost. See routes/ws.ts anti-CSWSH check.
WS_ALLOWED_ORIGINS=tauri://localhost,http://tauri.localhost
JWT_SECRET=[[park_lab_jwt_secret]]
EVENT_SIGNING_KEY=[[park_lab_event_signing_key]]
BACKUP_KEY=[[park_lab_backup_key]]
"""
##############################################################################
# Stack — the Car Wash REVIEW COLLECTOR on the reviewer's host (art-docker-station),
# NOT a booth. Same repo/branch/TAG promotion as the booths, but its file_paths name
@@ -134,7 +197,7 @@ registry_account = "komodo"
environment = """
REGISTRY=git.infra.msai.al/mca/parking_solution
# Pinned like the booths: bump to the stage-<sha> that carries the collector.
TAG=stage-f7a262a
TAG=stage-32b4d9e
# The host's NETBIRD address (an IP: Docker port bindings take no hostname) — the ingest port
# is published on the overlay only. Booths reach it by its Netbird DNS name.
COLLECTOR_BIND=100.75.184.156
@@ -142,7 +205,7 @@ COLLECTOR_BIND=100.75.184.156
# that booth's own stack as its CARWASH_REVIEW_TOKEN — one value, two consumers, nothing
# to keep in sync, and rotating a booth touches one secret. The booth id is the booth's
# pseudonymous CARWASH_REVIEW_BOOTH_ID, never a site name. Add a pair per booth.
COLLECTOR_BOOTH_TOKENS=booth-2:[[wash_review_token_booth_2]]
COLLECTOR_BOOTH_TOKENS=booth-2:[[wash_review_token_booth_2]],booth-1:[[wash_review_token_booth_buzi]],booth-lab:[[wash_review_token_booth_lab]]
# Phase-B trainer (the `trainer` service beside the collector; the Training section of /review
# is its UI). Only `publish` needs this: a Gitea token with package:write for the model's generic
# package. Uncomment when the first model is to be published.
+12 -1
View File
@@ -51,6 +51,10 @@ const CATEGORIES = {
"subscription_credentials",
"subscriptions",
"blocklist",
// Car Wash (venue module): orders are money history (settled against ledger events);
// the review outbox is a delivery queue of crops + choices — both go with the ledger.
"carwash_review_outbox",
"carwash_orders",
],
config: [
"site_config",
@@ -65,8 +69,15 @@ const CATEGORIES = {
// whose user is gone grants nothing.
"validation_program_users",
"validation_programs",
// Car Wash master data: prices reference categories + services (child first); the
// module's site-level config (pay-at, vision threshold) is config like site_config.
"carwash_prices",
"carwash_categories",
"carwash_services",
"carwash_config",
],
users: ["sessions", "role_permissions", "users", "roles"],
// role_jobs = which jobs a role follows (child of roles).
users: ["sessions", "role_permissions", "role_jobs", "users", "roles"],
diagnostics: ["app_logs"],
};
+162 -7
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 () => {
@@ -200,12 +200,167 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
await expect(cam().syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 403");
});
it("the dahua driver does NOT claim the capability (no ISAPI time endpoint)", async () => {
it("both camera drivers claim the capability (Dahua via global.cgi since 2026-09-17)", async () => {
const { dahuaDriver, hikvisionDriver } = await import("./camera.js");
const { isClockSyncable } = await import("../interfaces.js");
const mk = (d: typeof dahuaDriver) =>
d.create({ host: "10.0.10.12", port: 80, username: "admin", password: "x", channel: 1 });
expect(isClockSyncable(mk(dahuaDriver))).toBe(false);
expect(isClockSyncable(mk(dahuaDriver))).toBe(true);
expect(isClockSyncable(mk(hikvisionDriver))).toBe(true);
});
});
// Dahua — verified against an IPC-HFW2549T-AS-IL (fw 2.880) on 2026-09-17. The CGI
// numbers snapshot channels from 1 (channel=0 → HTTP 400), ignores any stream
// selector, and speaks NAIVE local wall time on global.cgi. See camera.ts and
// wiki/entities/dahua-ipc-hfw2549t.md.
describe("dahua snapshot URL — channel is 1-BASED, no stream selector", () => {
async function pathFor(config: Record<string, unknown>): Promise<string> {
const { dahuaDriver } = await import("./camera.js");
digestGet.mockReset();
digestGet.mockResolvedValue(reply(200));
dahuaDriver.create(config as never).captureSnapshot({ direction: "entry" });
return String((digestGet.mock.calls[0]![0] as { path: string }).path);
}
it("channel 1 as entered → channel=1 (the old `ch - 1` sent 0 → HTTP 400 on hardware)", async () => {
expect(await pathFor({ host: "1.2.3.4", channel: 1 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
});
it("defaults to channel 1 when none is configured", async () => {
expect(await pathFor({ host: "1.2.3.4" })).toBe("/cgi-bin/snapshot.cgi?channel=1");
});
it("channel 2 passes through; a stream setting is ignored", async () => {
expect(await pathFor({ host: "1.2.3.4", channel: 2, stream: 2 })).toBe("/cgi-bin/snapshot.cgi?channel=2");
});
it("a zero/negative channel is clamped to 1 rather than sent as-is", async () => {
expect(await pathFor({ host: "1.2.3.4", channel: 0 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
});
});
describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wall time", () => {
const HOST_NOW = "2026-09-17T10:35:49+02:00";
const timeReply = (naive: string) => reply(200, `result=${naive}\r\n`);
async function cam() {
const { dahuaDriver } = await import("./camera.js");
return dahuaDriver.create({ host: "10.0.10.11", port: 80, username: "admin", password: "x", channel: 1 }) as unknown as {
syncClock(localIso: string, maxDriftSec: number): Promise<{ driftSeconds: number | null; synced: boolean }>;
};
}
it("in-sync camera: reads, does NOT set", async () => {
digestRequest.mockResolvedValueOnce(timeReply("2026-09-17 10:35:40"));
const r = await (await cam()).syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: 9, synced: false });
expect(digestRequest).toHaveBeenCalledTimes(1);
const get = digestRequest.mock.calls[0]![0] as { method: string; path: string };
expect(get.method).toBe("GET");
expect(get.path).toBe("/cgi-bin/global.cgi?action=getCurrentTime");
});
it("an hour behind (the bench unit: DST off, NTP off) → sets the HOST wall time, no offset", async () => {
digestRequest
.mockResolvedValueOnce(timeReply("2026-09-17 09:35:51"))
.mockResolvedValueOnce(reply(200, "OK\r\n"));
const r = await (await cam()).syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: 3598, synced: true });
const set = digestRequest.mock.calls[1]![0] as { method: string; path: string };
expect(set.method).toBe("GET");
expect(set.path).toBe("/cgi-bin/global.cgi?action=setCurrentTime&time=2026-09-17%2010%3A35%3A49");
});
it("unparseable camera reply = infinite drift → syncs", async () => {
digestRequest
.mockResolvedValueOnce(reply(200, "Error\r\nBad Request!"))
.mockResolvedValueOnce(reply(200, "OK"));
const r = await (await cam()).syncClock(HOST_NOW, 60);
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 () => {
digestRequest
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
.mockResolvedValueOnce(reply(200, "Error\r\nInvalid Argument!"));
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 200 Error");
});
it("a non-200 set surfaces as an error", async () => {
digestRequest
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
.mockResolvedValueOnce(reply(401, "denied"));
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>");
});
});
+120 -24
View File
@@ -18,8 +18,12 @@ import { digestGet, digestRequest } from "./http-digest.js";
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
// HTTP when an event fires; the bytes are stored and referenced from the signed
// event as an independent fraud-control record (the camera PULLS, it never pushes
// to us). Hikvision (ISAPI) and Dahua (CGI) differ only in the snapshot URL and
// channel encoding. Both use HTTP Digest auth (see ./http-digest.ts).
// to us). Hikvision (ISAPI) and Dahua (CGI) differ in the snapshot URL, the
// channel encoding and the clock endpoint. Both use HTTP Digest auth (see ./http-digest.ts).
//
// VERIFIED on hardware (2026-09-17): a Dahua IPC-HFW2549T-AS-IL (fw 2.880) at
// 10.0.10.11 returns a 2880×1620 JPEG from /cgi-bin/snapshot.cgi?channel=1 —
// and HTTP 400 for channel=0. See wiki/entities/dahua-ipc-hfw2549t.md.
//
// VERIFIED on hardware (2026-06-15): a Hikvision unit at 10.0.10.121 returns a
// 2688×1520 JPEG from /ISAPI/Streaming/channels/101/picture with Digest auth.
@@ -139,10 +143,9 @@ class HttpCamera implements CameraDevice {
`${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}${busy}`,
);
}
stubLog(
this.driverId,
`captureSnapshot ${ctx.direction} (${res.body.length} bytes)`,
);
// Per-snapshot chatter → debug (a busy lane logs one every few seconds); the retry
// and failure lines above stay at info/throw.
stubLog(this.driverId, `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`, "debug");
return {
bytes: res.body,
contentType: res.contentType || "image/jpeg",
@@ -162,8 +165,8 @@ class HttpCamera implements CameraDevice {
});
}
/** Digest request against an arbitrary device path (ISAPI config reads/writes). */
protected isapi(method: "GET" | "PUT", path: string, body?: string) {
/** Digest request against an arbitrary device path (ISAPI / CGI config reads+writes). */
protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) {
return digestRequest({
host: this.#host,
port: this.#port,
@@ -186,24 +189,51 @@ 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.isapi("GET", "/ISAPI/System/time");
const read = await this.deviceRequest("GET", "/ISAPI/System/time");
if (read.status !== 200) {
throw new Error(`clock read failed: HTTP ${read.status}`);
}
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.
@@ -212,19 +242,83 @@ 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.isapi("PUT", "/ISAPI/System/time", body);
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${zoneChanged ? `; zone ${timeZone || "unset"} → ${wantZone}` : ""})`,
);
return { driftSeconds, synced: true, zoneChanged, timeZone: wantZone };
}
}
// --- Dahua clock sync (CGI global.cgi getCurrentTime / setCurrentTime) --------------
// Same problem, different surface. The Dahua CGI reads and writes the clock as a
// NAIVE local wall-time string ("2026-09-17 10:35:49", no offset) in whatever time
// zone / DST the camera is configured for. We deliberately write the HOST's local
// wall time verbatim: what must match the booth is the OSD timestamp burned into
// every snapshot and the event times, i.e. the wall clock — not the camera's idea
// of UTC. (The bench unit ran a year-round UTC+1 with DST off and NTP off; after
// this sync its OSD read the booth's time.) VERIFIED on hardware 2026-09-17:
// setCurrentTime answers 200 "OK" and getCurrentTime reads the new value back.
// See wiki/entities/dahua-ipc-hfw2549t.md.
const DAHUA_TIME_PATH = "/cgi-bin/global.cgi?action=getCurrentTime";
/** "2026-09-17T10:35:49+02:00" (host localIso, WITH offset) → "2026-09-17 10:35:49"
* (the naive wall time the Dahua CGI speaks). */
function naiveWallTime(localIso: string): string {
const m = localIso.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/);
if (!m) throw new Error(`syncClock: unparseable host time ${localIso}`);
return `${m[1]} ${m[2]}`;
}
/** Parse a naive "YYYY-MM-DD HH:MM:SS" as an instant in the HOST's zone — both sides
* of the drift comparison go through this, so the zone cancels out. */
function naiveMs(naive: string): number {
return Date.parse(naive.replace(" ", "T"));
}
class DahuaCamera extends HttpCamera {
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
const read = await this.deviceRequest("GET", DAHUA_TIME_PATH);
if (read.status !== 200) {
throw new Error(`clock read failed: HTTP ${read.status}`);
}
// Reply body: "result=2026-09-17 09:35:51"
const cameraNaive =
read.body.toString("utf8").match(/result=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1] ?? null;
const hostNaive = naiveWallTime(localIso);
const cameraMs = cameraNaive ? naiveMs(cameraNaive) : NaN;
const driftSeconds = Number.isFinite(cameraMs)
? Math.round(Math.abs(naiveMs(hostNaive) - cameraMs) / 1000)
: null;
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false };
}
const set = await this.deviceRequest(
"GET",
`/cgi-bin/global.cgi?action=setCurrentTime&time=${encodeURIComponent(hostNaive)}`,
);
// Dahua answers 200 with a body of "OK"; a refused write is a non-200 or "Error".
if (set.status !== 200 || !/^OK/.test(set.body.toString("utf8").trim())) {
throw new Error(
`clock set failed: HTTP ${set.status} ${set.body.toString("utf8").trim().slice(0, 40)}`,
);
}
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
return { driftSeconds, synced: true };
}
@@ -329,15 +423,17 @@ export const dahuaDriver: CameraDriver = {
id: "dahua",
category: "camera",
label: "Dahua camera",
description: "Dahua snapshot via CGI (HTTP Digest).",
description: "Dahua snapshot via CGI (HTTP Digest) + clock sync.",
transports: ["tcp-ip"],
configFields: cameraConfigFields,
// Dahua channels are 0-based on the CGI; the admin enters 1-based. No stream in the
// path (the second arg is ignored — Dahua has no main/sub snapshot distinction here).
// snapshot.cgi channels are 1-BASED, exactly as the admin enters them (only Dahua's
// configManager TABLES are 0-indexed — the earlier `ch - 1` here drew a permanent
// HTTP 400 on real hardware, 2026-09-17). No stream in the path: `subtype` is
// ignored by snapshot.cgi, the still always comes off the main stream.
create: (c) =>
new HttpCamera(
new DahuaCamera(
"dahua",
c,
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(0, ch - 1)}`,
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(1, ch)}`,
),
};
+8 -4
View File
@@ -32,7 +32,8 @@ export const passwordField: ConfigField = {
* Sink for stub/diagnostic device messages. Defaults to a no-op so the package
* has no host/runtime dependency; the server sets this to its Fastify logger.
*/
export type DeviceLogSink = (line: string) => void;
export type DeviceLogLevel = "debug" | "info" | "warn";
export type DeviceLogSink = (line: string, level: DeviceLogLevel) => void;
let sink: DeviceLogSink = () => {};
@@ -40,7 +41,10 @@ export function setDeviceLogSink(fn: DeviceLogSink): void {
sink = fn;
}
/** Stubs log instead of performing real I/O. Replaced with real protocols later. */
export function stubLog(driverId: string, msg: string): void {
sink(`[device:${driverId}] ${msg}`);
/** Device-side diagnostics (the sink is the server's logger). `info` for things an
* operator reading `docker logs` should see (a config write, a retry, a clock set);
* `debug` for per-event chatter (every snapshot's byte count) that only matters under
* LOG_LEVEL=debug. */
export function stubLog(driverId: string, msg: string, level: DeviceLogLevel = "info"): void {
sink(`[device:${driverId}] ${msg}`, level);
}
@@ -0,0 +1,346 @@
import { createSocket, type Socket } from "node:dgram";
import { afterEach, describe, expect, it } from "vitest";
import {
QR_CMD,
QR_OUTPUT_HTTP,
buildDeviceInfo,
checksum,
discoverReaders,
exchange,
frameHeader,
parseDeviceInfo,
parseFirmware,
parseFrame,
parseParams,
readFirmware,
readParams,
setNetwork,
writeSetting,
ipToBytes,
} from "./dingtian-qr-config.js";
// The DT-008 configuration protocol, against a FAKE reader on loopback that behaves like
// the real one (wiki/raw/dingtian_qr_linux/PROTOCOL.md): header + payload must arrive as
// two datagrams, every write is acked with cmd+1 and a status byte, search answers with
// a 96-byte DeviceInfo, set-network is applied WITHOUT a reply. Byte layouts below are
// the worked examples and the reference capture from the bench reader HC002721.
// --- reference bytes -------------------------------------------------------
/** Build a 720-byte Params struct like the bench capture (HTTP, 10.0.10.204:8080, 8H…). */
function referenceParams(over: Partial<{ outputType: number; server: string; serverPort: number }> = {}): Buffer {
const b = Buffer.alloc(720);
b.writeUInt32LE(0, 0x000); // static IP
ipToBytes("10.0.10.12").copy(b, 0x004);
ipToBytes("255.255.255.0").copy(b, 0x008);
ipToBytes("10.0.10.1").copy(b, 0x00c);
ipToBytes("8.8.8.8").copy(b, 0x010);
ipToBytes("8.8.4.4").copy(b, 0x014);
b.write(over.server ?? "10.0.10.204", 0x018, "utf8");
b.writeUInt32LE(over.serverPort ?? 8080, 0x048);
b.writeUInt32LE(0, 0x04c); // PHP
b.writeUInt8(over.outputType ?? 3, 0x198); // HTTP
b.writeUInt8(2, 0x19c); // 8H
b.writeUInt8(1, 0x1a0); // add Enter
b.writeUInt8(0, 0x1a1);
b.writeUInt32LE(1, 0x1a4); // ASCII
b.writeUInt32LE(1, 0x1c8);
b.writeUInt32LE(1, 0x1ec); // restart 12 h
b.writeUInt32LE(0, 0x1f0); // normal
b.writeUInt32LE(0, 0x1f8); // buzzer off
b.writeUInt32LE(20, 0x1fc); // 2000 µs
b.writeUInt32LE(4, 0x200); // 400 µs
b.writeUInt32LE(9600, 0x204);
b.writeUInt32LE(8, 0x208);
b.writeUInt32LE(1, 0x20c);
b.writeUInt32LE(2, 0x210); // parity none
b.writeUInt32LE(4, 0x214); // QR ASCII
b.writeUInt32LE(1, 0x218); // fill light open
b.writeUInt32LE(1, 0x288);
b.writeUInt32LE(1, 0x28c);
b.write("K:", 0x290, "utf8");
return b;
}
function referenceFirmware(serial = "HC002721"): Buffer {
const b = Buffer.alloc(64);
b.write("doorqrcode", 0);
b.write("ver_client1_1.1", 16);
b.write("v3s", 32);
b.write("h42", 40);
b.write(serial, 48);
return b;
}
// --- fake reader -----------------------------------------------------------
interface FakeReader {
readonly unicast: number;
readonly broadcast: number;
readonly writes: { cmd: number; value: number }[];
params: Buffer;
singleDatagramFrames: number;
close(): void;
}
/** A loopback reader. One socket plays both ports (unicast + "broadcast"). */
async function fakeReader(params = referenceParams(), serial = "HC002721"): Promise<FakeReader> {
const bind = (): Promise<Socket> =>
new Promise((res) => {
const s = createSocket("udp4");
s.bind(0, "127.0.0.1", () => res(s));
});
const uni = await bind();
const bc = await bind();
const state: FakeReader = {
unicast: uni.address().port,
broadcast: bc.address().port,
writes: [],
params,
singleDatagramFrames: 0,
close: () => {
uni.close();
bc.close();
},
};
const reply = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
// Real replies: header + payload in ONE datagram, id arbitrary.
sock.send(Buffer.concat([frameHeader(cmd, payload, 0x1234), payload]), rinfo.port, rinfo.address);
};
const deviceInfo = () => {
const p = parseParams(state.params);
return buildDeviceInfo({ ...p, serial });
};
const handle = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
switch (cmd) {
case QR_CMD.firmware:
return reply(sock, rinfo, 1, referenceFirmware(serial));
case QR_CMD.getParams:
return reply(sock, rinfo, 31, state.params);
case QR_CMD.search:
return reply(sock, rinfo, 3, deviceInfo());
case QR_CMD.setNetwork: {
// Applied only when the serial matches; the real reader sends NO ack.
const info = parseDeviceInfo(payload);
if (info.serial !== serial) return;
const next = Buffer.from(state.params);
next.fill(0, 0x018, 0x048);
next.write(info.server, 0x018, "utf8");
next.writeUInt32LE(info.serverPort, 0x048);
next.writeUInt32LE(info.httpLanguage, 0x04c);
state.params = next;
return;
}
case QR_CMD.outputType: {
const v = payload.readUInt32LE(0);
state.writes.push({ cmd, value: v });
if (v < 1 || v > 10) return reply(sock, rinfo, cmd + 1, Buffer.from([1])); // rejected
state.params = Buffer.from(state.params);
state.params.writeUInt8(v, 0x198);
return reply(sock, rinfo, cmd + 1, Buffer.from([0]));
}
default:
return;
}
};
// Two-datagram write discipline, like the hardware: a header announcing len > 0 waits
// for the payload datagram; a header WITH payload glued on is a single-datagram frame
// → counted and ignored.
for (const sock of [uni, bc]) {
let pending: { cmd: number; len: number } | null = null;
sock.on("message", (msg, rinfo) => {
if (pending) {
const p = pending;
pending = null;
if (msg.length === p.len) handle(sock, rinfo, p.cmd, msg);
return;
}
if (msg.length < 17 || msg.subarray(0, 4).toString("ascii") !== "XXXX") return;
const cmd = msg.readUInt32LE(8);
const len = msg.readUInt32LE(12);
if (msg.length > 17) {
state.singleDatagramFrames++;
return;
}
if (len === 0) handle(sock, rinfo, cmd, Buffer.alloc(0));
else pending = { cmd, len };
});
}
return state;
}
let reader: FakeReader | null = null;
const opts = () => ({
timeoutMs: 300,
retries: 0,
ports: { unicast: reader!.unicast, broadcast: reader!.broadcast },
});
afterEach(() => {
reader?.close();
reader = null;
});
// --- framing (worked examples from PROTOCOL.md §2) -------------------------
describe("DT-008 config frame", () => {
it("search request: magic, id 0, cmd 2, len 0, checksum 0xFF", () => {
expect(frameHeader(QR_CMD.search).toString("hex")).toBe("58585858" + "00000000" + "02000000" + "00000000" + "ff");
});
it("set buzzer on (cmd 18, u32 1): checksum 0xFF − 1 = 0xFE", () => {
const payload = Buffer.from([1, 0, 0, 0]);
expect(checksum(payload)).toBe(0xfe);
expect(frameHeader(18, payload).toString("hex")).toBe("58585858" + "00000000" + "12000000" + "04000000" + "fe");
});
it("parses a reader ack (cmd 19, one status byte) and rejects a bad checksum", () => {
const ack = Buffer.from("58585858" + "00000000" + "13000000" + "01000000" + "ff" + "00", "hex");
expect(parseFrame(ack)).toEqual({ id: 0, cmd: 19, payload: Buffer.from([0]) });
const bad = Buffer.from(ack);
bad[16] = 0x00;
expect(parseFrame(bad)).toBeNull();
expect(parseFrame(Buffer.from("YYYY", "ascii"))).toBeNull();
});
it("IPv4 is stored little-endian (bytes reversed): 10.0.10.12 → 0c 0a 00 0a", () => {
expect(ipToBytes("10.0.10.12").toString("hex")).toBe("0c0a000a");
expect(() => ipToBytes("10.0.10")).toThrow(/IPv4/);
});
});
describe("DT-008 blocks", () => {
it("decodes the reference 720-byte params", () => {
const p = parseParams(referenceParams());
expect(p).toMatchObject({
dhcp: 0,
ip: "10.0.10.12",
netmask: "255.255.255.0",
gateway: "10.0.10.1",
dns1: "8.8.8.8",
dns2: "8.8.4.4",
server: "10.0.10.204",
serverPort: 8080,
httpLanguage: 0,
outputType: QR_OUTPUT_HTTP,
cardInputFormat: 2,
lastAddEnter: 1,
restartInterval: 1,
buzzer: 0,
highPulseUs: 2000,
lowPulseUs: 400,
baudrate: 9600,
parity: 2,
qrOutputFormat: 4,
fillLight: 1,
cardPrefix: "K:",
qrPrefix: "",
});
});
it("DeviceInfo round-trips (serial, addresses, server, port, language)", () => {
const info = {
serial: "HC009E84",
ip: "10.0.10.7",
netmask: "255.255.255.0",
gateway: "0.0.0.0",
dns1: "0.0.0.0",
dns2: "0.0.0.0",
server: "10.0.10.101",
serverPort: 3000,
httpLanguage: 1,
};
const b = buildDeviceInfo(info);
expect(b.length).toBe(96);
expect(b.subarray(0, 8).toString("ascii")).toBe("HC009E84");
expect(b.readUInt32LE(88)).toBe(3000);
expect(parseDeviceInfo(b)).toEqual(info);
});
it("decodes FirmwareInfo", () => {
expect(parseFirmware(referenceFirmware())).toEqual({
model: "doorqrcode",
firmware: "ver_client1_1.1",
chip: "v3s",
hardware: "h42",
serial: "HC002721",
});
});
});
// --- transport against the fake reader ------------------------------------
describe("DT-008 config transport", () => {
it("readFirmware / readParams: unicast cmd 0 and 30, reply cmd+1", async () => {
reader = await fakeReader();
expect((await readFirmware("127.0.0.1", opts()))?.serial).toBe("HC002721");
const p = await readParams("127.0.0.1", opts());
expect(p?.server).toBe("10.0.10.204");
expect(p?.outputType).toBe(3);
expect(reader.singleDatagramFrames).toBe(0);
});
it("writeSetting sends header THEN payload (two datagrams) and returns the status byte", async () => {
reader = await fakeReader(referenceParams({ outputType: 6 })); // WG26, like park-2
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, QR_OUTPUT_HTTP, opts())).toBe(0);
expect(reader.writes).toEqual([{ cmd: 6, value: 3 }]);
expect(parseParams(reader.params).outputType).toBe(3);
expect(reader.singleDatagramFrames).toBe(0);
});
it("an out-of-range value is acknowledged with status 1 and changes nothing", async () => {
reader = await fakeReader();
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, 42, opts())).toBe(1);
expect(parseParams(reader.params).outputType).toBe(3);
});
it("no reader → null after the retries (never throws)", async () => {
reader = await fakeReader();
const dead = { ...opts(), ports: { unicast: 1, broadcast: 1 } }; // nobody listens on :1
expect(await exchange("127.0.0.1", QR_CMD.getParams, undefined, { ...dead, retries: 1 })).toBeNull();
expect(await readParams("127.0.0.1", dead)).toBeNull();
});
it("discoverReaders: cmd 2 to each broadcast, collects cmd 3 DeviceInfo, dedupes by serial", async () => {
reader = await fakeReader();
const found = await discoverReaders({ ...opts(), broadcasts: ["127.0.0.1", "127.0.0.1"] });
expect(found).toHaveLength(1);
expect(found[0]).toMatchObject({
serial: "HC002721",
ip: "10.0.10.12",
server: "10.0.10.204",
serverPort: 8080,
replyFrom: "127.0.0.1",
});
});
it("discoverReaders with no broadcast targets returns [] without touching the network", async () => {
expect(await discoverReaders({ broadcasts: [], timeoutMs: 50 })).toEqual([]);
});
it("setNetwork: broadcast cmd 32; the matching reader applies it silently (re-read to confirm)", async () => {
reader = await fakeReader();
const before = parseParams(reader.params);
await setNetwork(
{ ...before, serial: "HC002721", server: "10.0.10.101", serverPort: 3000 },
"127.0.0.1",
opts(),
);
await new Promise((r) => setTimeout(r, 50));
const after = await readParams("127.0.0.1", opts());
expect(after?.server).toBe("10.0.10.101");
expect(after?.serverPort).toBe(3000);
expect(after?.ip).toBe(before.ip); // network block preserved
});
it("setNetwork for another serial is ignored by this reader", async () => {
reader = await fakeReader();
const before = parseParams(reader.params);
await setNetwork({ ...before, serial: "HC00FFFF", server: "1.2.3.4", serverPort: 1 }, "127.0.0.1", opts());
await new Promise((r) => setTimeout(r, 50));
expect((await readParams("127.0.0.1", opts()))?.server).toBe("10.0.10.204");
});
});
@@ -0,0 +1,483 @@
import { createSocket, type Socket } from "node:dgram";
import { networkInterfaces } from "node:os";
// Dingtian DT-008 QR/RFID reader — CONFIGURATION protocol (UDP). This is what the
// vendor's Windows-only `QRCode_v1_6_5.exe` speaks for "Search device" / "Get parameter"
// / the Set buttons; reversed in wiki/raw/dingtian_qr_linux/PROTOCOL.md and verified on
// real readers (bench HC002721; park-2's two units read with it on 2026-10-08). Lets the
// setup wizard FIND readers on the device VLAN and put a freshly assigned reader into HTTP
// mode pointing at this booth — instead of a Windows laptop on site. The scan push itself
// (HTTP GET /qa/mcardsea.<ext>) is a different protocol, handled by routes/qr-reader.ts.
//
// Frame (both directions, little-endian):
// 'XXXX' | id u32 | cmd u32 | len u32 | checksum u8 (0xFF − Σpayload) | payload
// Even cmd = request/write, reply = cmd + 1. QUIRK: the reader only accepts a write when
// the 17-byte header and the payload arrive as TWO datagrams (header first); a single
// datagram is silently ignored. Replies come as one datagram, from an arbitrary source
// port. Reader listens on 24680 (unicast: 0 firmware, 30 params, every field write) and
// 24582 (broadcast: 2 search, 32 set-network). set-network is applied but NOT acknowledged
// by the real reader — verify it by re-reading the params (cmd 30).
//
// SECURITY: unauthenticated UDP, like the relay board — the reader sits on the isolated
// device VLAN reachable only by the host (wiki/concepts/network-isolation.md).
export const QR_PORT_UNICAST = 24680;
export const QR_PORT_BROADCAST = 24582;
const MAGIC = Buffer.from("XXXX", "ascii");
const HEADER_LEN = 17;
const PARAMS_LEN = 720;
const DEVICE_INFO_LEN = 96;
const FIRMWARE_LEN = 64;
/** Command numbers (requests; the reply is cmd + 1). */
export const QR_CMD = {
firmware: 0,
search: 2,
outputType: 6,
cardInputFormat: 8,
getParams: 30,
setNetwork: 32,
} as const;
/** `output type` values on the wire (cmd 6 / Params 0x198). Only HTTP contacts the booth;
* in every other mode the reader beeps locally and the scan goes elsewhere. */
export const QR_OUTPUT_HTTP = 3;
export const QR_OUTPUT_TYPES: Record<number, string> = {
1: "USB virtual keyboard",
2: "USB virtual serial port",
3: "HTTP",
4: "MQTT",
5: "RS232",
6: "WG26",
7: "WG34",
8: "RS485",
9: "AC Output",
10: "TCP",
};
export const QR_CARD_INPUT_FORMATS: Record<number, string> = {
1: "6H",
2: "8H",
3: "8H10D",
4: "6H10D",
5: "2H3D+4H5D",
};
export const QR_HTTP_LANGUAGES: Record<number, string> = {
0: "PHP",
1: "JSP",
2: "C#",
3: "ASP",
4: "CGI",
};
export function outputTypeName(v: number): string {
return QR_OUTPUT_TYPES[v] ?? `unknown (${v})`;
}
export interface QrOptions {
/** Per-attempt reply wait. */
readonly timeoutMs?: number;
/** Extra attempts after the first (the exe never retries; UDP can drop). */
readonly retries?: number;
/** Port overrides (tests run a fake reader on loopback ephemeral ports). */
readonly ports?: { readonly unicast?: number; readonly broadcast?: number };
}
const DEFAULT_TIMEOUT_MS = 1500;
const DEFAULT_RETRIES = 1;
// --- framing ---------------------------------------------------------------
export function checksum(payload: Buffer): number {
let sum = 0;
for (const b of payload) sum += b;
return (0xff - sum) & 0xff;
}
/** The 17-byte header for `cmd` + `payload` (the payload is sent as its own datagram). */
export function frameHeader(cmd: number, payload: Buffer = Buffer.alloc(0), id = 0): Buffer {
const h = Buffer.alloc(HEADER_LEN);
MAGIC.copy(h, 0);
h.writeUInt32LE(id >>> 0, 4);
h.writeUInt32LE(cmd >>> 0, 8);
h.writeUInt32LE(payload.length, 12);
h.writeUInt8(checksum(payload), 16);
return h;
}
export interface QrFrame {
readonly id: number;
readonly cmd: number;
readonly payload: Buffer;
}
/** Parse a reply datagram (header + payload in one). null = not a valid frame. */
export function parseFrame(datagram: Buffer): QrFrame | null {
if (datagram.length < HEADER_LEN || !datagram.subarray(0, 4).equals(MAGIC)) return null;
const id = datagram.readUInt32LE(4);
const cmd = datagram.readUInt32LE(8);
const len = datagram.readUInt32LE(12);
const payload = datagram.subarray(HEADER_LEN, HEADER_LEN + len);
if (payload.length !== len || checksum(payload) !== datagram.readUInt8(16)) return null;
return { id, cmd, payload };
}
// --- field codecs ----------------------------------------------------------
/** IPv4 as the reader stores it: little-endian u32 = the dotted bytes REVERSED. */
export function ipToBytes(ip: string): Buffer {
const parts = ip.split(".").map(Number);
if (parts.length !== 4 || parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) {
throw new Error(`not an IPv4 address: ${ip}`);
}
return Buffer.from(parts.reverse());
}
export function bytesToIp(b: Buffer, off: number): string {
return `${b[off + 3]}.${b[off + 2]}.${b[off + 1]}.${b[off]}`;
}
function cstr(b: Buffer, off: number, len: number): string {
const s = b.subarray(off, off + len);
const nul = s.indexOf(0);
return s.subarray(0, nul < 0 ? s.length : nul).toString("utf8");
}
function putStr(b: Buffer, off: number, len: number, s: string): void {
b.fill(0, off, off + len);
// Leave the last byte NUL (the exe caps the 48-byte server field at 47 chars).
b.write(s, off, len - 1, "utf8");
}
// --- blocks ----------------------------------------------------------------
/** 96-byte DeviceInfo: the search reply (cmd 3) and the set-network payload (cmd 32). */
export interface QrDeviceInfo {
readonly serial: string;
readonly ip: string;
readonly netmask: string;
readonly gateway: string;
readonly dns1: string;
readonly dns2: string;
/** Hostname or IP the reader pushes scans to (factory: "ipc.fondvision.com"). */
readonly server: string;
readonly serverPort: number;
/** 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI — only picks the push URL's extension. */
readonly httpLanguage: number;
}
export function parseDeviceInfo(b: Buffer): QrDeviceInfo {
if (b.length < DEVICE_INFO_LEN) throw new Error(`DeviceInfo too short: ${b.length}`);
return {
serial: cstr(b, 0, 20),
ip: bytesToIp(b, 20),
netmask: bytesToIp(b, 24),
gateway: bytesToIp(b, 28),
dns1: bytesToIp(b, 32),
dns2: bytesToIp(b, 36),
server: cstr(b, 40, 48),
serverPort: b.readUInt32LE(88),
httpLanguage: b.readUInt32LE(92),
};
}
export function buildDeviceInfo(info: QrDeviceInfo): Buffer {
const b = Buffer.alloc(DEVICE_INFO_LEN);
putStr(b, 0, 20, info.serial);
ipToBytes(info.ip).copy(b, 20);
ipToBytes(info.netmask).copy(b, 24);
ipToBytes(info.gateway).copy(b, 28);
ipToBytes(info.dns1).copy(b, 32);
ipToBytes(info.dns2).copy(b, 36);
putStr(b, 40, 48, info.server);
b.writeUInt32LE(info.serverPort >>> 0, 88);
b.writeUInt32LE(info.httpLanguage >>> 0, 92);
return b;
}
/** 64-byte FirmwareInfo (reply 1). */
export interface QrFirmware {
readonly model: string; // "doorqrcode"
readonly firmware: string; // "ver_client1_1.1"
readonly chip: string; // "v3s"
readonly hardware: string; // "h42"
readonly serial: string; // "HC002721"
}
export function parseFirmware(b: Buffer): QrFirmware {
if (b.length < FIRMWARE_LEN) throw new Error(`FirmwareInfo too short: ${b.length}`);
return {
model: cstr(b, 0, 16),
firmware: cstr(b, 16, 16),
chip: cstr(b, 32, 8),
hardware: cstr(b, 40, 8),
serial: cstr(b, 48, 16),
};
}
/** The 720-byte parameter struct (reply 31). Only the fields the exe shows are decoded. */
export interface QrParams {
readonly dhcp: number;
readonly ip: string;
readonly netmask: string;
readonly gateway: string;
readonly dns1: string;
readonly dns2: string;
readonly server: string;
readonly serverPort: number;
readonly httpLanguage: number;
/** See QR_OUTPUT_TYPES; 3 = HTTP. */
readonly outputType: number;
/** See QR_CARD_INPUT_FORMATS; 1 = 6H. */
readonly cardInputFormat: number;
readonly lastAddEnter: number;
readonly lastAddNewline: number;
readonly qrPrefix: string;
readonly qrSuffix: string;
readonly restartInterval: number;
readonly workMode: number;
readonly buzzer: number;
readonly highPulseUs: number;
readonly lowPulseUs: number;
readonly baudrate: number;
readonly dataBits: number;
readonly stopBits: number;
readonly parity: number;
readonly qrOutputFormat: number;
readonly fillLight: number;
readonly cardOutputFormat: number;
readonly cardPrefix: string;
readonly cardSuffix: string;
}
export function parseParams(b: Buffer): QrParams {
if (b.length < PARAMS_LEN) throw new Error(`Params too short: ${b.length}`);
return {
dhcp: b.readUInt32LE(0x000),
ip: bytesToIp(b, 0x004),
netmask: bytesToIp(b, 0x008),
gateway: bytesToIp(b, 0x00c),
dns1: bytesToIp(b, 0x010),
dns2: bytesToIp(b, 0x014),
server: cstr(b, 0x018, 48),
serverPort: b.readUInt32LE(0x048),
httpLanguage: b.readUInt32LE(0x04c),
outputType: b.readUInt8(0x198),
cardInputFormat: b.readUInt8(0x19c),
lastAddEnter: b.readUInt8(0x1a0),
lastAddNewline: b.readUInt8(0x1a1),
qrPrefix: cstr(b, 0x1a8, 32),
qrSuffix: cstr(b, 0x1cc, 32),
restartInterval: b.readUInt32LE(0x1ec),
workMode: b.readUInt32LE(0x1f0),
buzzer: b.readUInt32LE(0x1f8),
highPulseUs: b.readUInt32LE(0x1fc) * 100,
lowPulseUs: b.readUInt32LE(0x200) * 100,
baudrate: b.readUInt32LE(0x204),
dataBits: b.readUInt32LE(0x208),
stopBits: b.readUInt32LE(0x20c),
parity: b.readUInt32LE(0x210),
qrOutputFormat: b.readUInt32LE(0x214),
fillLight: b.readUInt32LE(0x218),
cardOutputFormat: b.readUInt32LE(0x288),
cardPrefix: cstr(b, 0x290, 32),
cardSuffix: cstr(b, 0x2b0, 32),
};
}
// --- transport -------------------------------------------------------------
function openSocket(): Promise<Socket> {
return new Promise((resolve, reject) => {
const s = createSocket({ type: "udp4", reuseAddr: true });
s.once("error", reject);
s.bind(0, "0.0.0.0", () => {
s.removeListener("error", reject);
resolve(s);
});
});
}
function sendTo(sock: Socket, host: string, port: number, buf: Buffer): Promise<void> {
return new Promise((resolve, reject) => {
sock.send(buf, port, host, (err) => (err ? reject(err) : resolve()));
});
}
/** Send `cmd` the way the exe does: the header datagram, then the payload datagram. */
async function sendCommand(sock: Socket, host: string, port: number, cmd: number, payload: Buffer): Promise<void> {
await sendTo(sock, host, port, frameHeader(cmd, payload));
if (payload.length) await sendTo(sock, host, port, payload);
}
/** Collect reply frames matching `want` for up to `ms`, calling `onFrame` for each;
* resolves early when `onFrame` returns true (= done). */
function collect(
sock: Socket,
ms: number,
onFrame: (f: QrFrame, from: string) => boolean,
): Promise<void> {
return new Promise((resolve) => {
const done = () => {
clearTimeout(timer);
sock.removeListener("message", onMsg);
resolve();
};
const onMsg = (msg: Buffer, rinfo: { address: string }) => {
const f = parseFrame(msg);
if (f && onFrame(f, rinfo.address)) done();
};
const timer = setTimeout(done, ms);
sock.on("message", onMsg);
});
}
/** Unicast `cmd` to the reader and await the `cmd + 1` reply payload; null = no reply. */
export async function exchange(
host: string,
cmd: number,
payload: Buffer = Buffer.alloc(0),
opts: QrOptions = {},
): Promise<Buffer | null> {
const port = opts.ports?.unicast ?? QR_PORT_UNICAST;
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const retries = opts.retries ?? DEFAULT_RETRIES;
const sock = await openSocket();
try {
for (let attempt = 0; attempt <= retries; attempt++) {
await sendCommand(sock, host, port, cmd, payload);
let got: Buffer | null = null;
await collect(sock, timeoutMs, (f) => {
if (f.cmd !== cmd + 1) return false;
got = f.payload;
return true;
});
if (got) return got;
}
return null;
} finally {
sock.close();
}
}
export async function readFirmware(host: string, opts?: QrOptions): Promise<QrFirmware | null> {
const b = await exchange(host, QR_CMD.firmware, undefined, opts);
return b && b.length >= FIRMWARE_LEN ? parseFirmware(b) : null;
}
export async function readParams(host: string, opts?: QrOptions): Promise<QrParams | null> {
const b = await exchange(host, QR_CMD.getParams, undefined, opts);
return b && b.length >= PARAMS_LEN ? parseParams(b) : null;
}
/** Write one u32 setting (cmd 6 output type, 8 card input format, 18 work mode, 22
* buzzer, …). Resolves the reader's status byte: 0 = applied (immediately, no reboot),
* 1 = rejected (out of range); null = no acknowledgement. */
export async function writeSetting(
host: string,
cmd: number,
value: number,
opts?: QrOptions,
): Promise<number | null> {
const payload = Buffer.alloc(4);
payload.writeUInt32LE(value >>> 0, 0);
const b = await exchange(host, cmd, payload, opts);
return b && b.length >= 1 ? b.readUInt8(0) : null;
}
/**
* Set the reader's network block (IP/netmask/gateway/DNS, push server + port, URL
* language) — cmd 32, an L2 BROADCAST that only the reader whose serial matches applies.
* The real reader applies it without replying, so this resolves after sending; the caller
* must re-read the params to confirm. `broadcast` is the subnet-directed address
* (e.g. 10.0.10.255 — see subnetBroadcastFor); the global 255.255.255.255 is refused by
* the kernel on some hosts (EACCES) and is not what the exe sends.
*/
export async function setNetwork(info: QrDeviceInfo, broadcast: string, opts: QrOptions = {}): Promise<void> {
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
const sock = await openSocket();
try {
sock.setBroadcast(true);
await sendCommand(sock, broadcast, port, QR_CMD.setNetwork, buildDeviceInfo(info));
} finally {
sock.close();
}
}
export interface DiscoveredReader extends QrDeviceInfo {
/** Address the reply came from (normally = ip). */
readonly replyFrom: string;
}
/**
* Search the LAN: cmd 2 to every subnet-directed broadcast (one per local IPv4 interface
* unless `broadcasts` is given), collect cmd 3 replies for `timeoutMs`, dedupe by serial.
* Readers must share an L2 segment with the host — fine on the booth (host network) and
* the device VLAN; impossible from a bridged dev container or across Netbird.
*/
export async function discoverReaders(
opts: QrOptions & { readonly broadcasts?: readonly string[] } = {},
): Promise<DiscoveredReader[]> {
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
const timeoutMs = opts.timeoutMs ?? 2000;
const targets = opts.broadcasts ?? subnetBroadcasts();
if (targets.length === 0) return [];
const sock = await openSocket();
const found = new Map<string, DiscoveredReader>();
try {
sock.setBroadcast(true);
for (const b of targets) {
// One unreachable interface must not abort the whole scan.
await sendCommand(sock, b, port, QR_CMD.search, Buffer.alloc(0)).catch(() => {});
}
await collect(sock, timeoutMs, (f, from) => {
if (f.cmd === QR_CMD.search + 1 && f.payload.length >= DEVICE_INFO_LEN) {
const info = parseDeviceInfo(f.payload);
found.set(info.serial, { ...info, replyFrom: from });
}
return false; // keep collecting until the deadline
});
} finally {
sock.close();
}
return [...found.values()];
}
// --- local network helpers -------------------------------------------------
function parseV4(s: string): number[] | null {
const p = s.split(".").map(Number);
return p.length === 4 && p.every((o) => Number.isInteger(o) && o >= 0 && o <= 255) ? p : null;
}
/** Subnet-directed broadcast addresses of every non-loopback local IPv4 interface. */
export function subnetBroadcasts(): string[] {
const out = new Set<string>();
for (const ifaces of Object.values(networkInterfaces())) {
for (const i of ifaces ?? []) {
if (i.family !== "IPv4" || i.internal) continue;
const a = parseV4(i.address);
const m = parseV4(i.netmask);
if (!a || !m) continue;
out.add(a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join("."));
}
}
return [...out];
}
/** The subnet-directed broadcast of the local interface whose subnet contains `host`;
* null when no directly attached interface does (set-network can't reach it then). */
export function subnetBroadcastFor(host: string): string | null {
const h = parseV4(host);
if (!h) return null;
for (const ifaces of Object.values(networkInterfaces())) {
for (const i of ifaces ?? []) {
if (i.family !== "IPv4" || i.internal) continue;
const a = parseV4(i.address);
const m = parseV4(i.netmask);
if (!a || !m) continue;
const same = h.every((o, k) => (o & m[k]!) === (a[k]! & m[k]!));
if (same) return a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join(".");
}
}
return null;
}
+3
View File
@@ -6,6 +6,7 @@ import { dingtianDriver } from "./access-dingtian.js";
import { stubAccessDriver } from "./access-stub.js";
import { dahuaDriver, hikvisionDriver } from "./camera.js";
import { escposDriver } from "./printer-generic.js";
import { k200lDriver } from "./printer-k200l.js";
import { rongtaDriver } from "./printer-rongta.js";
import { dingtianQrReaderDriver, tcpipReaderDriver, wiegandReaderDriver } from "./reader.js";
@@ -23,6 +24,7 @@ export function registerBuiltinDrivers(): void {
registry.register(hikvisionDriver);
registry.register(dahuaDriver);
registry.register(rongtaDriver);
registry.register(k200lDriver);
registry.register(escposDriver);
}
@@ -35,5 +37,6 @@ export {
hikvisionDriver,
dahuaDriver,
rongtaDriver,
k200lDriver,
escposDriver,
};
@@ -37,6 +37,8 @@ import {
// local usblp char device (/dev/usb/lp0); TCP writes to the raw print socket. This
// clone family is the natural USB candidate — reachability-only, no page to lose.
//
// (The K200L / XP-K200L is the exception: its LAN board DOES serve a status page,
// /prt_status.htm — use the `k200l` driver for it over TCP; see printer-k200l.ts.)
// Therefore this driver deliberately does NOT implement MonitorableDevice
// (no readStatus). The device monitor then falls back to the generic
// `healthCheck()` — a plain TCP reachability PING of the print socket. So the
@@ -0,0 +1,230 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createServer, type Server } from "node:net";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseRawReply, parseStatusPage, k200lDriver } from "./printer-k200l.js";
import { renderTicket } from "./printer-escpos.js";
import type { MonitorableDevice, PrinterDevice } from "../interfaces.js";
// The K200L (Xprinter / ICS; J-Speed 'POS-80' LAN board) driver. Its status page was captured verbatim
// from the unit on the lab bench, 2026-09-09: uppercase tags, values padded with
// spaces, and — the part that matters — the board's reply has NO status line and NO
// headers (the body starts at byte 0). The tests replay exactly that over a raw
// socket, plus a proper-HTTP variant, so the driver is proven against both.
/** The board's status table, as sent (CRLF, uppercase, padded values). */
function boardPage(flags: Partial<Record<string, "Yes" | "No">> = {}): string {
const v = (k: string) => `${flags[k] ?? "No"} `;
return [
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">',
"<HTML><HEAD><TITLE>Printer Status</TITLE>",
"<META http-equiv=refresh content=\"5;url='prt_status.htm'\"></HEAD>",
'<BODY><FORM id=Form1 action="prt_status.htm" method="get">',
"<TABLE id=Table3 cellPadding=3 border=0><TBODY>",
`<TR><TD>Cover Is Open</TD><TD style="width: 23px">${v("cover")}</TD></TR>`,
`<TR><TD>Cutter Error</TD><TD style="width: 23px">${v("cutter")}</TD></TR>`,
`<TR><TD>Paper End</TD><TD style="width: 23px">${v("paperEnd")}</TD></TR>`,
`<TR><TD>Paper Near End</TD><TD style="width: 23px">${v("nearEnd")}</TD></TR>`,
`<TR><TD>Printer Off-Line</TD><TD style="width: 23px">${v("offline")}</TD></TR></TBODY></TABLE>`,
'<INPUT type=submit value="Print Test Page" name=page_p2></FORM></BODY></HTML>',
].join("\r\n");
}
const INDEX =
"<HTML><HEAD><TITLE>Ethernet port configuration</TITLE></HEAD><BODY><TABLE><TR><TD>Mac Address</TD><TD>00-D8-23-5C-58-8C</TD></TR></TABLE></BODY></HTML>";
type Reply = { body: string; status?: number; raw?: boolean };
describe("parseRawReply", () => {
it("treats a reply without a status line as HTTP/0.9: the whole reply is the body", () => {
const r = parseRawReply("<!DOCTYPE HTML><HTML>x</HTML>");
expect(r.status).toBe(200);
expect(r.body).toBe("<!DOCTYPE HTML><HTML>x</HTML>");
});
it("splits a real HTTP reply into status and body", () => {
const r = parseRawReply("HTTP/1.0 404 Not Found\r\nContent-Type: text/html\r\n\r\n<b>nope</b>");
expect(r.status).toBe(404);
expect(r.body).toBe("<b>nope</b>");
});
});
describe("parseStatusPage", () => {
it("reads the board's padded, uppercase table", () => {
const f = parseStatusPage(boardPage({ cover: "Yes", nearEnd: "Yes" }));
expect(f).toEqual({ coverOpen: true, cutterError: false, paperEnd: false, paperNearEnd: true, offline: false });
});
it("leaves unknown pages empty rather than guessing", () => {
expect(parseStatusPage(INDEX)).toEqual({});
});
it("reads a fault's Yes, which the board wraps in <FONT color=#ff0000> (captured live, cover open)", () => {
// Verbatim from the unit on 2026-09-09 with the cover open: the three fault cells carry
// markup the No cells don't — the first parser rejected them ("missing coverOpen,
// paperEnd, offline" on the booth) while the No cells parsed.
const page = boardPage()
.replace("Cover Is Open</TD><TD style=\"width: 23px\">No ", "Cover Is Open</TD><TD style=\"width: 23px\"><FONT color=#ff0000>Yes</FONT> ")
.replace("Paper End</TD><TD style=\"width: 23px\">No ", "Paper End</TD><TD style=\"width: 23px\"><FONT color=#ff0000>Yes</FONT> ")
.replace("Printer Off-Line</TD><TD style=\"width: 23px\">No ", "Printer Off-Line</TD><TD style=\"width: 23px\"><FONT color=#ff0000>Yes</FONT> ");
expect(parseStatusPage(page)).toEqual({ coverOpen: true, cutterError: false, paperEnd: true, paperNearEnd: false, offline: true });
});
it("tolerates other markup shapes around a value", () => {
const page = boardPage()
.replace("Paper End</TD><TD style=\"width: 23px\">No ", "Paper End</TD><TD style=\"width: 23px\"><B><FONT color=\"#ff0000\">Yes </FONT></B>")
.replace("Printer Off-Line</TD><TD style=\"width: 23px\">No ", "Printer Off-Line</TD>\r\n<TD style=\"width: 23px\">\r\n<font>Yes</font>\r\n");
expect(parseStatusPage(page)).toEqual({ coverOpen: false, cutterError: false, paperEnd: true, paperNearEnd: false, offline: true });
});
it("reads labels wrapped in markup too", () => {
const page = boardPage({ nearEnd: "Yes" }).replace("<TD>Paper Near End</TD>", "<TD><B>Paper&nbsp;Near End</B></TD>");
expect(parseStatusPage(page).paperNearEnd).toBe(true);
});
});
describe("k200lDriver.readStatus over TCP", () => {
let server: Server | undefined;
const sockets = new Set<import("node:net").Socket>();
/** A raw TCP server that answers like the board (no status line) unless the reply
* says otherwise, and closes after the reply (HTTP/1.0). */
async function serve(reply: (path: string) => Reply): Promise<number> {
server = createServer((sock) => {
sockets.add(sock);
sock.on("close", () => sockets.delete(sock));
sock.once("data", (d) => {
const path = /^GET (\S+)/.exec(d.toString())?.[1] ?? "";
const r = reply(path);
if (r.raw === false) {
sock.end(`HTTP/1.0 ${r.status ?? 200} OK\r\nContent-Type: text/html\r\n\r\n${r.body}`);
} else {
sock.end(r.body);
}
});
});
await new Promise<void>((r) => server!.listen(0, "127.0.0.1", () => r()));
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("no port");
return addr.port;
}
afterEach(async () => {
for (const s of sockets) s.destroy();
sockets.clear();
if (server) await new Promise<void>((r) => server!.close(() => r()));
server = undefined;
});
function device(httpPort: number): MonitorableDevice & { driverId: string } {
return k200lDriver.create({ transport: "tcp-ip", host: "127.0.0.1", port: 9100, httpPort, timeoutMs: 1000 }) as unknown as MonitorableDevice & {
driverId: string;
};
}
it("reads the headerless reply: cover open + paper out + off-line → degraded, flags set", async () => {
const port = await serve((p) => (p === "/prt_status.htm" ? { body: boardPage({ cover: "Yes", paperEnd: "Yes", offline: "Yes" }) } : { body: INDEX }));
const dev = device(port);
expect(dev.driverId).toBe("k200l");
const s = await dev.readStatus();
expect(s.status).toBe("degraded");
expect(s.coverOpen).toBe(true);
expect(s.paperEnd).toBe(true);
expect(s.offline).toBe(true);
expect(s.cutterError).toBe(false);
expect(s.paperNearEnd).toBe(false);
expect(s.detail).toBe("cover open, paper out, printer off-line");
});
it("healthy printer → ready, every flag false", async () => {
const port = await serve(() => ({ body: boardPage() }));
const s = await device(port).readStatus();
expect(s.status).toBe("ready");
expect(s.coverOpen).toBe(false);
expect(s.detail).toBeUndefined();
});
it("paper near end alone → degraded 'paper low' (still prints, warn to reload)", async () => {
const port = await serve(() => ({ body: boardPage({ nearEnd: "Yes" }) }));
const s = await device(port).readStatus();
expect(s.status).toBe("degraded");
expect(s.paperNearEnd).toBe(true);
expect(s.detail).toBe("paper low");
});
it("also understands a proper HTTP reply (a board firmware that sends headers)", async () => {
const port = await serve(() => ({ body: boardPage({ cutter: "Yes" }), raw: false }));
const s = await device(port).readStatus();
expect(s.status).toBe("degraded");
expect(s.detail).toBe("cutter error");
});
it("a page without the status rows (the index) → degraded 'unexpected status page', never ready", async () => {
const port = await serve(() => ({ body: INDEX }));
const s = await device(port).readStatus();
expect(s.status).toBe("degraded");
expect(s.detail).toContain("unexpected status page");
expect(s.detail).toContain("missing");
});
it("a non-200 reply → degraded naming the code, never ready", async () => {
const port = await serve(() => ({ body: "", status: 404, raw: false }));
const s = await device(port).readStatus();
expect(s.status).toBe("degraded");
expect(s.detail).toContain("HTTP 404");
});
it("board unreachable (connection refused) → offline", async () => {
const port = await serve(() => ({ body: "" }));
await new Promise<void>((r) => server!.close(() => r()));
server = undefined;
const s = await device(port).readStatus();
expect(s.status).toBe("offline");
expect(s.detail).toMatch(/ECONNREFUSED/);
});
it("a board that accepts but never answers → offline 'status page timeout'", async () => {
server = createServer((sock) => {
sockets.add(sock); // hold the socket open, say nothing
sock.on("close", () => sockets.delete(sock));
});
await new Promise<void>((r) => server!.listen(0, "127.0.0.1", () => r()));
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("no port");
const dev = k200lDriver.create({ transport: "tcp-ip", host: "127.0.0.1", port: 9100, httpPort: addr.port, timeoutMs: 200 }) as unknown as MonitorableDevice;
const s = await dev.readStatus();
expect(s.status).toBe("offline");
expect(s.detail).toBe("status page timeout");
});
});
describe("k200lDriver — printing and USB are the generic ESC/POS path", () => {
let dir: string;
let devicePath: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "k200l-usb-"));
devicePath = join(dir, "lp0");
writeFileSync(devicePath, "");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it("prints the same ticket bytes the generic driver would, to the USB node", async () => {
const printer = k200lDriver.create({ transport: "usb", devicePath, timeoutMs: 1000 }) as PrinterDevice;
const data = { ticketId: "12345678901", issuedAt: "2026-09-09T10:00:00.000Z" };
await printer.printTicket(data);
expect(readFileSync(devicePath).equals(renderTicket(data))).toBe(true);
});
it("over USB readStatus is the reachability floor: ready when the node opens, offline when absent", async () => {
const present = k200lDriver.create({ transport: "usb", devicePath, timeoutMs: 1000 }) as unknown as MonitorableDevice;
expect((await present.readStatus()).status).toBe("ready");
const absent = k200lDriver.create({ transport: "usb", devicePath: join(dir, "absent"), timeoutMs: 1000 }) as unknown as MonitorableDevice;
expect((await absent.readStatus()).status).toBe("offline");
});
it("advertises both transports and exposes the status-page port after the print port", () => {
expect(k200lDriver.transports).toEqual(["tcp-ip", "usb"]);
const keys = k200lDriver.configFields.map((f) => f.key);
expect(keys.indexOf("httpPort")).toBe(keys.indexOf("port") + 1);
expect(keys).toContain("role");
});
});
@@ -0,0 +1,262 @@
import { connect as netConnect } from "node:net";
import type {
DeviceHealth,
MonitorableDevice,
PrinterDevice,
PrinterStatus,
PrintReport,
ReceiptData,
SubscriptionCardData,
TicketData,
WindowChargeNoticeData,
} from "../interfaces.js";
import type { ConfigField, DeviceConfig, PrinterDriver } from "../registry.js";
import { stubLog } from "./common.js";
import { transportFromConfig } from "./printer-escpos.js";
import { escposDriver } from "./printer-generic.js";
// K200L 80mm ESC/POS thermal printer (Xprinter / ICS "XP-K200L" family; label:
// "THERMAL RECEIPT PRINTER Model:K200L, Interface: USB+LAN, Command Support: ESC/POS").
// Its LAN board is the "J-Speed Ethernet Interface Module" (web UI "Ethernet WebConfig
// 1.02") and calls the printer "POS-80" — over USB it enumerates as 1fc9:2016
// "Printer POS-80". Identified on the lab bench 2026-09-09: it is the park-buzi unit.
// See wiki/entities/k200l-printer.md.
//
// PRINTING is the shared ESC/POS path (delegated to the generic driver — same bytes,
// same TCP-9100 / usblp transports). What this driver ADDS is live status: the board
// serves a status page, /prt_status.htm, with the same five decoded Yes/No rows the
// Rongta board serves under /prn_stat.htm (cover open, cutter error, paper end, paper
// near end, off-line). So over TCP the operator gets a real paper/cover verdict —
// the generic driver deliberately can't (reachability only), and the Rongta driver
// can't read THIS board either: its reply carries NO status line and NO headers
// (HTTP/0.9 style — the body starts at byte 0), which Node's http client rejects
// ("Parse Error: Expected HTTP/"). Hence the raw-socket fetch below, tolerant of both
// shapes. Over USB there is no page; status degrades to the reachability floor.
//
// Board facts worth knowing (all verified on the bench): factory address
// 192.168.123.100, DHCP off; web configurator on port 80 (Information / Configuration
// / Printer Status / Printer Test); the frameset reloads its frames every 1–3 s and
// the status page every 5 s, and the embedded HTTP server is tiny — leave the browser
// closed while the monitor polls, or connects will intermittently time out.
/** The fault flags the status page reports (a subset of PrinterStatus). */
type StatusFlag = "coverOpen" | "cutterError" | "paperEnd" | "paperNearEnd" | "offline";
type StatusFlags = Partial<Record<StatusFlag, boolean>>;
/** Label text on the status page (space-normalised, lowercased) → our key. */
const STATUS_FIELDS: Record<string, StatusFlag> = {
"cover is open": "coverOpen",
"cutter error": "cutterError",
"paper end": "paperEnd",
"paper near end": "paperNearEnd",
"printer off-line": "offline",
};
const EXPECTED: readonly StatusFlag[] = ["coverOpen", "cutterError", "paperEnd", "paperNearEnd", "offline"];
const LABELS: Record<StatusFlag, string> = {
paperEnd: "paper out",
coverOpen: "cover open",
cutterError: "cutter error",
offline: "printer off-line",
paperNearEnd: "paper low",
};
/** The board's status page. */
export const K200L_STATUS_PATH = "/prt_status.htm";
/**
* GET `path` over a raw TCP socket and return whatever the board sent, verbatim,
* once it closes the connection (HTTP/1.0 semantics — the board closes after the
* reply). No HTTP parsing here: this board answers without a status line, which
* node:http refuses to parse.
*/
export function fetchRaw(host: string, port: number, path: string, timeoutMs: number): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let settled = false;
const sock = netConnect({ host, port });
const timer = setTimeout(() => {
finish(() => reject(new Error("status page timeout")));
sock.destroy();
}, timeoutMs);
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
fn();
};
sock.setNoDelay(true);
sock.on("connect", () => {
sock.write(`GET ${path} HTTP/1.0\r\nHost: ${host}\r\nConnection: close\r\n\r\n`);
});
sock.on("data", (c: Buffer) => chunks.push(c));
sock.on("error", (err) => finish(() => reject(err)));
sock.on("close", () => finish(() => resolve(Buffer.concat(chunks).toString("latin1"))));
});
}
/**
* Split a raw reply into its HTTP status and body. A reply that starts with a status
* line is real HTTP (status + headers, body after the blank line); anything else is
* the HTTP/0.9-style reply this board sends — the whole thing IS the body, status 200.
*/
export function parseRawReply(raw: string): { status: number; body: string } {
const m = /^HTTP\/\d\.\d\s+(\d{3})[^\r\n]*\r?\n/.exec(raw);
if (!m) return { status: 200, body: raw };
const sep = raw.search(/\r?\n\r?\n/);
const body = sep === -1 ? "" : raw.slice(sep).replace(/^\r?\n\r?\n/, "");
return { status: Number(m[1]), body };
}
/** A cell's visible text: inner tags stripped (the board wraps a "Yes" in markup the
* "No" cells don't carry), entities and padding normalised, lowercased. */
function cellText(inner: string): string {
return inner
.replace(/<[^>]*>/g, "")
.replace(/&nbsp;/gi, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
/**
* Parse the status table into boolean flags. Each fault is a `<TD>label</TD>
* <TD>Yes|No</TD>` pair (the board pads the value with spaces, and may wrap a fault's
* "Yes" in its own tags — 2026-09-09, seen live as "missing coverOpen, paperEnd,
* offline" with the cover open, i.e. exactly the Yes cells). Returns only the
* recognised fields; a missing field stays undefined so the caller can detect an
* unexpected page (fail safe, not a false "ok").
*/
export function parseStatusPage(html: string): StatusFlags {
const out: StatusFlags = {};
const rowRe = /<TR[^>]*>\s*<TD[^>]*>([\s\S]*?)<\/TD>\s*<TD[^>]*>([\s\S]*?)<\/TD>/gi;
let m: RegExpExecArray | null;
while ((m = rowRe.exec(html))) {
if (m[1] === undefined || m[2] === undefined) continue;
const key = STATUS_FIELDS[cellText(m[1])];
const value = cellText(m[2]);
if (key && (value === "yes" || value === "no")) out[key] = value === "yes";
}
return out;
}
class K200lPrinter implements PrinterDevice, MonitorableDevice {
readonly driverId = "k200l";
/** The print path — the generic ESC/POS device built from the SAME config. */
readonly #print: PrinterDevice;
readonly #tcp: boolean;
readonly #host: string;
readonly #httpPort: number;
readonly #timeout: number;
constructor(config: DeviceConfig) {
this.#print = escposDriver.create(config) as PrinterDevice;
this.#tcp = transportFromConfig(config).kind === "tcp";
this.#host = config.host ? String(config.host) : "";
this.#httpPort = config.httpPort ? Number(config.httpPort) : 80;
this.#timeout = config.timeoutMs ? Number(config.timeoutMs) : 3000;
}
async connect(): Promise<void> {
await this.#print.connect();
}
async disconnect(): Promise<void> {
await this.#print.disconnect();
stubLog(this.driverId, "disconnect");
}
healthCheck(): Promise<DeviceHealth> {
return this.#print.healthCheck();
}
printTicket(data: TicketData): Promise<void> {
return this.#print.printTicket(data);
}
printReport(report: PrintReport): Promise<void> {
return this.#print.printReport(report);
}
printSubscriptionCard(data: SubscriptionCardData): Promise<void> {
return this.#print.printSubscriptionCard(data);
}
printReceipt(data: ReceiptData): Promise<void> {
return this.#print.printReceipt(data);
}
printWindowChargeNotice(data: WindowChargeNoticeData): Promise<void> {
return this.#print.printWindowChargeNotice(data);
}
/**
* Live operator-actionable status from the board's own page.
* - USB: no page — reachability floor only (ready/offline, never a guessed state);
* - board unreachable / timeout → offline (the same signal as a dead printer);
* - page reachable but not the status table (wrong path, index served, non-200) →
* degraded ("unexpected status page") — never "ready" off a page we didn't read;
* - any fault flag true → degraded, with the faults named; otherwise → ready.
*/
async readStatus(): Promise<PrinterStatus> {
const checkedAt = new Date().toISOString();
if (!this.#tcp) {
const h = await this.#print.healthCheck();
return { status: h.status === "ready" ? "ready" : "offline", detail: h.detail, checkedAt };
}
let raw: string;
try {
raw = await fetchRaw(this.#host, this.#httpPort, K200L_STATUS_PATH, this.#timeout);
} catch (err) {
return { status: "offline", detail: (err as Error).message, checkedAt };
}
const { status, body } = parseRawReply(raw);
if (status !== 200) {
return { status: "degraded", detail: `unexpected status page (${K200L_STATUS_PATH}: HTTP ${status})`, checkedAt };
}
const flags = parseStatusPage(body);
const missing = EXPECTED.filter((k) => flags[k] === undefined);
if (missing.length > 0) {
return {
status: "degraded",
detail: `unexpected status page (${K200L_STATUS_PATH}: missing ${missing.join(", ")})`,
checkedAt,
};
}
const faults = EXPECTED.filter((k) => flags[k] === true);
return {
status: faults.length > 0 ? "degraded" : "ready",
...flags,
detail: faults.length > 0 ? faults.map((f) => LABELS[f]).join(", ") : undefined,
checkedAt,
};
}
}
const httpPortField: ConfigField = {
key: "httpPort",
label: "Status web port",
type: "port",
required: false,
default: 80,
help: "The board's web configurator port; the status page /prt_status.htm is read from it for live monitoring (default 80). TCP only.",
};
/** The generic driver's fields (transport, device path, host, port, role, rank,
* timeout) plus the status-page port, placed right after the print port. */
function k200lFields(): ConfigField[] {
const out = [...escposDriver.configFields];
const i = out.findIndex((f) => f.key === "port");
out.splice(i === -1 ? out.length : i + 1, 0, httpPortField);
return out;
}
export const k200lDriver: PrinterDriver = {
id: "k200l",
category: "printer",
label: "K200L 80mm thermal printer (Xprinter / ICS, USB+LAN)",
description:
"Xprinter / ICS K200L (XP-K200L) 80mm ESC/POS printer; its LAN board reports itself as 'POS-80' (web configurator at 192.168.123.100:80 from the factory, DHCP off). Prints over raw TCP (port 9100) OR local USB /dev/usb/lp0 — the same bytes as the generic ESC/POS driver. Over TCP the board's /prt_status.htm page gives live paper / cover / cutter / off-line status; over USB there is no page, so it is monitored by reachability only. No auth on the print socket or the web UI — isolate the VLAN.",
transports: ["tcp-ip", "usb"],
configFields: k200lFields(),
create: (c) => new K200lPrinter(c),
};
+216
View File
@@ -41,3 +41,219 @@ describe("QR reader healthCheck (ICMP liveness)", () => {
expect(hostField!.required).toBe(false); // operation is push-by-serial; IP is monitor-only
});
});
// --- DT-008 configuration over the vendor UDP protocol -----------------------------
// The protocol layer is mocked (it has its own fake-reader tests in
// dingtian-qr-config.test.ts); here we check what the ADAPTER decides: which
// preconditions it reports, what it writes to fix them, and how it points the reader at
// the booth. Scenario values are park-2's real readers (WG26, server 10.0.10.101:3000).
const qr = vi.hoisted(() => ({
readFirmware: vi.fn(),
readParams: vi.fn(),
writeSetting: vi.fn(),
setNetwork: vi.fn(),
subnetBroadcastFor: vi.fn(),
discoverReaders: vi.fn(),
}));
vi.mock("./dingtian-qr-config.js", async (importOriginal) => {
const real = await importOriginal<typeof import("./dingtian-qr-config.js")>();
return { ...real, ...qr };
});
const fw = { model: "doorqrcode", firmware: "ver_client1_1.1", chip: "v3s", hardware: "h42", serial: "HC009E84" };
const park2Params = {
dhcp: 0,
ip: "10.0.10.7",
netmask: "255.255.255.0",
gateway: "0.0.0.0",
dns1: "0.0.0.0",
dns2: "0.0.0.0",
server: "10.0.10.101",
serverPort: 3000,
httpLanguage: 1,
outputType: 6, // WG26 — the park-2 fault
cardInputFormat: 1,
lastAddEnter: 1,
lastAddNewline: 0,
qrPrefix: "",
qrSuffix: "",
restartInterval: 1,
workMode: 0,
buzzer: 0,
highPulseUs: 2000,
lowPulseUs: 400,
baudrate: 9600,
dataBits: 8,
stopBits: 1,
parity: 2,
qrOutputFormat: 4,
fillLight: 1,
cardOutputFormat: 1,
cardPrefix: "",
cardSuffix: "",
};
type Configurable = {
checkPreconditions(): Promise<{ ok: boolean; issues: { key: string; fixable: boolean; message: string }[] }>;
fixPreconditions(): Promise<{ ok: boolean; issues: { key: string }[] }>;
configureInputPush(o: { host: string; port: number; pathBase: string; auth: { user: string; password: string } }): Promise<void>;
usesPushAuth?: boolean;
};
const reader = (cfg: Record<string, string>) => dingtianQrReaderDriver.create(cfg) as unknown as Configurable;
const push = { pathBase: "/x", auth: { user: "u", password: "p" } };
afterEach(() => {
for (const m of Object.values(qr)) m.mockReset();
});
describe("DT-008 preconditions (reader must be in HTTP mode, serial must match)", () => {
it("WG26 → one FIXABLE issue naming the mode and the current target", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue(park2Params);
const r = await reader({ serial: "HC009E84", host: "10.0.10.7" }).checkPreconditions();
expect(r.ok).toBe(false);
expect(r.issues).toHaveLength(1);
expect(r.issues[0]).toMatchObject({ key: "output-type", fixable: true });
expect(r.issues[0]!.message).toMatch(/WG26.*HTTP.*10\.0\.10\.101:3000/);
});
it("typed serial ≠ reported serial → UNFIXABLE (scans would land on the wrong device)", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
const r = await reader({ serial: "HC00D3B0", host: "10.0.10.7" }).checkPreconditions();
expect(r.ok).toBe(false);
expect(r.issues).toEqual([expect.objectContaining({ key: "serial-mismatch", fixable: false })]);
expect(r.issues[0]!.message).toContain("HC009E84");
});
it("serial comparison ignores case/whitespace; HTTP mode → ok", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
expect(await reader({ serial: " hc009e84 ", host: "10.0.10.7" }).checkPreconditions()).toEqual({ ok: true, issues: [] });
});
it("no IP → ok with no issues (nothing to talk to; legacy vendor-tool setup)", async () => {
expect(await reader({ serial: "HC009E84" }).checkPreconditions()).toEqual({ ok: true, issues: [] });
expect(qr.readParams).not.toHaveBeenCalled();
});
it("IP set but no UDP answer → UNFIXABLE 'unreachable' (save fails with a clear message)", async () => {
qr.readFirmware.mockResolvedValue(null);
qr.readParams.mockResolvedValue(null);
const r = await reader({ serial: "HC009E84", host: "10.0.10.9" }).checkPreconditions();
expect(r.ok).toBe(false);
expect(r.issues[0]).toMatchObject({ key: "unreachable", fixable: false });
expect(r.issues[0]!.message).toMatch(/10\.0\.10\.9.*UDP 24680/);
});
it("fixPreconditions writes cmd 6 = 3 (HTTP) once and re-checks", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValueOnce(park2Params).mockResolvedValue({ ...park2Params, outputType: 3 });
qr.writeSetting.mockResolvedValue(0);
const r = await reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions();
expect(qr.writeSetting).toHaveBeenCalledTimes(1);
expect(qr.writeSetting).toHaveBeenCalledWith("10.0.10.7", 6, 3);
expect(r.ok).toBe(true);
});
it("fixPreconditions: a rejected / unacknowledged write throws (no silent 'fixed')", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue(park2Params);
qr.writeSetting.mockResolvedValue(1);
await expect(reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions()).rejects.toThrow(/status 1/);
qr.writeSetting.mockResolvedValue(null);
await expect(reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions()).rejects.toThrow(/no acknowledgement/);
});
});
describe("DT-008 configureInputPush (point the reader at this booth)", () => {
it("already pointing at us → no write at all", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
await reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
expect(qr.setNetwork).not.toHaveBeenCalled();
});
it("different target → set-network with the READER's serial + its own network block, then verified by polling (reader is silent right after)", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams
.mockResolvedValueOnce({ ...park2Params, outputType: 3, server: "10.0.10.203", serverPort: 8080 })
.mockResolvedValueOnce(null) // re-initialising its network: no answer to the first poll
.mockResolvedValue({ ...park2Params, outputType: 3, server: "10.0.10.101", serverPort: 3000 });
qr.subnetBroadcastFor.mockReturnValue("10.0.10.255");
qr.setNetwork.mockResolvedValue(undefined);
vi.useFakeTimers();
try {
const p = reader({ serial: "hc009e84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
await vi.advanceTimersByTimeAsync(3000); // poll 1: silent, poll 2: new target
await p;
} finally {
vi.useRealTimers();
}
expect(qr.setNetwork).toHaveBeenCalledWith(
{
serial: "HC009E84", // as REPORTED, not as typed
ip: "10.0.10.7",
netmask: "255.255.255.0",
gateway: "0.0.0.0",
dns1: "0.0.0.0",
dns2: "0.0.0.0",
server: "10.0.10.101",
serverPort: 3000,
httpLanguage: 1,
},
"10.0.10.255",
);
});
it("reader did not apply the new target → throws (set-network has no ack; the re-read is the proof)", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3, server: "10.0.10.203", serverPort: 8080 });
qr.subnetBroadcastFor.mockReturnValue("10.0.10.255");
qr.setNetwork.mockResolvedValue(undefined);
vi.useFakeTimers();
try {
const p = reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
const expectation = expect(p).rejects.toThrow(/did not apply server 10\.0\.10\.101:3000 \(still 10\.0\.10\.203:8080\)/);
await vi.advanceTimersByTimeAsync(15_000); // polls once a second until the 12 s deadline
await expectation;
} finally {
vi.useRealTimers();
}
});
it("reader not on a directly attached subnet → throws before broadcasting", async () => {
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
qr.subnetBroadcastFor.mockReturnValue(null);
await expect(
reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 80, ...push }),
).rejects.toThrow(/directly attached subnet/);
expect(qr.setNetwork).not.toHaveBeenCalled();
});
it("declares usesPushAuth=false and pushesToBackend (the scan GET is identified by serial)", () => {
expect(reader({ serial: "x" }).usesPushAuth).toBe(false);
expect(dingtianQrReaderDriver.pushesToBackend).toBe(true);
});
});
describe("DT-008 discover (LAN search → wizard rows)", () => {
it("maps each reader to serial/host config + mode/target info", async () => {
qr.discoverReaders.mockResolvedValue([
{ serial: "HC009E84", ip: "10.0.10.7", netmask: "255.255.255.0", gateway: "0.0.0.0", dns1: "0.0.0.0", dns2: "0.0.0.0", server: "10.0.10.101", serverPort: 3000, httpLanguage: 1, replyFrom: "10.0.10.7" },
]);
qr.readFirmware.mockResolvedValue(fw);
qr.readParams.mockResolvedValue(park2Params);
const found = await (dingtianQrReaderDriver as unknown as { discover(): Promise<unknown[]> }).discover();
expect(found).toEqual([
{
id: "HC009E84",
label: "HC009E84 @ 10.0.10.7",
config: { serial: "HC009E84", host: "10.0.10.7" },
info: { output: "WG26", server: "10.0.10.101:3000", url: "/qa/mcardsea.jsp", cardFormat: "6H", firmware: "ver_client1_1.1" },
},
]);
});
});
+207 -14
View File
@@ -1,6 +1,31 @@
import type { DeviceHealth, ReaderDevice, ReaderEvent } from "../interfaces.js";
import type { DeviceConfig, ReaderDriver } from "../registry.js";
import type {
DeviceHealth,
PreconditionDevice,
PreconditionIssue,
PreconditionResult,
PushConfig,
PushConfigurableDevice,
ReaderDevice,
ReaderEvent,
} from "../interfaces.js";
import type { DeviceConfig, DiscoverableDriver, DiscoveredDevice, ReaderDriver } from "../registry.js";
import { hostField, portField, stubLog } from "./common.js";
import {
QR_CARD_INPUT_FORMATS,
QR_CMD,
QR_HTTP_LANGUAGES,
QR_OUTPUT_HTTP,
QR_PORT_UNICAST,
discoverReaders,
outputTypeName,
readFirmware,
readParams,
setNetwork,
subnetBroadcastFor,
writeSetting,
type QrFirmware,
type QrParams,
} from "./dingtian-qr-config.js";
import { icmpPing } from "./icmp.js";
// Reader drivers (RF / optical). Two integration paths: Wiegand reads reach the
@@ -78,33 +103,201 @@ export const tcpipReaderDriver: ReaderDriver = {
// Dingtian DT-008 QR/RFID access reader (same vendor as the relay board). Scans QR/barcode
// + ID/IC/NFC cards. A PUSH device: on each scan it HTTP-GETs our backend (/qa/mcardsea.<ext>)
// carrying its serial (cjihao); the backend resolves the lane by matching that serial to this
// device's `serial` config, decides, and replies the verdict (drives the beep). No host-side
// connection — the adapter is a stub; the real integration is the HTTP endpoint (apps/server
// routes/qr-reader.ts). Interfaces: Wiegand 26/34, TCP/IP, USB, RS485. See
// wiki/entities/dingtian-dt008-reader.md.
export const dingtianQrReaderDriver: ReaderDriver = {
// device's `serial` config, decides, and replies the verdict (drives the beep). The scan path
// is the HTTP endpoint (apps/server routes/qr-reader.ts) — this adapter never receives reads.
//
// What the adapter DOES do is CONFIGURE the reader over the vendor's UDP protocol
// (dingtian-qr-config.ts), the job that used to need the Windows exe on site:
// - discover(): find readers on the device VLAN (serial, IP, current push target);
// - preconditions: the reader must be in HTTP output mode — in WG26/RS232/USB… it beeps
// locally and NEVER contacts the booth (park-2, 2026-10-08: both readers in WG26, every
// enrolment "beeped but captured nothing"); and the serial typed must be the serial the
// reader reports, else scans resolve to the wrong device row;
// - configureInputPush(): point the reader's server/port at THIS booth (set-network).
// All of it needs the reader's IP (unicast). Without an IP the adapter configures nothing
// and the admin must use the vendor tool / scripts/dingtian_qr.py.
// See wiki/entities/dingtian-dt008-reader.md, wiki/sources/dingtian-qr-linux-tool.md.
class DingtianQrReader extends StubReader implements PreconditionDevice, PushConfigurableDevice {
/** The scan GET carries no credentials — identity is the serial. */
readonly usesPushAuth = false;
#host(): string {
return this.config.host ? String(this.config.host).trim() : "";
}
#serial(): string {
return String(this.config.serial ?? "").trim();
}
/** Read firmware + params; throws a precise message when the reader doesn't answer. */
async #read(host: string): Promise<{ fw: QrFirmware; params: QrParams }> {
const [fw, params] = await Promise.all([readFirmware(host), readParams(host)]);
if (!fw || !params) {
throw new Error(
`reader at ${host} did not answer on UDP ${QR_PORT_UNICAST} — check the IP (is it on the device VLAN?), or clear the IP to save without configuring the reader`,
);
}
return { fw, params };
}
#issues(fw: QrFirmware, params: QrParams): PreconditionIssue[] {
const issues: PreconditionIssue[] = [];
const typed = this.#serial();
if (typed && typed.toUpperCase() !== fw.serial.toUpperCase()) {
issues.push({
key: "serial-mismatch",
fixable: false,
message: `the reader at ${this.#host()} reports serial ${fw.serial}, not ${typed} — scans would resolve to the wrong device; enter ${fw.serial}`,
});
}
if (params.outputType !== QR_OUTPUT_HTTP) {
issues.push({
key: "output-type",
fixable: true,
message: `output type is ${outputTypeName(params.outputType)} — must be HTTP, otherwise the reader beeps but never contacts the booth (currently targets ${params.server}:${params.serverPort})`,
});
}
return issues;
}
async checkPreconditions(): Promise<PreconditionResult> {
const host = this.#host();
if (!host) return { ok: true, issues: [] }; // nothing to talk to — legacy, vendor-tool-configured
try {
const { fw, params } = await this.#read(host);
const issues = this.#issues(fw, params);
return { ok: issues.length === 0, issues };
} catch (err) {
return { ok: false, issues: [{ key: "unreachable", fixable: false, message: (err as Error).message }] };
}
}
async fixPreconditions(): Promise<PreconditionResult> {
const host = this.#host();
if (!host) return { ok: true, issues: [] };
const { params } = await this.#read(host);
if (params.outputType !== QR_OUTPUT_HTTP) {
const status = await writeSetting(host, QR_CMD.outputType, QR_OUTPUT_HTTP);
if (status !== 0) {
throw new Error(
`reader at ${host} did not accept output type HTTP (${status == null ? "no acknowledgement" : `status ${status}`})`,
);
}
stubLog(this.driverId, `${host}: output type ${outputTypeName(params.outputType)} → HTTP`);
}
return this.checkPreconditions();
}
/** Re-read the params once a second until they show `server:port` or `deadlineMs`
* passes; resolves the last read (null = never answered). */
async #waitForTarget(host: string, server: string, port: number, deadlineMs = 12_000): Promise<QrParams | null> {
const end = Date.now() + deadlineMs;
let last: QrParams | null = null;
while (Date.now() < end) {
await new Promise((r) => setTimeout(r, 1000));
last = await readParams(host, { timeoutMs: 1000, retries: 0 });
if (last && last.server === server && last.serverPort === port) return last;
}
return last;
}
/**
* Make the reader push to THIS booth: server = our IP on its subnet, port = our listen
* port. `pathBase`/`auth` are ignored — the reader's URL is fixed (/qa/mcardsea.<ext>)
* and unauthenticated. set-network is an L2 broadcast the reader applies WITHOUT an
* ack, so the result is confirmed by re-reading the params.
*/
async configureInputPush(opts: PushConfig): Promise<void> {
const host = this.#host();
if (!host) return;
const { fw, params } = await this.#read(host);
if (params.server === opts.host && params.serverPort === opts.port) return; // already us
const broadcast = subnetBroadcastFor(host);
if (!broadcast) {
throw new Error(
`cannot set the reader's server: ${host} is not on a directly attached subnet (set-network is an L2 broadcast) — set server ${opts.host}:${opts.port} with the vendor tool`,
);
}
await setNetwork(
{
serial: fw.serial, // the reader matches on ITS serial, never the typed one
ip: params.ip,
netmask: params.netmask,
gateway: params.gateway,
dns1: params.dns1,
dns2: params.dns2,
server: opts.host,
serverPort: opts.port,
httpLanguage: params.httpLanguage, // any extension is served (/qa/mcardsea.<ext>)
},
broadcast,
);
// The reader re-initialises its network stack after set-network and answers nothing
// for a few seconds (bench: silent at 1.5 s, back by ~5 s) — poll, don't read once.
const after = await this.#waitForTarget(host, opts.host, opts.port);
if (!after || after.server !== opts.host || after.serverPort !== opts.port) {
throw new Error(
`reader at ${host} did not apply server ${opts.host}:${opts.port} (still ${after?.server ?? "?"}:${after?.serverPort ?? "?"})`,
);
}
stubLog(
this.driverId,
`${host}: push target ${params.server}:${params.serverPort} → ${opts.host}:${opts.port}`,
);
}
}
/** LAN search + a params read per reader so the admin sees the mode and target at a glance. */
async function discoverDingtianReaders(): Promise<DiscoveredDevice[]> {
const found = await discoverReaders();
return Promise.all(
found.map(async (r) => {
const [fw, params] = await Promise.all([readFirmware(r.ip), readParams(r.ip)]);
const info: Record<string, string> = {
output: params ? outputTypeName(params.outputType) : "unknown",
server: `${r.server}:${r.serverPort}`,
url: `/qa/mcardsea.${(QR_HTTP_LANGUAGES[r.httpLanguage] ?? "php").toLowerCase().replace("c#", "aspx")}`,
};
if (params) info.cardFormat = QR_CARD_INPUT_FORMATS[params.cardInputFormat] ?? String(params.cardInputFormat);
if (fw) info.firmware = fw.firmware;
return {
id: r.serial,
label: `${r.serial} @ ${r.ip}`,
config: { serial: r.serial, host: r.ip },
info,
};
}),
);
}
export const dingtianQrReaderDriver: ReaderDriver & DiscoverableDriver = {
id: "dingtian-qr-reader",
category: "reader",
label: "Dingtian DT-008 QR/RFID reader (HTTP push)",
description:
"Dingtian DT-008 QR/barcode/RFID access reader that HTTP-pushes each scan to the backend. Set its server IP/port to this host in the vendor tool; enter its serial here so scans resolve to this lane.",
"Dingtian DT-008 QR/barcode/RFID access reader that HTTP-pushes each scan to the backend. Scan the LAN to find it; with its IP, saving puts it in HTTP mode pointing at this booth (no vendor tool). Its serial maps scans to this device.",
transports: ["tcp-ip"],
// Pushes scans to the backend → the wizard offers the backend-IP picker; the save
// pipeline then runs configureInputPush (set-network) with that IP + our port.
pushesToBackend: true,
configFields: [
{
key: "serial",
label: "Device serial (cjihao)",
type: "string",
required: true,
help: "The reader's serial as it reports in each scan (the `cjihao` field). Used to map scans to this lane.",
help: "The reader's serial as it reports in each scan (the `cjihao` field). Used to map scans to this lane. Must match what the reader reports (checked on test/save when the IP is set).",
},
{
// OPTIONAL: the reader pushes by serial (operation needs no IP), but giving its
// IP lets the status monitor ICMP-ping it for a real online/offline dot instead
// of an always-green stub. Leave blank to skip monitoring (shows "set IP").
// OPTIONAL for operation (the reader pushes by serial), but it is what lets the
// wizard CONFIGURE the reader (HTTP mode + server target) and the status monitor
// ping it. Blank = nothing is configured; the reader must be set up with the vendor
// tool / scripts/dingtian_qr.py, and liveness shows "set IP".
...hostField,
required: false,
help: "Optional: the reader's IP, used ONLY to monitor it (ping). Scans still resolve by serial. Leave blank to skip liveness monitoring.",
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.",
},
],
create: (c) => new StubReader("dingtian-qr-reader", c),
discover: discoverDingtianReaders,
create: (c) => new DingtianQrReader("dingtian-qr-reader", c),
};
+1
View File
@@ -18,6 +18,7 @@ export {
hikvisionDriver,
dahuaDriver,
rongtaDriver,
k200lDriver,
escposDriver,
} from "./drivers/index.js";
export { isPrinter, type PrinterRole } from "./drivers/printer-rongta.js";
+11 -1
View File
@@ -124,6 +124,10 @@ export function hasPreconditions(
// See wiki/concepts/device-input-flow.md.
export interface PushConfigurableDevice {
configureInputPush(opts: PushConfig): Promise<void>;
/** False for a device whose push carries NO credentials (the DT-008 reader's scan GET
* is identified by its serial, not Digest auth) — the backend then skips persisting
* the generated push user/password. Absent = true (the Dingtian relay). */
readonly usesPushAuth?: boolean;
}
export interface PushConfig {
@@ -199,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
+19
View File
@@ -32,6 +32,7 @@ export const RESOURCES = [
"recyclebin", // soft-deleted master data: view / restore / purge
"backup", // encrypted DB backups: configure target + trigger a manual run
"carwash", // Car Wash module: orders/queue (read), intake (create), done/pay/void (update)
"barrier", // the EXIT barrier opened with NO payment (forgiven exit) — see wiki/decisions/forgiven-exit.md
] as const;
export type Resource = (typeof RESOURCES)[number];
@@ -94,6 +95,12 @@ export const PERMISSIONS: readonly Permission[] = [
// `drawer:create`; see ModuleManifest.tillGuards). Settings (categories, services,
// price matrix, sponsorship program) ride site:update.
"carwash:read", "carwash:create", "carwash:update", "carwash:cash",
// Forgiven exit (wiki/decisions/forgiven-exit.md): open the EXIT barrier for a car with
// no payment — a ticketed transient (its fee is signed as a $0 payment carrying the
// forgone amount) or a car with no session at all. Admin by default; the owner grants
// it to a role deliberately. Every use is signed, attributed, photographed and on the
// operator's Z-report. Never the entry side.
"barrier:create",
] as const;
/** The protected built-in role: non-deletable, non-editable, always = ALL
@@ -329,6 +336,11 @@ export interface LedgerPayload {
readonly grossMinor?: number;
readonly discountMinor?: number;
readonly validationIds?: string[];
/** payment: a FORGIVEN exit (wiki/decisions/forgiven-exit.md). `amountMinor` is 0 —
* nothing was tendered, so cash/card/drawer are untouched — and `forgoneMinor` is the
* fee the car owed and the operator waived. Reported as its own Z-report line, never
* folded into the merchant-validation `discountMinor`. */
readonly forgoneMinor?: number;
/** payment: the per-validation receipt lines as settled (label + amount taken off) —
* stamped so the printed receipt reproduces without re-deriving the fold. */
readonly validationLines?: { programId: string; label: string; mode: string; discountMinor: number }[];
@@ -463,6 +475,11 @@ export const REASON_CODES = [
"exit.freeGrace",
// manual / human-intervention barrier open
"exit.manualOpen",
// forgiven exit: the owner/operator (barrier:create) lets a car out with no money.
// With a ticket → a $0 payment carries the forgone fee; no session → anomaly only.
// See wiki/decisions/forgiven-exit.md.
"exit.forgiven",
"exit.forgiven.noSession",
// plate reconciliation: the exiting car's plate is already OPEN under a DIFFERENT
// ticket (possible ticket-swap fraud). Suspected = flagged; Override = operator
// consciously released it. See wiki/concepts/plate-reconciliation.md.
@@ -512,6 +529,8 @@ export const REASON_EN: Record<ReasonCode, string> = {
"exit.open.failed": "exit recorded, but the barrier did not open — open manually",
"exit.freeGrace": "free entry-grace (no charge)",
"exit.manualOpen": "manual barrier open (human intervention)",
"exit.forgiven": "manual exit by {operator} — fee of {forgone} {currency}, no payment: {note}",
"exit.forgiven.noSession": "manual exit by {operator} — no ticket / no session: {note}",
"exit.plateSwapSuspected": "possible ticket swap — plate {plate} is already inside under ticket {otherIdentity}",
"exit.plateSwapOverride": "operator {operator} released a suspected ticket-swap exit (plate {plate}, also open under {otherIdentity})",
"sub.refused.notFound": "subscription refused — not found",
Binary file not shown.
+485
View File
@@ -0,0 +1,485 @@
#!/usr/bin/env python3
"""
dingtian_qr.py - cross-platform (Linux/Windows/macOS) command line tool for
Dingtian QR code / RFID readers. Replacement for the Windows-only
QRCode_v1_6_5.exe configuration tool. Pure Python 3, no dependencies.
Protocol (reverse engineered from QRCode_v1_6_5.exe + packet captures, Oct 2026)
---------------------------------------------------------------------------------
Transport: UDP. The reader listens on 24680 (unicast commands) and 24582
(broadcast search / network set). Every message starts with a 17 byte header:
off size field notes
0 4 'XXXX' magic
4 4 id LE u32, PC sends 0, reader echoes an arbitrary value
8 4 cmd LE u32, even = request, odd (cmd+1) = reply
12 4 len LE u32, payload length
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF (0xFF when no payload)
17 payload
The Windows tool sends header and payload as TWO datagrams (17 byte header
first, then the raw payload). Reader replies are a single datagram.
Commands:
2 search broadcast to :24582, no payload -> 3 96 byte DeviceInfo
0 firmware info no payload -> 1 64 bytes
30 get parameters no payload -> 31 720 byte Params
32 set network broadcast to :24582, 96 byte DeviceInfo (reader matches serial)
6 output type u32 1..10 (OUTPUT_TYPES)
8 card input format u32 1..5 (CARD_INPUT)
10 enter / newline u32 = add_enter | (add_newline << 8)
38 serial + QR format 5 x u32: baud, data bits, stop bits, parity, qr_output_format
12 QR prefix u32 prefix/suffix type (0 HEX, 1 ASCII) + 32 raw bytes
14 QR suffix u32 prefix/suffix type (same value) + 32 raw bytes
44 card output u32 card_output_format (0 HEX,1 ASCII), u32 prefix/suffix type,
32 bytes prefix, 32 bytes suffix
28 wiegand pulses 2 x u32: high_pulse/100, low_pulse/100 (units of 100 us)
40 scan fill light u32 0 close, 1 open
18 work mode u32 0 normal, 1 single, 2 interval
16 restart interval u32 0 no, 1 every 12 h, 2 every 24 h
22 buzzer u32 0 off, 1 on
Every write is acknowledged with cmd+1 and a one byte status: 0 = applied,
1 = rejected (value out of range). A frame sent as ONE datagram (header+payload
together) is ignored by the reader, so the two-datagram form is mandatory.
"""
import argparse
import json
import socket
import struct
import sys
import time
PORT_UNICAST = 24680
PORT_BCAST = 24582
MAGIC = b'XXXX'
OUTPUT_TYPES = {1: 'USB virtual keyboard', 2: 'USB virtual serial port', 3: 'HTTP', 4: 'MQTT',
5: 'RS232', 6: 'WG26', 7: 'WG34', 8: 'RS485', 9: 'AC Output', 10: 'TCP'}
CARD_INPUT = {1: '6H', 2: '8H', 3: '8H10D', 4: '6H10D', 5: '2H3D+4H5D'}
QR_FORMAT = {0: 'Decimal', 1: 'HEX', 2: 'Decimal Reverse', 3: 'HEX Reverse', 4: 'ASCII'}
HEX_ASCII = {0: 'HEX', 1: 'ASCII'}
PARITY = {0: 'Even', 1: 'Odd', 2: 'None', 3: 'Space', 4: 'Mark'}
RESTART = {0: 'No', 1: '12Hours', 2: '24Hours'}
WORKMODE = {0: 'Normal', 1: 'Single', 2: 'Interval'}
ONOFF = {0: 'Off', 1: 'On'}
FILL_LIGHT = {0: 'Close', 1: 'Open'}
DHCP = {0: 'Static IP', 1: 'DHCP'}
HTTP_LANG = {0: 'PHP', 1: 'JSP', 2: 'C#', 3: 'ASP', 4: 'CGI'}
# ---------------------------------------------------------------- framing
def checksum(payload):
return (0xFF - sum(payload)) & 0xFF
def header(cmd, payload=b'', ident=0):
return MAGIC + struct.pack('<III', ident, cmd, len(payload)) + bytes([checksum(payload)])
def parse(datagram):
"""Return (ident, cmd, payload) or None if the datagram is not a valid frame."""
if len(datagram) < 17 or datagram[:4] != MAGIC:
return None
ident, cmd, ln = struct.unpack_from('<III', datagram, 4)
payload = datagram[17:17 + ln]
if len(payload) != ln or checksum(payload) != datagram[16]:
return None
return ident, cmd, payload
def send(sock, addr, cmd, payload=b''):
"""Send exactly like the Windows tool: header datagram first, then payload datagram."""
sock.sendto(header(cmd, payload), addr)
if payload:
sock.sendto(payload, addr)
def ip2b(s):
"""IPv4 as stored by the reader: little-endian u32 (= inet_aton reversed)."""
return socket.inet_aton(s)[::-1]
def b2ip(b):
return socket.inet_ntoa(bytes(b[:4])[::-1])
def cstr(b):
return bytes(b).split(b'\0', 1)[0].decode('utf-8', 'replace')
def u32(b, off):
return struct.unpack_from('<I', b, off)[0]
# ---------------------------------------------------------------- blocks
def parse_device_info(d):
"""96 byte block: search reply (cmd 3) and set-network payload (cmd 32)."""
return {
'serial': cstr(d[0:20]),
'ip': b2ip(d[20:24]), 'netmask': b2ip(d[24:28]), 'gateway': b2ip(d[28:32]),
'dns1': b2ip(d[32:36]), 'dns2': b2ip(d[36:40]),
'server': cstr(d[40:88]),
'server_port': u32(d, 88),
'http_language': u32(d, 92),
}
def build_device_info(serial, ip, netmask, gateway, dns1, dns2, server, server_port, http_language=0):
d = bytearray(96)
d[0:20] = serial.encode()[:20].ljust(20, b'\0')
d[20:24] = ip2b(ip)
d[24:28] = ip2b(netmask)
d[28:32] = ip2b(gateway)
d[32:36] = ip2b(dns1)
d[36:40] = ip2b(dns2)
d[40:88] = server.encode()[:47].ljust(48, b'\0')
d[88:92] = struct.pack('<I', server_port)
d[92:96] = struct.pack('<I', http_language)
return bytes(d)
def parse_firmware(d):
return {'model': cstr(d[0:16]), 'firmware': cstr(d[16:32]), 'chip': cstr(d[32:40]),
'hardware': cstr(d[40:48]), 'serial': cstr(d[48:64])}
def parse_params(d):
"""720 byte parameter struct (reply 31 to cmd 30)."""
return {
'dhcp': u32(d, 0x000),
'ip': b2ip(d[0x004:0x008]),
'netmask': b2ip(d[0x008:0x00c]),
'gateway': b2ip(d[0x00c:0x010]),
'dns1': b2ip(d[0x010:0x014]),
'dns2': b2ip(d[0x014:0x018]),
'server': cstr(d[0x018:0x048]),
'server_port': u32(d, 0x048),
'http_language': u32(d, 0x04c),
'output_type': d[0x198],
'card_input_format': d[0x19c],
'last_add_enter': d[0x1a0],
'last_add_newline': d[0x1a1],
'qr_prefix_type': u32(d, 0x1a4), # 0 HEX / 1 ASCII
'qr_prefix': bytes(d[0x1a8:0x1c8]).rstrip(b'\0'),
'qr_suffix_type': u32(d, 0x1c8), # written with the same value as qr_prefix_type
'qr_suffix': bytes(d[0x1cc:0x1ec]).rstrip(b'\0'),
'restart_interval': u32(d, 0x1ec),
'work_mode': u32(d, 0x1f0),
'unknown_1f4': u32(d, 0x1f4),
'buzzer': u32(d, 0x1f8),
'high_pulse_us': u32(d, 0x1fc) * 100,
'low_pulse_us': u32(d, 0x200) * 100,
'baudrate': u32(d, 0x204),
'data_bits': u32(d, 0x208),
'stop_bits': u32(d, 0x20c),
'parity': u32(d, 0x210),
'qr_output_format': u32(d, 0x214),
'fill_light': u32(d, 0x218),
'card_output_format': u32(d, 0x288), # 0 HEX / 1 ASCII
'card_prefix_type': u32(d, 0x28c), # 0 HEX / 1 ASCII
'card_prefix': bytes(d[0x290:0x2b0]).rstrip(b'\0'),
'card_suffix': bytes(d[0x2b0:0x2d0]).rstrip(b'\0'),
}
def describe(p):
"""Human readable version of parse_params()."""
out = dict(p)
out['dhcp'] = DHCP.get(p['dhcp'], p['dhcp'])
out['http_language'] = HTTP_LANG.get(p['http_language'], p['http_language'])
out['output_type'] = OUTPUT_TYPES.get(p['output_type'], p['output_type'])
out['card_input_format'] = CARD_INPUT.get(p['card_input_format'], p['card_input_format'])
out['qr_prefix_type'] = HEX_ASCII.get(p['qr_prefix_type'], p['qr_prefix_type'])
out['qr_suffix_type'] = HEX_ASCII.get(p['qr_suffix_type'], p['qr_suffix_type'])
out['restart_interval'] = RESTART.get(p['restart_interval'], p['restart_interval'])
out['work_mode'] = WORKMODE.get(p['work_mode'], p['work_mode'])
out['buzzer'] = ONOFF.get(p['buzzer'], p['buzzer'])
out['parity'] = PARITY.get(p['parity'], p['parity'])
out['qr_output_format'] = QR_FORMAT.get(p['qr_output_format'], p['qr_output_format'])
out['fill_light'] = FILL_LIGHT.get(p['fill_light'], p['fill_light'])
out['card_output_format'] = HEX_ASCII.get(p['card_output_format'], p['card_output_format'])
out['card_prefix_type'] = HEX_ASCII.get(p['card_prefix_type'], p['card_prefix_type'])
for k in ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix'):
out[k] = p[k].decode('utf-8', 'replace') if p[k] else ''
if p[k]:
out[k + '_hex'] = p[k].hex()
return out
# ---------------------------------------------------------------- transport helpers
def open_socket(timeout=1.0, bind_ip='0.0.0.0'):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((bind_ip, 0))
s.settimeout(timeout)
return s
def discover(timeout=2.0, broadcast='255.255.255.255', bind_ip='0.0.0.0'):
"""Broadcast cmd 2 and collect cmd 3 replies. Returns list of (reply_ip, DeviceInfo)."""
s = open_socket(timeout, bind_ip)
send(s, (broadcast, PORT_BCAST), 2)
found = {}
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == 3 and len(f[2]) >= 96:
info = parse_device_info(f[2])
found[info['serial']] = (addr[0], info)
s.close()
return list(found.values())
def request(ip, cmd, payload=b'', expect=None, timeout=2.0, retries=2):
"""Send a unicast command and wait for the reply (cmd + 1 unless `expect` given).
Returns the reply payload or None on timeout. For write commands the payload is
one status byte: b'\\x00' = applied, b'\\x01' = rejected."""
expect = cmd + 1 if expect is None else expect
s = open_socket(timeout)
try:
for _ in range(retries + 1):
send(s, (ip, PORT_UNICAST), cmd, payload)
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == expect:
return f[2]
return None
finally:
s.close()
def get_firmware(ip):
d = request(ip, 0)
return parse_firmware(d) if d else None
def get_params(ip):
d = request(ip, 30)
return parse_params(d) if d else None
# ---------------------------------------------------------------- set commands
def _set(ip, cmd, payload, wait):
"""Write command; True only if the reader acknowledged with status 0."""
if wait:
r = request(ip, cmd, payload)
if r is None:
print('cmd %d: no acknowledgement' % cmd, file=sys.stderr)
elif r != b'\x00':
print('cmd %d: rejected by reader (status %s)' % (cmd, r.hex()), file=sys.stderr)
return r == b'\x00'
s = open_socket()
send(s, (ip, PORT_UNICAST), cmd, payload)
s.close()
return True
def set_simple(ip, cmd, value, wait=True):
return _set(ip, cmd, struct.pack('<I', value & 0xFFFFFFFF), wait)
def _pad32(b):
return bytes(b)[:32].ljust(32, b'\0')
def set_format(ip, p, wait=True):
"""Send the eight commands behind the 'Format parameter' Set button.
p: dict with parse_params() keys."""
ok = True
ok &= set_simple(ip, 6, p['output_type'], wait)
ok &= set_simple(ip, 8, p['card_input_format'], wait)
ok &= set_simple(ip, 10, (p['last_add_enter'] & 0xff) | ((p['last_add_newline'] & 0xff) << 8), wait)
ok &= _set(ip, 38, struct.pack('<5I', p['baudrate'], p['data_bits'], p['stop_bits'],
p['parity'], p['qr_output_format']), wait)
ok &= _set(ip, 12, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_prefix']), wait)
ok &= _set(ip, 14, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_suffix']), wait)
ok &= _set(ip, 44, struct.pack('<II', p['card_output_format'], p['card_prefix_type'])
+ _pad32(p['card_prefix']) + _pad32(p['card_suffix']), wait)
ok &= _set(ip, 28, struct.pack('<II', p['high_pulse_us'] // 100, p['low_pulse_us'] // 100), wait)
return bool(ok)
def set_external(ip, p, wait=True):
"""Send the four commands behind the 'External parameter' Set button."""
ok = True
ok &= set_simple(ip, 40, p['fill_light'], wait) # -> Params 0x218
ok &= set_simple(ip, 18, p['work_mode'], wait) # -> Params 0x1f0 (verified on real reader)
ok &= set_simple(ip, 16, p['restart_interval'], wait) # -> Params 0x1ec
ok &= set_simple(ip, 22, p['buzzer'], wait) # -> Params 0x1f8 (verified on real reader)
return bool(ok)
def set_network(info, broadcast='255.255.255.255', timeout=2.0):
"""Broadcast cmd 32 with a DeviceInfo block; the reader whose serial matches applies it.
Returns (addr, payload) of a cmd 33 reply, or None."""
payload = build_device_info(info['serial'], info['ip'], info['netmask'], info['gateway'],
info['dns1'], info['dns2'], info['server'], info['server_port'],
info.get('http_language', 0))
s = open_socket(timeout)
send(s, (broadcast, PORT_BCAST), 32, payload)
got = None
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == 33:
got = (addr, f[2])
break
s.close()
return got
# ---------------------------------------------------------------- CLI
SET_FIELDS_INT = ('output_type', 'card_input_format', 'last_add_enter', 'last_add_newline', 'baudrate',
'data_bits', 'stop_bits', 'parity', 'qr_output_format', 'qr_prefix_type',
'card_output_format', 'card_prefix_type', 'high_pulse_us', 'low_pulse_us',
'fill_light', 'buzzer', 'restart_interval', 'work_mode')
SET_FIELDS_STR = ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix')
EXTERNAL_FIELDS = ('fill_light', 'buzzer', 'restart_interval', 'work_mode') # External Set button
# everything else in SET_FIELDS_INT / SET_FIELDS_STR belongs to the Format Set button
def _enum_help(table):
return ', '.join('%d %s' % (k, v) for k, v in table.items())
def _parse_bytes(text):
"""CLI prefix/suffix value: plain text, or 'hex:0d0a' for binary bytes. Max 32 bytes."""
if text.lower().startswith('hex:'):
b = bytes.fromhex(text[4:])
else:
b = text.encode('utf-8')
if len(b) > 32:
raise SystemExit('prefix/suffix longer than 32 bytes: %r' % text)
return b
def main(argv=None):
ap = argparse.ArgumentParser(
description='Dingtian QR/RFID reader configuration tool (UDP 24680/24582). '
'See PROTOCOL.md for the wire format.',
epilog='Examples: %(prog)s discover --broadcast 192.168.1.255 | %(prog)s get 192.168.1.99 | '
'%(prog)s set 192.168.1.99 --output-type 3 --buzzer 1')
sub = ap.add_subparsers(dest='cmd', required=True)
d = sub.add_parser('discover', help='broadcast search for readers (cmd 2)')
d.add_argument('--broadcast', default='255.255.255.255', help='broadcast address, e.g. 192.168.1.255')
d.add_argument('--timeout', type=float, default=2.0)
i = sub.add_parser('info', help='firmware info (cmd 0)')
i.add_argument('ip')
g = sub.add_parser('get', help='read all parameters (cmd 30)')
g.add_argument('ip')
g.add_argument('--raw', action='store_true', help='print numeric codes instead of names')
g.add_argument('--hexdump', action='store_true', help='also hexdump the 720 byte struct')
n = sub.add_parser('set-network', help='broadcast new network settings (cmd 32)')
for k in ('serial', 'ip', 'netmask', 'gateway', 'dns1', 'dns2', 'server'):
n.add_argument('--' + k, required=True)
n.add_argument('--server-port', type=int, required=True)
n.add_argument('--http-language', type=int, default=0, help='0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI')
n.add_argument('--broadcast', default='255.255.255.255')
f = sub.add_parser('set', help='change format/external parameters (reads current values first)',
description='Reads the reader\'s current parameters (cmd 30), applies the given '
'changes and sends the full Format (6,8,10,38,12,14,44,28) and '
'External (40,18,16,22) command sequences, exactly like the Windows tool.')
f.add_argument('ip')
helps = {
'output_type': _enum_help(OUTPUT_TYPES), 'card_input_format': _enum_help(CARD_INPUT),
'last_add_enter': '0/1 append Enter after the code', 'last_add_newline': '0/1 append new line',
'baudrate': 'e.g. 9600, 115200', 'data_bits': '5..8', 'stop_bits': '1 or 2',
'parity': _enum_help(PARITY), 'qr_output_format': _enum_help(QR_FORMAT),
'qr_prefix_type': _enum_help(HEX_ASCII) + ' (applies to QR prefix and suffix)',
'card_output_format': _enum_help(HEX_ASCII), 'card_prefix_type': _enum_help(HEX_ASCII),
'high_pulse_us': 'Wiegand high pulse in microseconds (multiple of 100, default 2000)',
'low_pulse_us': 'Wiegand low pulse in microseconds (multiple of 100, default 400)',
'fill_light': _enum_help(FILL_LIGHT), 'buzzer': _enum_help(ONOFF),
'restart_interval': _enum_help(RESTART), 'work_mode': _enum_help(WORKMODE),
}
for k in SET_FIELDS_INT:
f.add_argument('--' + k.replace('_', '-'), type=int, metavar='N', help=helps[k])
for k in SET_FIELDS_STR:
f.add_argument('--' + k.replace('_', '-'), type=str, metavar='TEXT',
help='up to 32 bytes; plain text, or "hex:0d0a" for binary bytes, "" to clear')
f.add_argument('--no-wait', action='store_true', help='do not wait for acknowledgements')
a = ap.parse_args(argv)
if a.cmd == 'discover':
for ip, info in discover(a.timeout, a.broadcast):
print(json.dumps({'reply_from': ip, **info}, indent=2))
return 0
if a.cmd == 'info':
r = get_firmware(a.ip)
print(json.dumps(r, indent=2) if r else 'no reply')
return 0 if r else 1
if a.cmd == 'get':
raw = request(a.ip, 30)
if raw is None:
print('no reply')
return 1
if a.hexdump:
for o in range(0, len(raw), 32):
print('%04x: %s' % (o, raw[o:o + 32].hex(' ')))
p = parse_params(raw)
print(json.dumps(p if a.raw else describe(p), indent=2, default=lambda b: b.hex()))
return 0
if a.cmd == 'set-network':
info = {'serial': a.serial, 'ip': a.ip, 'netmask': a.netmask, 'gateway': a.gateway,
'dns1': a.dns1, 'dns2': a.dns2, 'server': a.server, 'server_port': a.server_port,
'http_language': a.http_language}
r = set_network(info, a.broadcast)
print('acknowledged by', r[0] if r else 'nobody (no cmd 33 reply within timeout)')
return 0 if r else 1
if a.cmd == 'set':
p = get_params(a.ip)
if p is None:
print('no reply from reader')
return 1
fmt_changed = ext_changed = False
for k in SET_FIELDS_INT + SET_FIELDS_STR:
v = getattr(a, k)
if v is None:
continue
p[k] = _parse_bytes(v) if k in SET_FIELDS_STR else v
if k in EXTERNAL_FIELDS:
ext_changed = True
else:
fmt_changed = True
if not (fmt_changed or ext_changed):
print('nothing to change')
return 0
# only the button group(s) that contain a changed field are sent, like pressing that Set button
ok = True
if fmt_changed:
r = set_format(a.ip, p, not a.no_wait)
print('format parameters:', 'ok' if r else 'FAILED')
ok &= r
if ext_changed:
r = set_external(a.ip, p, not a.no_wait)
print('external parameters:', 'ok' if r else 'FAILED')
ok &= r
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Bench sink for the Dingtian DT-008 QR/RFID reader.
Answers the reader's HTTP-GET push on any path (/qa/mcardsea.php|jsp|asp|aspx|cgi) with the
vendor-SDK verdict JSON and `Connection: close`, and prints one line per read. Stdlib only.
python3 scripts/reader-sink.py # port 80 (needs sudo/admin), refuse = 1 beep
python3 scripts/reader-sink.py -p 3000 --accept # accept = 2 beeps, output 0
Point the reader's Server address/port at this machine (QRCode tool → Setting → Network parameter).
See wiki/entities/dingtian-dt008-reader.md.
"""
import argparse
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
ACCEPT = False
class Sink(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.0"
def log_message(self, *_): # silence the default access log; we print our own line
pass
def _handle(self):
q = {k: v[0] for k, v in parse_qs(urlsplit(self.path).query).items()}
cardid = q.get("cardid", "")
status = q.get("status", "")
channel = "qr" if cardid.startswith("Q:") else "card" if cardid.startswith("K:") else "?"
print(
f"{time.strftime('%H:%M:%S')} {self.client_address[0]:15} serial={q.get('cjihao', '?'):10} "
f"dev={q.get('mjihao', '?'):3} dir={'in' if status[-1:] == '1' else 'out' if status[-1:] == '0' else '?':3} "
f"ch={channel:4} cardid={cardid!r} path={urlsplit(self.path).path}",
flush=True,
)
body = json.dumps(
{
"data": [
{
"cardid": cardid,
"cjihao": q.get("cjihao", ""),
"mjihao": q.get("mjihao", ""),
"status": 1 if ACCEPT else 0, # 1 = valid (2 beeps), 0 = invalid (1 beep)
"time": str(int(time.time())),
"output": 0,
}
],
"code": 0,
"message": "",
}
).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.send_header("Connection", "close") # the reader only acts once the socket closes
self.end_headers()
self.wfile.write(body)
do_GET = _handle
do_POST = _handle
def main():
global ACCEPT
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-p", "--port", type=int, default=80)
ap.add_argument("-b", "--bind", default="0.0.0.0")
ap.add_argument("--accept", action="store_true", help="reply status=1 (valid, 2 beeps) instead of 0")
a = ap.parse_args()
ACCEPT = a.accept
print(f"reader sink on {a.bind}:{a.port} verdict={'ACCEPT' if ACCEPT else 'REFUSE'} (Ctrl-C to stop)", flush=True)
HTTPServer((a.bind, a.port), Sink).serve_forever()
if __name__ == "__main__":
main()
+19
View File
@@ -101,6 +101,25 @@ now refuses to run if any table is uncategorized). See [[local-dev-workflow]].
under diagnosis runs `LOG_LEVEL=debug` with no code change; warn+ persistence is unaffected
(it filters independently in the tee).
### Noise cut (2026-10-08)
Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, of which 60 were the
Docker HEALTHCHECK's `/health` every 30 s logged as "incoming request" + "request completed";
160 vision lines, of which 143 were uvicorn access lines for `GET /health` (Docker's probe plus
the booth server's footer-chip poll every 8 s, `DEVICE_POLL_MS`). Levels were never the problem
— all of it was `info`. Changes:
- **`/health` is silent** (`logLevel: "silent"` on the route); vision drops `/health` access
lines with a `logging.Filter` on `uvicorn.access` (`DropHealthAccessLog`, app.py).
- **One line per request**: `disableRequestLogging` + an `onResponse` hook →
`GET /api/x → 200 12ms`. ⚠ That flag also stops Fastify's default error handler from logging
handler errors (fastify/lib/error-handler.js), so an `onError` hook logs 5xx with the stack.
- **Chatter → debug**: the hik-alarm `HIT` line (ACCEPTED/REJECTED carry everything) and the
per-snapshot `captureSnapshot … (N bytes)` line; `stubLog` gained a level argument (device
diagnostics default `info`, per-event chatter passes `"debug"`). `LOG_LEVEL=debug` restores all.
Expected on a quiet booth: a handful of lines per hour instead of ~500.
## The booth viewer
A **Logs screen** under Setup (`/setup/logs`, gated by `log:read`, sq+en) — filter by
+11
View File
@@ -204,6 +204,17 @@ filter shows a `matched/total` count). No new API — filtering is over data alr
segment — **booth** (operator-initiated, `source: manual`) vs **reader** (device-initiated:
wiegand/lpr/qr/ticket). Filters are scoped within the current shift window, as the feed already is.
## Forgiven exit — open with NO payment (built 2026-10-08)
The one human-intervention open that is allowed to skip the payment: an operator holding
**`barrier:create`** (admin by default; the owner grants it per role) lets a car out for free.
Decision + as-built in [[forgiven-exit]]. In short: a ticketed car gets a **$0 `payment`
carrying `forgoneMinor`** (the fee it owed) then the same re-open path as above (anomaly +
`vehicle_exit` with `exit.forgiven`); a car with no session gets an anomaly under a
`forgiven:<id>` ref + the pulse. Reason optional, open shift required, **nothing printed**,
and the forgone amount is its own Z-report line — never inside cash/card ([[shift]]). The
no-unpaid-bypass rule above still holds for everyone without that permission.
## ⚠ Open question — walk-back grace renews on every payment (voucher overstay)
> **Update 2026-06-20 — pricing half resolved; grace-renewal half still open.** The overstay work
+25 -5
View File
@@ -2,7 +2,7 @@
type: concept
tags: [parking, architecture, devices, setup]
sources: [parking-system-architecture]
updated: 2026-06-15
updated: 2026-10-08
---
# Device Discovery
@@ -20,10 +20,30 @@ device carries an `id`, a `label`, a `config` blob to **auto-fill** the setup fo
(firmware, MAC, …). The [[device-registry]]'s `isDiscoverable()` guard lets the system treat it
as optional; the setup catalog returns a `discoverable` list of driver ids.
> **No current driver implements discovery.** The [[dingtian-relay]] board uses a fixed IP
> (entered/known at setup). The capability remains for future UDP-discoverable devices (cameras
> via ONVIF, etc.). The worked example below is the (removed) UHPPOTE driver — kept because the
> **broadcast gotchas are transferable** to any UDP discovery we add later.
> **Implemented by one driver (2026-10-08): the [[dingtian-dt008-reader|Dingtian DT-008 QR/RFID
> reader]]** (`dingtian-qr-reader`), via the vendor tool's UDP protocol reversed in
> [[dingtian-qr-linux-tool]] (`packages/devices/src/drivers/dingtian-qr-config.ts`). The
> [[dingtian-relay]] board still uses a fixed IP. The UHPPOTE example below is historical, kept
> because the **broadcast gotchas are transferable** — the DT-008 driver applies all of them.
## DT-008 reader discovery (current)
`discover()` sends the search command (2) to the **subnet-directed broadcast of every local
IPv4 interface** on UDP 24582 and collects the DeviceInfo replies (3) for 2 s, deduped by serial;
then, per reader, a unicast params read (30) so the wizard row shows what matters **before**
assigning: `output` mode (HTTP vs WG26/RS232/…), current `server:port` target, push `url`
extension, `cardFormat`, `firmware`. "Use" fills `serial` + `host`. Verified on the bench unit
(HC002721 @ 10.0.10.12) and, read-only, on park-2's two readers. Needs an L2 segment shared
with the readers: works from the booth (host-network server) and the device VLAN; **not** from a
bridged dev container (`docker-compose.dev.yml`) nor across Netbird — there, use
`scripts/dingtian_qr.py get <ip>` on the booth instead.
## Roadmap for the other devices
Cameras (SADP + ONVIF WS-Discovery, both verified on the lab VLAN 2026-10-08), network printers
(TCP 9100 sweep + web fingerprint), the Dingtian relay's multicast search and Dahua's 37810 tool
protocol — with the method and rules distilled from the DT-008 work — are planned in
[[device-discovery-roadmap]].
## UHPPOTE discovery (historical example)
+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]]).
+11 -1
View File
@@ -2,7 +2,7 @@
type: concept
tags: [parking, architecture, devices, admin]
sources: [parking-system-architecture]
updated: 2026-06-15
updated: 2026-10-08
---
# First-Run Setup (device selection)
@@ -30,6 +30,16 @@ lane** — the pool-of-spaces model; see [[entry-exit-points]].
authenticated input push ([[device-input-flow]]) — the admin never touches the device's own web
UI. **Fails the save** (no DB row) if the device can't be configured, so there are no
orphan/half-configured rows. On success persists to `devices`.
**DT-008 readers (2026-10-08)** go through the same pipeline when their IP is given: the
precondition check reads the reader over the vendor UDP protocol ([[dingtian-qr-linux-tool]])
and reports *output type ≠ HTTP* (fixable — the save switches it) and *typed serial ≠ reported
serial* (not fixable — the admin must enter the real one); `configureInputPush` then
set-networks the reader's push target to this booth's IP + listen port and confirms it by
re-reading (the reader is silent for a few seconds after the write, so it polls). The reader's
scan GET carries no credentials, so no push user/password is persisted for it
(`usesPushAuth = false`). With **no IP** nothing is configured and the save succeeds with a
warning — the reader must then be set up with the vendor tool / `scripts/dingtian_qr.py`
([[site-device-installation]] §2).
4. **Remove** — `DELETE /api/setup/assign/:id` (admin-only) drops one instance's row. Only our
row is removed; the device itself is not un-hardened/un-configured (a stale push from an
unknown device id is already rejected, and re-assigning reconfigures it).
+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.
+3 -3
View File
@@ -70,9 +70,9 @@ RESET_ALLOWED=1 DATABASE_URL=/path node packages/db/scripts/reset-db.mjs --all
| Flag | Wipes | Keeps |
| --- | --- | --- |
| `--financial` | `ledger_events` (entry/exit/payment/void/shift/cash/anomaly), `device_events`, `snapshots`, subscription **instances** + credentials/plates, `blocklist` | users, devices, config, tariffs, subscription **plans** |
| `--config` | `site_config`, `devices`, `setup_state` (→ re-runs first-run setup), tariffs + versions + **drafts**, subscription plans | everything else |
| `--users` | `users`, `roles`, `role_permissions`, auth `sessions` | everything else |
| `--financial` | `ledger_events` (entry/exit/payment/void/shift/cash/anomaly), `device_events`, `snapshots`, subscription **instances** + credentials/plates, `blocklist`, `carwash_orders`, `carwash_review_outbox` | users, devices, config, tariffs, subscription **plans**, Car Wash master data |
| `--config` | `site_config`, `devices`, `setup_state` (→ re-runs first-run setup), tariffs + versions + **drafts**, subscription plans, validation programs, `carwash_prices/categories/services/config` | everything else |
| `--users` | `users`, `roles`, `role_permissions`, `role_jobs`, auth `sessions` | everything else |
| `--diagnostics` | `app_logs` (the unsigned [[app-logs]] store behind `/setup/logs`) | everything else |
| `--all` | every table (blank slate) | — |
+15 -1
View File
@@ -2,7 +2,7 @@
type: concept
tags: [parking, printer, device, monitoring, reliability]
sources: []
updated: 2026-06-14
updated: 2026-09-09
---
# Printer status monitoring
@@ -90,3 +90,17 @@ reads. Full repo typechecks.
Yes/No and degrade on anything unexpected, so this is a confidence check, not a blocker.
- Tying a `degraded`/`offline` entry-dispenser into [[printer-roles-failover]] failover and the
(not-yet-built) entry flow's all-printers-down policy ([[device-input-flow]]).
## K200L — a second status-page board, and a fetch that node:http can't do (2026-09-09)
The park-buzi printer turned out to be a **K200L** (Xprinter/ICS XP-K200L; LAN board "J-Speed
Ethernet WebConfig 1.02", self-named "POS-80"). Its board serves the **same five decoded Yes/No
rows** as the Rongta page — under **`/prt_status.htm`**. Two things kept it invisible until now:
the Rongta driver only knew `/prn_stat.htm` (so in July the unit was filed as "no status page →
generic driver"), and the board's reply carries **no HTTP status line or headers** (HTTP/0.9
style), which `node:http` rejects outright and `curl` shows as an empty `000`. The new **`k200l`**
driver (`printer-k200l.ts`) prints through the generic ESC/POS path and reads the page over a raw
TCP socket, tolerant of both reply shapes; mapping is the Rongta one (unreachable → offline; page
not understood → degraded, never ready; any fault → degraded naming it; else ready; USB →
reachability floor). Bench-verified: cover open → amber "cover open, paper out, printer off-line".
Tests replay the captured headerless reply. Full device notes: [[k200l-printer]].
+73 -4
View File
@@ -2,7 +2,7 @@
type: concept
tags: [parking, device, printer, transport, usb, escpos, provisioning]
sources: []
updated: 2026-08-30
updated: 2026-09-09
status: settled
---
@@ -134,6 +134,11 @@ preselecting the first present device; a saved-but-unplugged path stays selectab
"saved — not present now"; zero devices found falls back to the free-text path + a check-the-cable
hint. The transport option label no longer hardcodes lp0.
> **Superseded 2026-09-09:** the XP-K200L DOES serve a status page — the same table as the Rongta,
> at **`/prt_status.htm`**, without HTTP headers. It now has its own **`k200l`** driver (raw-socket
> fetch; LAN = live cover/paper status, USB = reachability floor). See [[k200l-printer]]. The note
> below is kept for the record.
>
> Driver-choice note for this clone: the ICS XP-K200L does NOT serve the Rongta `/prn_stat.htm`
> status page (checked on hardware at 10.0.10.11 — print socket 9100 open, status page absent),
> so on NETWORK the honest driver is **cashino** (reachability-only monitoring); under `rongta`
@@ -174,7 +179,60 @@ itself is redone.
target on a policy-driven restart, the container can come back up still bound to the pre-incident
view. This matches the exact reported asymmetry (reboot doesn't fix it; explicit restart does).
**Not yet confirmed on hardware** — this is the leading theory, not a verified root cause. To
> **Bench result 2026-09-09 — the re-enumeration hypothesis is FALSIFIED for this unit.** The
> failing printer (`1fc9:2016` "POS-80", now on the dev bench, attached to WSL via usbipd) was
> cover-cycled while `dmesg -w` and `lsusb` were watched: **nothing** — no disconnect, no
> re-enumeration, same bus/device number (a real drop would have shown as a vhci detach, since
> Windows sees the bus first). So the device node does NOT change when the cover opens, and the
> container `/dev/usb` bind-mount cannot be going stale for that reason. The failure is in how
> `usblp` / the app's open-probe reacts to the printer's **error state** (cover-open status),
> not in the device node. Next discriminator is the **exact `detail` text** the monitor logged
> on park-buzi at the offline transition (`docker logs <stack>-server-1 | grep
> 'device-monitor:.*-> offline'`): `EBUSY` = a handle is held inside the server process (usblp
> allows ONE opener — candidate: the `withTimeout` open-leak or a close that never returned;
> fits "docker restart fixes"), `usb open timeout` = `open()` itself blocks in the kernel, `EIO`
> = `usblp_open`'s bidirectional read submit failed (printer endpoint state). The theory below
> is kept for the record.
> **Lab reproduction FAILED to reproduce (2026-09-09, later the same day).** The same printer
> unit on the `park-lab` box (a real Linux host, the booth's exact image `stage-2d9bb15`, the
> prod compose with the `/dev/usb` bind-mount, the dev DB snapshot with the USB printer added as
> `booth-receipt`, cards printed via the subscription "Reprint card" path): paper out → open
> cover → load roll → close cover → reprint — **no error, status never stuck offline.** So the
> printer, the app's USB transport and the compose wiring are cleared in isolation. What is left
> is park-buzi's own environment (kernel/USB stack, the physical USB port/hub/cable/power at the
> booth) and/or that container's *history* (weeks of uptime before the first failure — a leaked
> handle needs a prior timeout to exist; a fresh container has none).
>
> **Status: park-buzi closed (staff shortage), everything shut down — evidence pending.** The
> evidence is on the booth's DISK and survives shutdown/reboot: Docker keeps the container log
> under `/var/lib/docker/containers/<id>/`, the kernel journal is persistent. **The day the box
> powers on again (or lands on the bench), pull these FIRST, before deploying anything:**
>
> ```bash
> # 1. the app's own record: the exact error text at every offline/ready transition
> docker logs park-buzi-server-1 2>&1 | grep -E "device-monitor:.*printer.*-> (offline|ready)"
> # 2. what the HOST kernel saw around those times (usblp errors, resets, disconnects)
> sudo journalctl -k --since "-30 days" | grep -i -E "usblp|usb 1-|usb 2-|disconnect|reset"
> # 3. the physical path: hub or direct port? (and note which PSU feeds the printer)
> lsusb -t
> ```
>
> Reading (1): `EBUSY` = a handle stuck inside the server process (usblp allows ONE opener;
> fits "container restart fixes it") → look at the `withTimeout` leak below; `usb open timeout`
> = `open()` blocks in the kernel; `EIO` = `usblp_open`'s bidirectional read submit failed
> (printer/link state). Reading (2): any `USB disconnect` / `reset` / `usblp1: removed` at the
> transition times means the LINK dropped at the booth (cable/port/hub/power) even though the
> unit never dropped on the bench.
>
> **Follow-ups that need no booth (proposed, not built):** (a) `withTimeout` in
> `printer-escpos.ts` abandons the FileHandle when an open/write times out — close it when the
> underlying promise eventually settles, so a timeout can never leave the node held; (b) make
> the monitor self-document the next occurrence: after N consecutive offline polls on a USB
> printer, log the errno, `ls -la /dev/usb`, and who holds the node, so the next failure anywhere
> in the fleet carries its own diagnosis without a person at the booth.
**Not confirmed on hardware — and now contradicted by the bench (above).** The original plan to
confirm at the next occurrence, BEFORE restarting anything:
```bash
# host:
@@ -197,8 +255,19 @@ whether the Bus/Device number changes.
passthrough + a udev rule pinning a stable symlink name — reintroduces the renumbering fragility
the directory bind-mount was chosen to avoid, so only worth doing alongside (1)/(2), not instead.
**Open sub-question — printer identity.** The park-buzi unit shows as "Generic (unknown)" in the
app; not yet identified by vendor/product ID. Lab reproduction uses a **RONGTA** unit instead (not
**Printer identity — IDENTIFIED 2026-09-09.** The failing unit is on the dev bench: a **K200L**
(Xprinter/ICS XP-K200L family — see [[k200l-printer]] for the LAN setup and its status page): USB
`1fc9:2016`, product string **"Printer POS-80"** (0x1fc9 = NXP, the printer's USB controller chip;
"POS-80" is the generic 80 mm ESC/POS designation — no brand in the descriptor, which is why the app
shows "Generic"). Seen via `usbipd list` on the Windows host (busid 8-1). **Dev-bench caveat:** the
stock Microsoft WSL2 kernel (6.6.87.2) has `CONFIG_USB_PRINTER` **not set** — usbip/vhci is there,
so the printer can be attached and seen by `lsusb`, but no `usblp` → no `/dev/usb/lpN` → the app's
USB transport and the container's `/dev/usb` bind-mount cannot be exercised without a custom WSL
kernel (`.wslconfig` `kernel=`) built with `CONFIG_USB_PRINTER=y`. Also, through usbip the
cover-open disconnect is seen by *Windows* first (usbipd detaches; `--auto-attach` re-exports), so
the bench only shows *whether* the device drops off the bus, not the host-kernel/container
staleness itself. Previously: the park-buzi unit showed as "Generic (unknown)" in the app; not
identified by vendor/product ID. Lab reproduction uses a **RONGTA** unit instead (not
the same hardware), so the lab cannot currently reproduce the park-buzi symptom directly — only
validate the general re-enumeration mechanism. Commands to identify the real park-buzi printer next
time it's reachable via SSH: `lsusb`, `udevadm info -q property -n /dev/usb/lp1`, `udevadm info -a
+10
View File
@@ -113,6 +113,16 @@ no variance gate, no manager override.
> shared via `formatStampSq` from [[rongta-printer]]. Consistent with the "[[i18n|printed paper is
> always Albanian]]" rule — independent of the operator's UI language.
### Forgiven exits on the Z-report (built 2026-10-08)
A [[forgiven-exit]] is a signed `payment` with `amountMinor: 0` and `forgoneMinor` = the fee
waived, no tender. It adds **nothing** to cash, card, the ticket bucket or the drawer (the
tender sums add 0), so the shift total is untouched by construction. The Z-report sums
`forgoneMinor` into `forgoneTotalMinor` + `forgoneCount`, stamps them on the signed
`shift_z_report` (only when > 0, so older payloads stay identical) and prints one line
`Dalje manuale (N): X` after the merchant-validation leakage line — a separate figure on
purpose, so the owner can tell "the bar validated it" from "the operator let it out".
### Shift history UI + permission scoping (2026-06-19)
A read-only **shift-history screen** (`GET /api/shifts`) lists completed shifts — each a signed
`shift_z_report` folded for its figures (no re-summing), newest-first, expandable to the drawer
+347
View File
@@ -0,0 +1,347 @@
---
type: reference
tags: [parking, runbook, installation, devices, network, field]
sources: []
updated: 2026-10-08
---
# Site device installation — know it BEFORE you are standing in the booth
A field runbook: for every device we deploy, its **factory address and credentials**, the **tool**
you need, **what the app configures by itself** at assign time versus **what must be done by hand on
the device**, and the **traps already paid for** on park-buzi and the lab. The [[appliance-provisioning]]
runbook covers the booth PC (OS, disk, Docker, Periphery); this page covers everything plugged into
it. Written 2026-09-09 after an evening lost to a printer whose factory address nobody had written
down ([[k200l-printer]]).
Rule of thumb that explains most of this page: **every field device ships on its own private
subnet with DHCP off, and none of them announce themselves.** You bring a laptop that can take a
second static address, you put it on the device's factory subnet, you move the device to the site
plan, and only then does anything else see it.
## Before leaving the office
**Bring**
- A laptop with an Ethernet port and the right to add a **second static IPv4 address** to it
(Windows: adapter → IPv4 → Advanced → add). Under WSL, remember the source-address bug
([[wsl-dev-networking]]): after adding a temporary address, `ping` may work while HTTP times out.
- The Dingtian reader tool **`QRCode_v1_6_5.exe`** (Windows) **or `scripts/dingtian_qr.py`**
(Python 3, runs on the booth itself — see [[dingtian-qr-linux-tool]]) for a DT-008's IP, server
target, output type, prefixes and card format. Symbologies are set in neither (no known path).
A browser is enough for everything else.
- Patch cables, a USB A–B cable (printers), the site's **address plan** (below) filled in, the
app **admin** password, and a fresh Komodo **onboarding key** if the booth PC is new
([[appliance-provisioning]] §7a).
- The **serials** if already known: DT-008 `cjihao` (on the reader's label / in the tool), camera
MAC/serial, printer model (label on the bottom — the K200L's own web UI calls it "POS-80").
**Address plan** — the device VLAN ([[network-isolation]]) is `10.0.10.0/24` on both sites so far,
**every device static, DHCP off everywhere**. The convention from park-buzi / park-lab:
| Address | Device | Factory address it came from |
| --- | --- | --- |
| 10.0.10.1 | VLAN gateway (switch/router) | — |
| 10.0.10.5 | [[dingtian-relay]] board (barriers + inputs) | `192.168.1.100` |
| 10.0.10.7 / .8 | [[dingtian-dt008-reader]] entry / exit (**unique IP each**) | `192.168.1.99` |
| 10.0.10.9 | entry-dispenser printer (park-buzi: Cashino KP-300H) | *not recorded — fill in* |
| 10.0.10.10 | booth-receipt printer (park-buzi: [[rongta-printer]]) | *not recorded — fill in* |
| 10.0.10.11 / .7 (lab) | [[k200l-printer]] | `192.168.123.100` |
| 10.0.10.12 / .13 | [[lpr-camera]] entry / exit (Hikvision DS-2CD1047G3H-LIU) | `192.168.1.64` (Hikvision default; needs activation) |
| 10.0.10.203 | the booth PC on the device VLAN (**the `backendIp` every device pushes to**) | — |
Fill the real numbers into the site record before you drive; the wizard asks for the booth's push
address once and writes it into the Dingtian and the cameras.
## 1. Dingtian relay board (DT-R004 family) — barriers, button, radar
**Factory:** IP `192.168.1.100`, web UI on port 80, login `admin` / `admin`, UDP `60000` (binary) /
`60001` (string), multicast discovery `224.0.2.11:60000`. See [[dingtian-relay]].
**By hand, on the device (browser at its factory address):** set the site IP / mask / gateway in
the Network page and reboot. That is the only thing you *must* do by hand. Optional but recommended:
in the web UI **disable the UDP2 "string" protocol** (a password-less relay-fire path); the app's
harden step tries to disable it and **warns if the device refused** — then do it here.
**Wiring:** button on **I1** (NO contact to GND, idles HIGH, pulls LOW on press); radar dry contact
on **I2**; barrier operator's open input on **relay 1** (entry) and **relay 2** (exit); a spare relay
for the entry button lamp ([[button-light-indicator]]). One board can carry both barriers; two
distant barriers = two boards ([[entry-exit-points]]).
**What the wizard does on assign** ([[first-run-setup]], [[device-input-flow]]): finds the board by
multicast ("Scan for controllers" — laptop/booth must share the L2 segment), checks and clears
`input_link_relay` (factory default auto-fires a relay from its input — the app must decide, not the
board), sets a random **relay password** (UDP binary), disables every other control channel, rotates
the web login, and writes the **input push** URL + per-device Digest credentials so button/radar
edges reach the booth PC. You enter the relay map (which relay is entry/exit/both) and the inputs
(button → its relay; radar → `presence`, `activeLow` if it idles opposite the button —
[[hikvision-radar]]).
**Traps**
- The HTTP CGI API is **unauthenticated** on this firmware; `admin/admin` gates only the web page.
Never enable `session_en` — it bricks the config API and only a **factory reset** recovers. The
VLAN is the boundary, not the login ([[dingtian-relay]] §Hardening).
- A relay password mismatch shows as **"offline despite ping"**: the status query is answered only
with the right password. Re-assign / re-enter the relay password in the device form.
- "Relay test" in Setup pulses real hardware and signs a ledger event — use it to prove wiring,
once per relay.
## 2. Dingtian DT-008 QR + RFID readers
**Factory:** IP `192.168.1.99`; no web UI — everything is set over the network with
**`QRCode_v1_6_5.exe`** (Windows) or **`scripts/dingtian_qr.py`** (any OS; same UDP protocol,
reversed 2026-10 — [[dingtian-qr-linux-tool]]). See [[dingtian-dt008-reader]].
**From the wizard (app builds after 2026-10-08):** add a reader → **Skano LAN-in / Scan the
LAN** lists every DT-008 on the device VLAN with its mode and current server; **Use** fills
serial + IP; **Test** says whether it is in HTTP mode and whether the serial matches; **Save**
switches it to HTTP and points its server at this booth (items 2 and 6 below, done for you).
Items 1, 3, 4, 5 are still manual (IP via `set-network`, prefixes/card format via `set`, both in
`scripts/dingtian_qr.py`; symbologies only in the exe). Needs the reader's IP in the form — with
it blank the save warns and configures nothing.
**By hand (vendor tool, or `scripts/dingtian_qr.py` from the booth), per reader:**
1. **Unique device IP** (`.7` entry, `.8` exit). Two readers on one IP was the 2026-06-18
"wrong barrier" incident — scans land on the wrong device row.
2. **Output type = `HTTP`** (the tool also offers RS232 / WG26 / WG34 / RS485 / USB keyboard /
USB serial — in any of those the reader beeps locally and never contacts the booth), **Server
IP = THIS site's booth** (park-2 is `10.0.10.101`; `10.0.10.203` is the lab — never copy it),
**server port** = the booth's HTTP port (80 behind the prod proxy); "server language" can stay
whatever it is (php/jsp/asp/aspx/cgi are all served — the reader GETs `/qa/mcardsea.<ext>`).
3. **Output prefixes:** `QRCode Output Prefix` = `Q:`, `Card Output Prefix` = `K:` (channel
tagging — a printed clone of a card cannot pass as the card).
4. **Card Input format = `6H`** (defines the UID shape enrolled; changing it later orphans every
card).
5. **Symbologies: QR + Code128 only**, minimum decode length ≥ 10, checksums on — otherwise low
sun through the striped arm produces phantom 6-digit reads (park-buzi, July).
6. Note the **serial (`cjihao`)** — the wizard binds the reader by serial, not by IP.
**In the wizard:** add the reader with its serial, bind it to the controller relay it sits at
(direction is inherited from the relay). **Verify:** scan a card — the server log shows
`READ serial=… → device=… verdict=… dir=…`; the reader beeps **twice** on accept, once on refuse,
and only after the server's reply (no reply = no beep, the scan still happened).
**From the booth, no Windows (2026-10-08):** `get` / `set` are unicast UDP, so they run on the
booth host over SSH (Python 3 is on every booth; the server container has none):
```
scp scripts/dingtian_qr.py <booth>:/tmp/ && ssh <booth> python3 -I /tmp/dingtian_qr.py get 10.0.10.7
ssh <booth> python3 -I /tmp/dingtian_qr.py set 10.0.10.7 --output-type 3 # item 2: HTTP mode
```
`get` prints every field above by name (`output_type`, `server`, `server_port`, `card_input_format`,
`qr_prefix`, `card_prefix`…). `set` changes only the fields given and re-sends the rest as read.
Only `discover` / `set-network` need the L2 broadcast (run them on the booth, not across Netbird).
**Trap:** a factory reset or a swapped unit silently loses items 3–5. Re-apply all of them.
**Trap (park-2, 2026-10-08): "it beeps, so it works" is false.** Enrolling a card failed on both
readers although each beeped. The booth log held **zero** `/qa/mcardsea` requests over 21 h and the
capture window saw only the form's own polls: the readers never contact the booth at all. A beep
without a `READ` line in the log means the reader is **not in HTTP mode or points at another
server** — fix it on the reader (item 2), nothing in the app or the wizard can. Diagnose in one
command on the booth: `docker logs <server> --since 1h 2>&1 | grep -c mcardsea` while a card is
presented — `0` = reader-side; then **read the reader itself** with `dingtian_qr.py get` (above).
park-2's answer: both readers `output_type = WG26` (server `10.0.10.101:3000`, JSP, 6H, no
prefixes) — they were left in Wiegand mode at install, so every scan went to a Wiegand line
nobody is listening on. (Port 3000 is fine: the host-net server listens there directly; 80 via
Caddy works too.) Fix = `set <ip> --output-type 3` per reader, then re-run the enrolment.
**Trap (2026-09-17): two DT-008 units read disjoint card sets.** park-buzi's units (`H05M…`)
read the site's 125 kHz cards and the fresh lab unit (`HC002721`) reads only 13.56 MHz cards,
although the box leaflet claims both. Batch variant, a dead 125 kHz front end, or a non-EM 125 kHz
card format — unresolved. Rule until it is: **test a replacement reader against the site's actual
cards before it ships**, and record the site's card technology. Quick sort of a card: an NFC phone
detects 13.56 MHz, cannot see 125 kHz. Details: [[dingtian-dt008-reader]] §"Two units, two card
sets".
**Identify what a reader can read — before it ships (2026-09-17).** Keep a **reference kit** in the
lab: one known EM4100 125 kHz fob, one known Mifare Classic (M1) card, and a phone with NFC. Tap all
three on the unit with the tool's log pane open (or [[dingtian-dt008-reader]] §Bench sink): a line
per tap = that technology decodes. The phone always beeps on a 13.56 MHz unit with a random `08…`
id (never a credential, but proves the 13.56 MHz radio). Then tap **the site's own cards**. Write
the result on the site record next to the serial (`reads: EM4100 | M1 | both`). Serial families are
only a hint (`H05M…` read park-buzi's 125 kHz cards, `HC…` did not); the vendor can confirm from a
serial. A unit that fails the site's cards does not leave the lab.
**Parameters per card technology** — identical except one field:
| | 125 kHz site (park-buzi today) | 13.56 MHz site |
| --- | --- | --- |
| Card Input format | **`6H`** (what park-buzi's cards are enrolled with — never change on a live site) | **`8H`** preferred: the native UID is 4 bytes, `6H` drops one and two cards can collide — confirm `8H` on the lab unit before the first enrolment ([[open-questions]] #18) |
| Output prefixes | `Q:` / `K:` | `Q:` / `K:` |
| Output type / server | HTTP, booth IP, booth HTTP port | same |
| Buzzer | On (the operator hears accept/refuse) | On |
| Symbologies | QR + Code128 only | same |
| Card stock | EM4100 (or whatever the reference test showed) — do not mix | Mifare Classic UID-based; note that a phone is never a card |
A site is one technology: once cards are enrolled the reader batch, the input format and the
card stock are frozen together. Migrating means re-enrolling every credential.
**The tool's Setting tab (v1.6.5, seen 2026-09-17):** *Search device* lists units by serial; *Get
parameter* loads one. *Network parameter*: IP / Netmask / Gateway / DNS1 / DNS2, DHCP (Static IP),
**Server address / Server Port / HTTP Server Language**, its own *Set* button. *Format parameter*:
Output type `HTTP`, **Card Input format** (`6H`), QRCode Output format/prefix/suffix, **Card Output
format/prefix/suffix** (prefix fields are where `Q:` / `K:` go), serial baud/bits greyed out under
HTTP, Low/High Pulse, its own *Set*. *External parameter*: Restart interval (12 h), Work mode
(Normal), **Buzzer On/Off**, Scan code fill light, its own *Set*. Each group is written by **its own
Set button** — setting the network and forgetting the format *Set* is easy. The log pane at the bottom
echoes every card read by the tool (`… A238BC`), which is the quickest "did the radio see it" check.
The *Test device* tab is the read monitor. Symbology selection was not found on this tab — locate it
on the *Test device* tab or in a newer tool before relying on item 5.
## 3. Hikvision camera (DS-2CD1047G3H-LIU, AcuSense) — ANPR + snapshots
**Factory:** `192.168.1.64`, **inactive** until a password is set on first boot (browser at that
address or the SADP tool); after activation the login is `admin` / the password you chose. Site
convention so far: `admin` / `admin123` on the first units (change per site and record it). See
[[lpr-camera]].
**By hand, on the camera:**
1. Activate, set the site IP, disable DHCP. Time: NTP off-site is unavailable — the app re-syncs
the camera clock from the booth at every offline→ready edge ([[clock-integrity]]).
2. **Streams:** the snapshot the app pulls MUST come from the **sub stream** (`102`) — the main
stream's ISAPI snapshot returns **503 instantly, always, on this model**. Set the sub stream to
the highest resolution the camera allows.
3. **Event push:** Event → Motion Detection with the AcuSense **Detection Target = Vehicle** filter
ON, "Notify Surveillance Center" on, then Alarm Settings → **Alarm Server** →
`http://10.0.10.203/api/devices/hikvision/<deviceId>/event`. The `deviceId` exists only after
the wizard assign, so: **assign first, then come back to the camera**. Digest user/password if
the firmware allows it (the wizard shows them).
4. "Enable Hikvision-CGI" is a different legacy surface — **not** needed for ISAPI.
5. **Close the web UI / live view when done.** The camera has few connection slots; a browser left
open makes every snapshot pull 503 "Device Busy" ([[lpr-camera]] §503).
**In the wizard:** driver `hikvision`, host, `admin` password, channel 1, **stream = Sub**, ANPR on,
bind to the relay at that barrier, `alarmPushEnabled` on.
**Verify, do not assume:** drive a car through and look at `GET /api/events` (or the log) for an
alarm with `targetType=vehicle`. A camera configured for push that has sent **zero** alarms is
broken on its side: pull its *Diagnose Information*; `Main Db is broken` means a corrupt config
database → **factory reset**, then redo 1–3 (the Vehicle target filter defaults OFF after a reset).
Point the Alarm Server at a dumb HTTP sink on the laptop if you need to see the verbatim body
([[lpr-camera]] §"auto-enter but not auto-exit").
**If the camera is a Dahua** (first unit inspected 2026-09-17, [[dahua-ipc-hfw2549t]]): factory
`192.168.1.108`, `admin` + a password set at first boot, web UI on port 80 (HTTPS off by default
on the bench unit). In the wizard: driver `dahua`, host, `admin` password, **channel 1 as printed** (the
driver sent `channel=0` → HTTP 400 until 2026-09-17; fixed). There is no HTTP Alarm Server to
point at the booth: events would be read by the server holding an `eventManager.cgi?action=attach`
stream (**not built yet** — a Dahua today gives snapshots + clock sync only, no lane busy/free
and no ANPR bridge), so no "assign first, then go back to the camera" step — but SMD must be set
to **Vehicle** on the camera. Set the time zone by hand; the app re-syncs the clock from the
booth like it does for Hikvision (the bench unit ran 1 h behind with DST off; NTP is useless on
the isolated VLAN). Five wrong logins lock `admin` for 5 minutes — check the password with one
`curl --digest` before assigning.
## 4. Radar (vehicle presence at the entry barrier)
A dry-contact sensor into a Dingtian input, nothing on the network. Check with the board's input
status (`00` query → `relays:inputs`) whether it **idles HIGH or LOW**; if it idles opposite the
button, set `activeLow` on that input in the wizard, or the gate inverts (tickets only when the
lane is empty). It is advisory: it gates the button, it never opens anything ([[hikvision-radar]],
[[entry-double-press]]).
## 5. Printers — three models, one byte stream, different status
All print the same ESC/POS bytes over **raw TCP 9100** or **USB (`/dev/usb/lpN`)**; what differs
is whether the app can see paper/cover state ([[printer-status-monitoring]],
[[printer-usb-transport]]). Roles: **entry-dispenser** outside at the lane, **booth-receipt**
inside (receipts, subscription cards, Z-reports, and the backup for entry tickets), **wash-desk**
if the site has a Car Wash ([[printer-roles-failover]]). Higher `failoverRank` = tried first.
| Model | Factory network | Config UI | App driver | Live status |
| --- | --- | --- | --- | --- |
| [[k200l-printer]] (Xprinter/ICS K200L, "POS-80" board; **the park-buzi unit**) | `192.168.123.100/24`, DHCP off | browser, port 80, no login: Configuration → fixed IP → Save → Restart | **`k200l`** | over LAN: cover / paper / cutter / off-line from `/prt_status.htm`; over USB: reachability only |
| [[rongta-printer]] (RP-series) | *not recorded — fill in* | status page `/prn_stat.htm` on port 80 | `rongta` | over LAN: full; USB: reachability |
| Cashino KP-300H | *not recorded — fill in* | *not recorded* | `escpos` (generic) | reachability only, by design — no trustworthy status source |
**Prefer LAN over USB** wherever a cable can reach: the booth sees a real amber "cover open, paper
out" while a roll is changed, and the `usblp` path (udev rule, node renumbering, the park-buzi
"offline after reload" mystery) drops out of the picture. USB needs the appliance's `usblp` +
udev rule ([[printer-usb-transport]] §Provisioning) and the printer shows up as `/dev/usb/lpN`,
numbered by plug order.
**Verify:** the wizard's "Test" only *probes* (opens the port / the device node) — it prints
nothing. Print something real: a subscription with a QR credential auto-prints its card and has a
**Reprint card** button; a payment prints a receipt; a wash till prints slips. Check the Cashino's
barcode with a real ticket (the KP-300H garbled overflowing barcodes until the geometry fix).
## 6. Order of work on site
1. Address plan on paper; VLAN ports patched; booth PC up with its device-VLAN address.
2. Dingtian: factory address → site address (browser) → wire button, radar, barriers.
3. Wizard: **controllers first** (the relay map + inputs); "Relay test" each barrier.
4. Readers: tool (IP, server, prefixes, format, symbologies) → wizard (serial, bind) → scan test.
5. Cameras: activate → IP → sub stream → wizard assign → Alarm Server + Vehicle target → drive-through
test → close the browser.
6. Printers: site address → wizard (role, rank) → print a card.
7. Walk-through: button + radar → ticket; QR entry then exit; RFID; a subscriber's plate at the
camera; pay at the booth → receipt → exit; paper reload on each printer while watching the
footer.
8. Record in the site record: every IP, serial, camera password, printer model, which relay is
which, photos of the labels. Remove the temporary laptop addresses. Log out of every device UI.
## 7. Reaching the cameras remotely — port forward through the booth host (park-2, 2026-10-08)
park-buzi exposed its two Hikvision web UIs on the site router (`park-buzi.msai.al:8081` / `:8082`,
see [[lpr-camera]]). park-2 does the same **through the booth host**, because its router only
knows the 192.168.1.0/24 side while the cameras live on the device VLAN:
| | address |
| --- | --- |
| router / internet side | `eno1` 192.168.1.101, gateway 192.168.1.1, public 91.230.255.154 |
| device VLAN side | `eno1` 10.0.10.101 (same NIC, second address) |
| Netbird | `wt0` 100.75.7.237 = `park-2.nb.infra` |
| entry camera | 10.0.10.9:80 → published as **8081** |
| exit camera | 10.0.10.10:80 → published as **8082** |
Done with iptables on the host (needs root; the admin account has no passwordless sudo).
`ip_forward` is already 1 because Docker set it. Docker also sets the FORWARD policy to DROP, so
the explicit ACCEPTs are mandatory, and the SNAT is what brings the camera's replies back through
the host (the cameras' gateway is not the booth):
```bash
iptables -t nat -A PREROUTING -p tcp --dport 8081 -j DNAT --to-destination 10.0.10.9:80
iptables -t nat -A PREROUTING -p tcp --dport 8082 -j DNAT --to-destination 10.0.10.10:80
iptables -t nat -A POSTROUTING -p tcp -d 10.0.10.9 --dport 80 -j SNAT --to-source 10.0.10.101
iptables -t nat -A POSTROUTING -p tcp -d 10.0.10.10 --dport 80 -j SNAT --to-source 10.0.10.101
iptables -I FORWARD -p tcp -d 10.0.10.9 --dport 80 -j ACCEPT
iptables -I FORWARD -p tcp -d 10.0.10.10 --dport 80 -j ACCEPT
iptables -I FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
apt install -y iptables-persistent && netfilter-persistent save # survive reboots
```
- **Reach:** from any Netbird peer with a policy to park-2, `http://park-2.nb.infra:8081/`
(no router change needed). From the internet only once the router forwards 8081/8082 to
192.168.1.101. PREROUTING does not apply to the host's own traffic — test from another machine.
- **Netbird-only variant:** add `-d 100.75.7.237` to the two PREROUTING rules; then the public
forward can never reach the cameras even if someone adds it on the router.
- **Undo:** the same lines with `-D`. **ufw**, if ever enabled there, also needs
`ufw route allow proto tcp to 10.0.10.9 port 80` (and `.10`).
- **Why not Docker:** `docker run -p 100.75.7.237:8081:80 alpine/socat …` would do the same
without sudo, bound to the overlay only; the user chose the iptables route.
- This is a deliberate hole in [[network-isolation]] (camera web UI reachable off the VLAN);
the camera's own digest auth is the only gate behind it. Keep the public side off unless
needed; prefer the Netbird path.
## Gaps to fill next time you hold the hardware
- Factory address and configuration tool of the **Cashino KP-300H** and the **Rongta RP** units
(both still unknown here).
- Where in `QRCode_v1_6_5.exe` the **symbologies** are selected (the Setting tab has no such field;
the IP / server / prefix fields are now described in §2).
- The **card technology** each site uses and which reader batch reads it, on the site record next to
the serial; and the result of the EM4100 test on the lab unit.
- Whether the camera activation was done with SADP or the browser at park-buzi, and the per-site
camera password location.
- Where the **site record** lives (a page per site under `wiki/entities/`? — park-buzi and park-2
have none yet; the Komodo stack env is the closest thing).
Related: [[appliance-provisioning]] · [[first-run-setup]] · [[device-registry]] ·
[[network-isolation]] · [[entry-exit-points]] · [[dingtian-relay]] · [[dingtian-dt008-reader]] ·
[[lpr-camera]] · [[hikvision-radar]] · [[k200l-printer]] · [[rongta-printer]] ·
[[printer-usb-transport]] · [[wsl-dev-networking]]
+9 -1
View File
@@ -2,12 +2,20 @@
type: concept
tags: [parking, domain, business, pricing, validation, design]
sources: [parksql2017-legacy-schema]
updated: 2026-06-17
updated: 2026-09-08
status: open
---
# Validation & Sponsorship — merchant comps, coupons, postpaid B2B
> **Sponsor accounts superseded (2026-09-08).** The `sponsors` table sketched below — a
> counterparty with a stored `balance_minor` and a billing period — is now a special case of the
> **[[party-ledger]]** (design): any party (subscriber, hotel, fleet, supplier) with a balance
> *derived* from signed `charge` / settlement / `write_off` events, never a stored column. A
> postpaid sponsor = a party; each comped stay = a `charge` against it; the monthly invoice = its
> statement. The validation *mechanics* (signed validation events on a session) are unchanged
> and built ([[validation-discounts]]).
Builds on [[validation-discounts]] (the signed-event discount mechanism) to add the layer it leaves
open: **a sponsor account and postpaid B2B billing.** The driving case — **a nearby business with a
postpaid agreement whose customers enter and exit freely, billed to the business monthly.**
+64 -1
View File
@@ -1,7 +1,7 @@
---
title: Vision review outbox — harvesting the operator's category choice for a trusted reviewer
type: concept
status: booth side built 2026-09-06; collector pending
status: live — first package delivered park-2 → collector 2026-10-08 (after a month blocked by a missing Netbird policy)
related: [venue-modules, opencv-anpr-service, threat-model, append-only-event-chain, network-isolation]
---
@@ -58,6 +58,20 @@ exactly one in N) and calls `enqueueEntry()`; the core never imports the module.
as "entry stream — label the vehicle", the export carries a `kind` column, and **operator
agreement is computed from wash items only** (an entry sample has no operator decision).
**Every car that passes, not only ticketed ones (2026-10-08).** The entry stream was fed from
the session-tied read only (`snapshot.ts`, taken when a ticket is printed or an exit is signed).
park-2 ran a whole afternoon with its barriers up: hundreds of camera vehicle pushes, zero
tickets, zero samples. So the ANPR bridge (`anpr-entry.ts`), which already pulls and analyses
frames for every vehicle push on an `anpr: true` camera, now keeps the **best-framed vehicle of
each poll loop** (highest body-type confidence with a box), stores that one frame as a snapshot
(`identity = pass:<snapshotId>`, no session) and emits a vehicle read with the camera's id —
plate or no plate. One sample per detection (the loop is one per car, joins slide it). The
module's `sampleEntry(deviceId)` **dedups per camera for 30 s** (`ENTRY_DEDUP_MS`): the pass
sample and the ticket entry's read, seconds apart from the same camera, are one car. The plate
box is handed over whenever the detector saw a plate, confident or not — it is what the crop
blurs. Pass snapshots ride the normal retention/pruning. Needs `anpr: true` and the per-camera
auto-trigger on (the bridge bails before polling otherwise) — same gate as recognition today.
An internet feed was considered the same day and kept OUT of the collector's ingest: licensed
sets only, in a separate folder with provenance, used as warm-up and weighted down, and never
the judge of accuracy — the evaluation set is gate crops only.
@@ -154,6 +168,55 @@ its own repo the day it needs its own cadence. Deploy the collector BEFORE a boo
package kind it does not know (a 422 is abandoned, not retried). The export neutralises cells
that start like a spreadsheet formula (category/service names are booth-supplied text).
> **Incident 2026-09-16 — the collector's DB predated the `kind` column; nothing worked for 9
> days and nothing said so.** The reviewer opened /review: *Training — trainer not reachable:
> fetch failed*. On the host: collector `stage-2d9bb15` **unhealthy** (`/health` → 500 *no such
> column: kind*), trainer healthy but every `/readiness` a Python traceback; the volume's
> `collector.sqlite` (created 2026-09-07 by the previous build, **0 items**) had the original
> column set. `CREATE TABLE IF NOT EXISTS` shapes only a NEW database — an existing volume keeps
> its old columns, so every query naming `kind` failed: the collector's health, **every ingest**
> (booths would have got 500s and kept retrying — the log shows none ever arrived, a separate
> question), and the trainer's readiness. The trainer's stdlib server printed the traceback and
> dropped the socket, which the collector could only render as "fetch failed".
>
> Fixes (same day): `CollectorDb` now **migrates on open** — `PRAGMA table_info` vs a list of the
> columns added since the first deploy, `ALTER TABLE … ADD COLUMN` for each missing one (all
> nullable or defaulted; **append to that list whenever a column joins the CREATE**); the trainer's
> handlers are guarded — an unexpected exception is a **500 JSON** naming the error, never a
> dropped connection; the collector's status proxy surfaces the trainer's error text. Rule going
> forward: the collector owns the schema; the trainer only reads; a deploy that changes the table
> must be accompanied by a migration entry, and the Training section is the first place a
> schema/DB mismatch shows — read its error text before suspecting the network.
**Status (2026-09-07).** Live: the collector runs on `art-docker-station` and park-2 is wired to
it (`stage-dbbb051` on both stacks, every entry sampled). The review screen at
`http://docker-station.nb.infra:8090/review` is filling; no labels reviewed yet.
## Troubleshooting — "the cameras are busy but nothing reaches the collector" (2026-10-08)
Found a month after both sides were built: **not one package had ever arrived**. Both codebases
were fine; the Netbird **policy** between the booths group and the collector host did not exist,
so `docker-station.nb.infra` resolved nowhere from the booth (Node: `fetch failed`, cause
`ENOTFOUND`; every row `queued`, attempts climbing, the 6 h backoff cap hiding it). Adding the
policy in the Netbird dashboard was the whole fix — the first row went out at its next scheduled
retry, nothing restarted. Checklist, in order:
1. **Is anything queued at all?** Only a vehicle read **tied to a session** (ticket taken or an
exit) is sampled; the camera's motion pushes feed subscription plate matching only. Barriers
left open = no tickets = no samples, however busy the lane. Query on the booth (no sqlite3
there; use the image's own driver):
```bash
s=$(docker ps -q --filter name=server); m=/app/node_modules/.pnpm/better-sqlite3@12.10.1/node_modules/better-sqlite3
docker exec $s node -e "const D=require('$m');const db=new D('/data/parking.sqlite',{readonly:true});
console.log(db.prepare(\"select status, json_extract(payload,'\$.kind') kind, count(*) n, max(sent_at) lastSent, max(last_error) err from carwash_review_outbox group by 1,2\").all())"
```
(`kind` lives inside `payload`; the image is in the row until delivered.)
2. **`fetch failed`** → from the booth host: `resolvectl query docker-station.nb.infra` and
`netbird status -d | grep -A4 docker-station`. Not found / not listed = the booth and the
collector host are not peers → Netbird policy. Resolves = `curl -X POST
http://docker-station.nb.infra:8090/ingest` must answer **401** (the collector's token check),
anything else is the collector.
3. **Collector side:** `docker logs wash-collector-collector-1 | grep -c /ingest` — zero means
nothing ever arrived; the container's health lines are its own probes.
4. After the fix, rows drain on **their own timers** (`1 min · 2^attempts`, cap 6 h); a restart
does not reset `next_attempt_at`. Expect a backlog to trickle in over hours, new rows at once.
+10 -1
View File
@@ -2,7 +2,7 @@
type: reference
tags: [parking, dev-environment, networking, wsl, troubleshooting]
sources: []
updated: 2026-06-15
updated: 2026-09-09
---
# WSL2 Dev Networking (for device testing)
@@ -110,6 +110,15 @@ trap:
Verified on hardware (2026-06-15): after the hook, `10.0.10.121` pings and the real [[lpr-camera]]
Hikvision driver pulls a snapshot with **no** source-forcing (`localAddress` becomes optional).
> **It bit again, 2026-09-09 — and the fix was pinned to the wrong NIC.** Configuring the
> [[k200l-printer]] meant adding `192.168.123.101` beside `10.0.10.203` on the mirrored LAN NIC;
> WSL then sourced 10.0.10.x traffic from the 192.168.123 address: `ping` fine, every HTTP
> connect timing out, `ip route get 10.0.10.7` showing `src 192.168.123.101`. `parking-net.service`
> was active but pins **`eth1`**, and the mirrored LAN NIC is **`eth0`** on this box now — so the
> boot fixer was a no-op. Run `deploy/wsl-fix-route-source.sh eth0` (and fix the unit's argument),
> or `curl --interface 10.0.10.203 …` as a one-off. Interface names are not stable across WSL
> reboots/NIC changes; the script accepts the NIC as an argument for exactly this reason.
## On the real appliance: multi-subnet is a deployment config, not a WSL hack
Production is a **dedicated hardened Linux appliance** ([[disk-os-hardening]]), so the WSL story
+22
View File
@@ -14,6 +14,8 @@ parking appliance. Written from the **first real provisioning, 2026-06-23** (har
actual hardware, including the firmware-specific workaround. Companion to [[disk-os-hardening]] (the
*why*), [[tpm]] (TPM analysis), [[container-deployment]] (the images), and
[[fleet-deployment-komodo]] (the deploy control plane this runbook's §7 uses).
**The devices plugged into the booth** (relay board, readers, cameras, radar, printers — factory
addresses, tools, hand steps, traps) have their own field runbook: [[site-device-installation]].
> ⚠ This box is the [[threat-model|outsider-with-the-box]] defence. The load-bearing anti-fraud
> control is still [[reconciliation]] over the [[append-only-event-chain|signed chain]] — disk
@@ -312,6 +314,12 @@ sudo loginctl enable-linger admin # so the user service starts at boot witho
**Verify:** `systemctl --user status periphery` → active; the server **`park-buzi`** appears and
goes **OK/green** in Core → Servers. Then **delete the onboarding key**.
> **After a reboot: `Unit periphery.service not loaded` (park-lab, 2026-09-09).** The unit
> existed but had never been **enabled**, so nothing started it at boot and `reset-failed` /
> `restart` had nothing to act on. Fix: `systemctl --user daemon-reload && systemctl --user enable
> --now periphery`. Add `enable --now` to the install sequence above whenever the installer's own
> enable did not stick (check with `systemctl --user is-enabled periphery` before leaving).
**➜ Next step is §7b below — the Stack itself is not deployed yet.** A green Server in Core just
means the agent connected; it runs nothing until you add the Registry/Git accounts and deploy.
@@ -350,6 +358,12 @@ docker exec -it -e ADMIN_USER=admin -e ADMIN_PASS='<strong-pw>' \
park-buzi-server-1 node scripts/seed-admin.mjs
```
The container is named `<stack>-server-1` (compose project = the Komodo stack name: `park-2-server-1`
on park-2; `docker ps` confirms). Leave `ADMIN_USER`/`ADMIN_PASS` off and the script prompts
(Enter = `admin`) — preferred on a shared shell, the password never enters history. Idempotent: an
existing username is left alone unless `FORCE=1` (§7e). After a `--users`/`--all` reset (§7d) run it
again — it recreates the built-in `admin` role row the reset removes.
> **Secrets-on-disk note.** The generated `.env` lands on the booth with **cleartext** secrets
> (compose needs real values). That's why the disk is LUKS-encrypted (§3–4) and keys are per-booth
> — the encryption is the control, and a single-booth compromise leaks only that booth's key. See
@@ -415,6 +429,14 @@ docker exec -it \
> it) **and** you type the DB filename to confirm (`parking.sqlite`; `--yes` skips that for scripted
> setup only). It is a **training/demo** tool — never run on a production booth's data.
> **Drift caught 2026-09-07:** the Car Wash module (six `carwash_*` tables) and `role_jobs` had
> landed without a category, so the guard refused every reset on a booth carrying them. Categorised
> now — orders + the review outbox under `--financial`, prices/categories/services/config under
> `--config`, `role_jobs` under `--users` — and verified `--all` on a freshly migrated DB. The script
> ships **inside the server image**, so a booth runs the fixed version only from the next deployed
> tag; until then `docker cp` the file from the repo into the container at
> `/app/node_modules/@parking/db/scripts/reset-db.mjs` and run the same command.
After `--users`/`--all` (users cleared), re-seed the first admin exactly as in §7b
(`docker exec … node scripts/seed-admin.mjs`) so someone can log back in. Since 2026-07-06 the seed
script **self-heals the built-in `admin` role row** that this reset also wipes — before that fix the
@@ -173,6 +173,13 @@ The CLI is still there for debugging, inside the running container:
- **Reviewing is the bottleneck**: the Training section shows labels per class against the
minimum and keeps Train disabled until two classes clear it.
**"Training — trainer not reachable: fetch failed" (2026-09-16).** Not a network problem: the
trainer answered `/health` but its `/readiness` crashed on the collector's DB (a volume from before
the `kind` column) and the stdlib server dropped the socket without a reply. Since the fix the
trainer answers **500 JSON with the error** and the collector shows that text; a genuine network
failure still reads "fetch failed" / ECONNREFUSED. See [[vision-review-outbox]] §Incident 2026-09-16.
## Packaging rule (same as the vision service)
Core deps are light (numpy, opencv-headless, onnxruntime): `inspect`, `evaluate`, the data and
+7
View File
@@ -121,6 +121,13 @@ prod); `ENV=dev` switches to the dev override.
internal); `/api/ws` upgrades pass through. `Caddyfile` binds `:80` so it matches ANY host — booth
IP, localhost, or `parksystems.msai.al` (pointed at the booth IP via hosts/DNS on-site). TLS later:
swap `:80` for the real hostname + uncomment Caddy `:443` → auto-HTTPS.
**Ports are stack-env variables since 2026-10-08**: `HTTP_PORT` (Caddy listen, default 80),
`SERVER_PORT` (host-net server + the advertised device push port, default 3000) and
`VISION_HOST_PORT` (vision's loopback publish, default 8089). The Caddyfile reads the first two
as `{$HTTP_PORT:80}` / `{$SERVER_PORT:3000}`, so a booth with nothing set is byte-for-byte the
old `:80 → :3000`. Introduced because the **lab stack moved onto `art-docker-station`**, a shared
host whose `:80` belongs to another service — the `park-lab` stack env sets 8080 / 3100 / 8189
([[fleet-deployment-komodo]]). Same-origin WS passes on any port (host header includes it).
- `WS_ALLOWED_ORIGINS` (env) must list any REMOTE origin admins use (same-origin always passes).
## Invariants (must hold)
+179
View File
@@ -0,0 +1,179 @@
---
type: decision
tags: [parking, decisions, devices, setup, discovery, cameras, printers, relay, readers]
sources: [dingtian-qr-linux-tool, ds-2cd1047g3h-liu]
updated: 2026-10-08
status: open
---
# Memo: discovery mechanisms for the devices we already know
**Ask (operator, 2026-10-08):** write down how we will give every known device class — relays,
printers, cameras, readers — a **Scan** in the setup wizard, the way the DT-008 reader got one
today. This memo is the plan: what exists, the method that worked, what each device can
actually answer on the wire (probed on the lab VLAN today where possible), the rules that carry
over, and the order to build in. Nothing here is built except the reader.
## 1. Why discovery is worth building (the park-2 lesson)
[[first-run-setup]] has the admin **type** what a device is — IP, serial, port. Nothing checked
that the typed picture matched the device. park-2 ran a month with two readers whose typed
config was perfect and whose *actual* output mode was Wiegand: every card "beeped" and none
reached the booth ([[site-device-installation]] §2 trap). Discovery is the reality check that
replaces typing with **what the device says about itself**, and — the part that matters more —
its companion **identity precondition**: *the serial/MAC you typed is the one the device at
that IP reports*. The same mechanism ends the Windows-tool-on-a-laptop site visits (SADP for
cameras, the Dingtian tools, printer utilities): one laptop-free wizard on the booth.
## 2. What already exists (don't rebuild)
- `DiscoverableDriver.discover() → DiscoveredDevice[]` in `@parking/devices` (`id`, `label`,
`config` to auto-fill, free-form `info`), the registry's `isDiscoverable()`, the catalog's
`discoverable` list, admin-only `GET /api/setup/discover/:driverId` (health-checks each hit),
and the wizard's **Scan** button + **Use** per row, rendering every `info` key
([[device-discovery]]).
- The write side that discovery feeds: `PreconditionDevice` (check → fixable/unfixable issues,
shown on **Test**, fixed on **Save**), `PushConfigurableDevice` (point the device at this
booth), `HardenableDevice`. The DT-008 driver is the worked example of all three together.
- Already a discovery in all but name: `GET /api/setup/usb-printers` lists `/dev/usb/lpN` with
the printer's self-reported make/model from sysfs `ieee1284_id` ([[printer-usb-transport]]).
## 3. The method that worked for the DT-008 (reuse it verbatim)
1. **Learn the protocol on the bench, never on a site.** Vendor tool + a lab unit; capture the
tool's own datagrams or read the vendor doc. Write it up as `raw/<device>/PROTOCOL.md`
(frame, ports, commands, field tables, *verification status per command*).
2. **TypeScript module + fake-device tests** (`drivers/<device>-config.ts`, `*.test.ts` with a
loopback fake that enforces the protocol's quirks — e.g. the DT-008's two-datagram writes).
3. **Driver hooks:** `discover()` (search → per-hit identity read → `config` + `info`),
`checkPreconditions()` (identity match + the one or two settings our flow depends on),
`fixPreconditions()` / `configureInputPush()` only for settings proven writable.
4. **Bench round trip with restore**: change → read back → change back → byte-diff the device's
config. Only then touch a site, and there only through the wizard.
5. Wiki: entity page, [[device-discovery]], [[first-run-setup]], the install runbook, log.
## 4. Per device: what answers on the wire
Status legend: **verified** = we saw it on the lab VLAN today (host `10.0.10.203`);
**documented** = vendor doc / wiki says so, not yet seen; **unknown** = needs a capture.
| device | mechanism | transport | returns | status |
| --- | --- | --- | --- | --- |
| DT-008 reader | vendor search cmd 2 | UDP bcast 24582 | serial, IP, server:port | **verified, built** |
| Hikvision cameras / DVR | **SADP** Probe | UDP mcast `239.255.255.250:37020`, XML | model, **serial**, **MAC**, IPv4, HTTP + command port, (activation state) | **verified**: 9 devices answered |
| Hikvision, Dahua, any IP camera | **ONVIF WS-Discovery** Probe | UDP mcast `239.255.255.250:3702`, SOAP | `XAddrs` (device-service URL), scopes: hardware model, name, sometimes MAC | **verified** on 4 Hikvision; the bench Dahua did **not** answer (see 4.2) |
| Dahua cameras | ConfigTool search ("DHIP") | UDP bcast 37810 | (per vendor tool: IP, MAC, serial, model) | **unknown** — my guessed frame got no reply; capture the ConfigTool like the DT-008 exe |
| Dingtian relay | search | UDP mcast `224.0.2.11:60000`, payload `05 AA` | "devices reply" ([[dingtian-relay]]) — reply content not recorded | **documented**; no relay on the lab VLAN to probe |
| Rongta / K200L LAN printers | no vendor discovery known to us | — | — | **unknown** (vendor utilities exist; protocol uncaptured) |
| any network ESC/POS printer | **TCP 9100 sweep** of the device subnet + web fingerprint | TCP connect ×254 in parallel, then HTTP GET | IP; model only via the board's web page | **verified**: 2 hits (`.220`, `.234`) in ~1 s — both *office* printers, neither ours → fingerprint is mandatory |
| USB printers | `/dev/usb/lpN` + `ieee1284_id` | sysfs | path, MFG/MDL | **built** |
### 4.1 Cameras — two protocols, run both, merge by MAC/serial
- **SADP** is the one that finds *everything Hikvision*, including units whose ONVIF is off
(5 of today's 9 answered SADP only) and **unactivated** units (factory `192.168.1.64`,
`<Activated>false</Activated>`) — i.e. the exact state a new G3H arrives in. Its ProbeMatch
carries `DeviceDescription` (model), `DeviceSN`, `MAC`, `IPv4Address`, `HttpPort`,
`CommandPort` (8000). Newer firmware (the DVR today) adds `<Encrypt>true</Encrypt><Salt>…`
for its *write* side; the inquiry itself stays plaintext. SADP can also **activate** a camera
and **set its IP** (password-protected) — the runbook's "activate with SADP or the browser"
step ([[site-device-installation]] §3) could become a wizard action later; discovery first.
- **WS-Discovery** is the vendor-neutral path and the only standard one Dahua offers. Scopes
give the model (`onvif://www.onvif.org/hardware/DS-2CD2T43G0-I5`) and `XAddrs` gives the
device-service URL — enough to pick the driver (`DS-…` → `hikvision`, Dahua names → `dahua`)
and the IP. **Caveat seen today:** the bench IPC-HFW2549T answered neither WS-Discovery nor
my 37810 guess; Dahua ships ONVIF switchable (web UI → Network → *Integration Protocol* /
ONVIF) — check that unit's setting before concluding anything. Record the outcome on
[[dahua-ipc-hfw2549t]].
- **Identity precondition for cameras:** on Use, store `serial` (SADP `DeviceSN` / ONVIF
scope) + `mac` next to `host`; on Test/Save compare with what the camera reports over its own
API (Hikvision `/ISAPI/System/deviceInfo` → `serialNumber`; Dahua
`magicBox.cgi?action=getSerialNo`). A swapped or re-addressed camera then fails loudly instead
of silently snapshotting the wrong lane. Further preconditions the same hook can own, all from
past incidents: clock drift ([[lpr-camera]] clock sync), ANPR push target = this booth
([[lpr-camera]] §Camera PUSH — Alarm Server), vehicle target filter on.
- Shape: keep the per-driver API; `hikvisionDriver.discover()` = SADP ∪ ONVIF filtered to
Hikvision hardware, `dahuaDriver.discover()` = ONVIF filtered ∪ (37810 once captured). Merge by
MAC, then serial; never by IP.
### 4.2 Dingtian relay — documented, unprobed
[[dingtian-relay]] records the vendor's search: multicast `224.0.2.11:60000`, payload `05 AA`,
devices reply; defaults IP `192.168.1.100`, UDP 60000 binary / 60001 string. Open before
building: (a) what the reply contains (MAC? firmware? — needed for identity; our relay config
has no serial today, identity is the IP alone); (b) whether a **hardened** board (relay_pw set,
string protocol disabled — [[dingtian-relay]] §hardening) still answers an unauthenticated
search — if not, discovery only finds *new* boards, which is still the useful case; (c) whether
the reply can come back on the host network from a multicast group (needs
`IP_ADD_MEMBERSHIP` on the device-VLAN interface, or the board may answer by unicast to the
sender — capture to know). Needs a board on the bench; one visit of the vendor tool with the
same capture method as the DT-008.
### 4.3 Printers — sweep + fingerprint, not a vendor protocol
Neither the Rongta board nor the K200L's "J-Speed" LAN module has a discovery protocol we know;
both vendors ship Windows utilities that surely broadcast something, uncaptured. The pragmatic
mechanism is already verified: **connect to TCP 9100 on every address of the device subnet in
parallel** (254 probes, ~1 s), then **fingerprint each hit over HTTP**: Rongta answers
`GET /prn_stat.htm` with its status page ([[rongta-printer]]); the K200L web configurator is a
three-frame page titled "Ethernet WebConfig" ([[k200l-printer]]); anything else is listed as
"unknown 9100 device" (today's two office printers would be). Identity: the K200L *Information*
frame shows its MAC; Rongta's pages carry none we know — fall back to the ARP entry after the
connect (`/proc/net/arp` on the host network). No ESC/POS serial exists over 9100, so the
precondition is weaker here: "a Rongta/K200L board still answers at this IP" plus the live
status page. Preconditions worth owning: USB path still present (already in the USB select),
network board reachable, paper/cover state ([[printer-status-monitoring]]).
### 4.4 DT-008 reader — built; two gaps
Discovery, identity (serial), output mode and push target are done. Still manual: giving a
factory `192.168.1.99` unit its site IP (cmd 32 `set-network` supports it — a "Set IP" action
in the discovery row would finish the laptop-free install), and prefixes / card format (cmds
12/14/44/8). Both are in `scripts/dingtian_qr.py` today ([[dingtian-qr-linux-tool]]).
## 5. Rules that carry over to every implementation
1. **Subnet-directed broadcast per interface**, never `255.255.255.255` (EACCES on some
hosts, and not what vendor tools send); **multicast needs `IP_MULTICAST_IF` per interface**
and, to *receive* group traffic, `IP_ADD_MEMBERSHIP` — SADP/ONVIF replied by unicast to the
sender today, so sending was enough; don't assume that for the relay.
2. **Replies arrive from arbitrary source ports** — match on content, not port; collect for a
window (~2 s), then stop.
3. **Dedupe and identify by a stable identity (serial, MAC) — never by IP**; the IP is the thing
most likely to be wrong.
4. **Discovery is read-only.** "Use" fills the form; writes happen only on Save, through
preconditions/push-config, each proven on the bench with a restore. Discovery must never be
periodic/background: it is an admin action in Setup, so the booth operator (our adversary,
[[threat-model]]) has no new lever.
5. **L2 only.** Works from the booth (host-network server) and the device VLAN; impossible
from a bridged dev container and across Netbird — say so in the empty-result message
(the wizard's "no devices found" text already does).
6. **Replies are untrusted input** from an unauthenticated network: cap sizes, parse XML
without entity expansion, never pass a reply string into a shell/URL unescaped, never
forward credentials to a discovered address without the identity check.
7. **Serials and MACs are site data** — they go in the device row, not in commits/wiki with
booth names ([[fleet-deployment-komodo]] pseudonymity rule).
## 6. Order of work
1. **Cameras — SADP + WS-Discovery** (protocols verified today; no bench captures needed;
biggest field pain = activation/IP of new units; two vendors covered). Half a day plus the
identity precondition.
2. **Printers — 9100 sweep + fingerprint** (verified mechanism, small code, replaces guessing
the printer's IP at park-buzi-type installs).
3. **Dingtian relay search** — when a board is on the bench; capture the reply first.
4. **Dahua 37810** — capture the ConfigTool; until then Dahua relies on ONVIF being enabled.
5. **DT-008 "Set IP" from the discovery row** (set-network is proven).
## 7. Open questions
- Does a hardened Dingtian board answer the `05 AA` search? What is in the reply?
- Is ONVIF off on the bench Dahua, or did the probe not reach it? (web UI check, then re-probe)
- SADP `Encrypt/Salt` on newer firmware: inquiry stays plaintext — confirm on a 2026 unit.
- Rongta board MAC/identity: any page or ESC/POS query that returns a stable id?
- Should the camera row offer **activate + set IP** (SADP write side), or stay read-only and
leave activation to the browser? (Leaning read-only first; writes only after a bench round trip.)
Related: [[device-discovery]] · [[device-registry]] · [[first-run-setup]] ·
[[site-device-installation]] · [[dingtian-dt008-reader]] · [[dingtian-relay]] · [[lpr-camera]] ·
[[dahua-ipc-hfw2549t]] · [[rongta-printer]] · [[k200l-printer]] · [[dingtian-qr-linux-tool]]
+18 -1
View File
@@ -72,6 +72,12 @@ Three git branches map to three image tags and three booth roles:
CI (`build-images.yml`, which now triggers on `dev`/`stage`/`main`) builds `:stage` + `:stage-<sha>`;
then **bump `TAG=stage-<sha>`** in `komodo/resources.toml` and deploy from Core. `main` only ever
receives what survived staging.
- ⚠️ **`<sha>` is the sha of the push HEAD, not of the code commit.** CI runs once per push and tags
with `GITHUB_SHA`. If the code commit and the `bump(resources)` commit go up in the *same* push,
the image is `stage-<bump sha>` and the pin (`stage-<code sha>`) points at nothing — Komodo fails
with `failed to resolve reference … not found` (2026-10-08, `stage-1167e27`). Either push the code
commit first and bump after the build lands, or pin to whatever sha is the push head. A
komodo-only push does not trigger a build, so a pin-fix commit pushed alone is safe.
- **`stage` was branched from `dev`** (2026-06-29) so the first real-world test carries the full current
app, not a `main` that predates this work. `park-buzi`'s Stack `branch` + `TAG` both point at `stage`.
- **DB migrations run at boot** (`migrate-runtime.mjs`), so a promotion auto-migrates the staging booth's
@@ -193,12 +199,23 @@ publish.
## park-lab — the lab bench joins the fleet (2026-07-07)
> **2026-10-08 — park-lab now runs on `art-docker-station`** (`server = "art-docker-station"`,
> the same Periphery that hosts `wash-collector`), so the app can be exercised without the lab
> box. That host's `:80` is taken, so the stack env sets **`HTTP_PORT=8080`, `SERVER_PORT=3100`,
> `VISION_HOST_PORT=8189`** — three new variables honoured by `docker-compose.prod.yml` and the
> Caddyfile ([[container-deployment]] §proxy); booths leave them unset. The UI is
> `http://<station>:8080/`. Caveats of a shared host: the server still runs on the HOST network
> (it sees the station's LAN, not a device VLAN — device I/O is not testable there, only the app),
> the `parking-data` volume is per-stack (`park-lab_parking-data`), and the USB-printer
> `/dev/usb` bind still applies: if the station has no `/dev/usb`, Docker creates it as an empty
> directory on first start (harmless — the printer simply probes "offline").
Second `[[stack]]` in `komodo/resources.toml`: **`park-lab`** (server = the lab box's Periphery
`connect_as`), the first non-booth member and the proof of the tier model in practice:
| Stack | compose branch | image tag | secrets |
| --- | --- | --- | --- |
| park-lab | `dev` | **moving `dev`** (a lab may float) | `park_lab_*` |
| park-lab | `dev` → **`stage` (2026-09-09)** | ~~moving `dev`~~ → **pinned to the booth's `stage-<sha>` under reproduction** (2026-09-09: the lab re-joined the fleet to reproduce the park-buzi printer cover-open bug, so it must run the booth's exact image; review outbox under its **own** id `booth-lab` since 2026-09-16 — never a booth's, so bench crops stay separable per booth on the collector) | `park_lab_*` |
| park-buzi | `stage` | pinned `stage-<sha>` | `park_buzi_*` |
The three knobs are independent per stack — the ResourceSync's own branch only governs where the
+111
View File
@@ -0,0 +1,111 @@
---
type: decision
tags: [parking, decisions, exit, barrier, threat-model, shift, z-report, permissions]
sources: []
updated: 2026-10-08
status: built 2026-10-08
---
# Forgiven exit — the owner opens the EXIT barrier with no payment
> **Built 2026-10-08** (same day as decided). As-built notes at the end of this page; the
> decisions below are what shipped.
**The ask (user, 2026-10-08).** The owner/admin sometimes needs to let a car out regardless:
a transient that took a ticket but will not be charged, or a car with no session at all (it
came in while the barriers were up). The open must produce **no money** and must be **flagged**
in the live feed. First floated for both directions; **narrowed the same day to the EXIT
barrier only** — the entry keeps its existing paths ([[operator-issued-entry]] when the button
is broken, barriers physically up otherwise).
## Why it is safe to give the operator this at all
This is the exact move the [[threat-model]] worries about (pocket the fee, "lose" the ticket,
let the car out). As with [[operator-issued-entry]], the defence is not to withhold the
capability but to make every use **signed, attributed, photographed and impossible to hide**:
it lands on a named operator's shift, with the fee it forgave, where the owner reads it.
## Decisions
1. **Exit only.** Reuses the human-intervention re-open path in `exit-flow.ts`
(`reopenBarrier`: anomaly signed FIRST, then the human-intervention `vehicle_exit`, exit
snapshot, `pulseOpen`). Today that path refuses an unpaid or grace-expired transient; the
feature is a **second authorization branch** on it, behind a dedicated permission.
2. **Accounting: a signed ZERO-amount payment that carries the forgone fee.** The Z-report
([[shift]]) sums `amountMinor` by tender, so a zero payment adds nothing to cash, card or the
drawer — the shift total is untouched by construction. The fee the car owed is recorded in
its **own field** (`forgoneMinor`, with a reason code), reported as its **own line**
("forgone exits: N, amount X"), and is NOT the merchant-validation `discountMinor` — the
owner must be able to tell "the bar validated it" from "the operator let it out".
Signing the payment also **closes the ticket**, so it cannot be reused ([[plate-reconciliation]]
ticket-swap).
3. **No session (car has no ticket, e.g. came in with the barriers up):** signed anomaly with
the exit snapshot and the plate read, then the pulse. Nothing to forgive, nothing to close.
4. **Permission:** a new one, **admin only by default**; the owner decides whether operators get
it. Requires an **open shift** (same `requireShift` as the pay routes) so every use is on
someone's report.
5. **Reason text is OPTIONAL** (user, 2026-10-09 — reversed from "mandatory" the day before:
"We don't need to force the user to write a reason"). The accountability is the
signature, the operator name, the snapshot and the Z-report line; an empty note is signed
as "(no reason given)" so the English sentence stays readable.
6. **Print nothing.** No receipt, no slip — there is no payment to receipt (user, 2026-10-08).
7. **Visibility:** warn-level log line, anomaly in the live feed with the snapshot, the Z-report
line. **No cap, no blocking** — blocking the owner at the gate recreates the "lot stuck"
problem; the defence is reporting.
8. **Safety unchanged:** `pulseOpen` only, never a timed close ([[fail-state-safety]]).
## Not decided / out of scope
- Entry-side free open: **rejected** for now (the entry has its own paths).
- Whether a forgiven exit should also void an attached car-wash charge line: open; today the
zero payment would carry no charge lines at all.
## Build sketch (when asked)
`exit-flow.reopenBarrier(identity, operator, { forgive: { reason } })` → quote the fee as the
pay flow would (PayStation quote), sign `payment { amountMinor: 0, forgoneMinor, reason }`,
then the existing re-open body. Route `POST /api/barrier/forgive` with the new permission +
`requireShift`. Z-report: `forgoneTotalMinor` + `forgoneCount` (old reports → 0), one print
line. Web: a guarded button in the pay/exit modal, reason field optional. Reason codes:
`exit.forgiven`, `exit.forgiven.noSession`. Tests on the no-money invariant (cash/card/drawer
unchanged) and on the ticket being closed.
## As built (2026-10-08)
- **Permission `barrier:create`** (new resource `barrier` in the code-defined grid,
`packages/shared`). Admin has it by the all-permissions invariant; the owner grants it to any
role from Setup → Roles — "the owner can give permission to other operators" (user).
- **`PayStation.forgive(identity, { operator, note })`** — quotes the fee as the pay flow
would, signs `payment { amountMinor: 0, forgoneMinor: <quote>, operator, reasonCode:
"exit.forgiven", reason: "manual exit by X — fee of N CUR, no payment: <note>" }` with **no
tender** (nothing was tendered), marks the projection paid. Refuses (409) when the quote
carries module charge lines (a wash on the ticket): parking is forgiven, a wash is not.
- **`ExitFlow.reopenBarrier(id, operator, { forgiven })`** — the existing human-intervention
re-open with the walk-back check bypassed for a forgiven call (a 0-minute grace tariff must
not refuse it); the anomaly and the `vehicle_exit` carry `exit.forgiven` + `forgiven: true`
+ `forgoneMinor`. **`ExitFlow.forgiveExitNoSession(operator, note)`** — anomaly under a fresh
`forgiven:<uuid>` identity (so its exit snapshot shows in the feed) + pulse; no payment, no
exit event. Relay driving shared in `#pulseExit` (signed first; a failed pulse is
`ok:true, opened:false` + "open by hand").
- **Route `POST /api/barrier/forgive { identity?, note? }`** — `barrier:create` + the open-shift
gate (`409 no_shift`); the note is optional; no identity = the no-session path.
- **Z-report**: `forgoneTotalMinor` + `forgoneCount` summed from `forgoneMinor` (never into
cash/card; `discountTotalMinor` untouched), on the signed `shift_z_report` only when > 0, one
print line `Dalje manuale (N): X`, shown in the X-report, the close confirm and history.
- **Web**: in the pay/exit modal a red ghost "Forgive & open" for an OPEN transient that owes
money (unpaid or overstay) → reason box → "Confirm — open exit, no payment"; on the booth
header the **exit lane light itself is the control** for the no-ticket case (user,
2026-10-09: "only Hyrje and Dalje Manuale") — same chrome as the entry light, still showing
the lane state, labelled "Dalje manuale" and clickable → a small styled dialog (optional
reason, red confirm). For anyone without `barrier:create` + own open shift it is the plain
"Dalje" light. The modal button likewise only renders with the permission + shift.
Live-feed reason texts in en/sq. **Nothing is printed.**
- Tests: exit-flow (ticketed + no-session), pay-station (`forgive`), shift-service (totals
untouched, own line, history), routes (403 without the permission, 409 no shift, 400 no
note accepted, ledger sequence entry→payment→anomaly→exit, report figures).
**Wording (user, 2026-10-09).** The user-facing words are **"manual exit" / "dalje manuale"**,
not forgive/forgiven/forgone — too much "fal, falur, falje" (user). Applies to both language
files, the printed Z-report line (`Dalje manuale (N)`) and the signed English fallback
sentences. Internal names stay (`exit.forgiven`, `forgoneMinor`, `barrier:create`) — they
are code identifiers, not copy.
+31 -1
View File
@@ -2,7 +2,7 @@
type: decision
tags: [parking, decisions, open]
sources: [parking-system-architecture]
updated: 2026-09-04
updated: 2026-10-08
status: open
---
@@ -148,3 +148,33 @@ procurement. (See [[parking-system-architecture]] §10.)
already carried `subscription:*` (stale note); roles now remember the jobs they follow and
a grown job is re-applied with one click, never silently; every role edit is signed as a
`config_change`. **Settled** — details on [[venue-modules]] §"Permissions matrix" Status.
17. **Party ledger — receivables & payables across modules.** _(Raised by the user, 2026-09-08.)_
Postpaid [[subscription]]s, hotel guest-nights billed to the hotel, Car Wash fleet deals on
account, and supplier/utility bills all need "who owes whom". Designed as a **counterparty
sub-ledger** — parties + signed `charge` / settlement / `write_off` events, balance derived,
aging + statements, CSV for the accountant — see [[party-ledger]] (design only, not built).
Interacts with #9 (a statement is **not** a fiscal invoice; fiscalisation is off-appliance)
and #8 (one currency per party until FX exists). Also reopened on the subscription page: a
**renewal is currently off-book** (an edit, no `payment`).
18. **DT-008 — why two units read disjoint card sets, and `6H` on a 13.56 MHz UID.** _(Raised on
the bench, 2026-09-17.)_ park-buzi's readers (`H05M…`) read the site's 125 kHz cards; the fresh
lab unit (`HC002721`) reads only 13.56 MHz cards, although the box leaflet claims EM-ID + M1 +
14443A/B + 15693 in one unit. Unresolved between a batch variant, a dead/disabled 125 kHz front
end, and a non-EM 125 kHz card format at park-buzi. To settle: (a) a known EM4100 fob on the lab
unit (reads → card format; not → unit/variant, vendor with the serial); (b) the site record
names the card technology and a replacement is tested against real cards before shipping;
(c) on a 13.56 MHz read the native UID is 4 or 7 bytes, so
**`Card Input format = 6H` truncates it** — a phone tap showed it keeps the first three bytes in
reversed order and drops the fourth; confirm on a card with a printed UID, and decide whether
`8H` is required for 13.56 MHz sites before any card is enrolled against one. (Phones present a
random `08…` UID per tap and can never be credentials.) See
[[dingtian-dt008-reader]] §"Two RF variants".
19. **Discovery for every known device class.** _(Raised by the user, 2026-10-08, after the
park-2 readers turned out to be in Wiegand mode for a month.)_ The wizard's Scan exists
generically and the DT-008 implements it; cameras (SADP + ONVIF, both verified on the lab
VLAN), network printers (9100 sweep + fingerprint), the Dingtian relay (multicast search,
reply unknown) and Dahua (37810, uncaptured) do not. Plan, rules and order of work:
[[device-discovery-roadmap]]. Settles when cameras and printers scan from the wizard and the
relay's search reply has been captured on the bench.
+149
View File
@@ -0,0 +1,149 @@
---
type: decision
tags: [parking, decisions, open, finance, ledger, modules, subscriptions, carwash]
sources: []
updated: 2026-09-08
status: open
---
# Party ledger — who owes the site, and whom the site owes
**Design only (2026-09-08). Nothing built.** Captured from a design conversation with the user; to be
refined before any code. The trigger was the [[subscription]] billing redesign: as soon as a
subscription can be **postpaid**, the site is *collecting a debt*, and the user immediately listed
three more debtors/creditors that need the same treatment. So this is not a subscription feature
— it is a **counterparty sub-ledger** that subscriptions, hotels, fleets and suppliers all sit on.
## The problem stated
The user's constraints, verbatim in spirit:
1. **Postpaid subscriptions** — the subscriber pays at the start or end of a month; the site must
see what is unpaid.
2. **Hotels** — occasional daily access for a hotel's guests, billed to the hotel, not the guest.
3. **Car Wash fleet deals** — the wash cleans a company's cars; payment is due per period; the
*site* collects the debt.
4. **Car Wash suppliers and utility bills** — the wash needs to see what it has paid and still owes
its suppliers (detergent, water, electricity).
5. **The admin needs one view of uncollected dues: who owes what to the park.**
Today none of this is modelled. Money exists in exactly two shapes: a signed `payment` at a till
([[shift]], [[append-only-event-chain]]) and a drawer voucher (`cash_in` / `cash_out`). Neither
names a *counterparty*, so "who owes whom" cannot be asked. The earlier
[[validation-sponsorship]] page sketched a `sponsors` table with a stored `balance_minor` for the
postpaid-merchant case; this page **supersedes that sketch** with something general.
## The decision (proposed)
Add **one core concept, once**: a **party** with an **account**, and three signed ledger event
types that move that account. Modules (Parking, Car Wash, later Bar — [[venue-modules]]) append
charges against parties; the core owns the party master data, the balance derivation, the
statement and the aging report. No module keeps its own receivable.
### Party (core master data, module-agnostic)
A party is any legal or natural person the site has money dealings with — a subscriber, a hotel, a
fleet company, a utility, a supplier. Mutable master data (like `subscriptions`), soft-deletable
([[soft-delete]]):
```
parties id, name, contact, taxId?, currency, kind {customer|supplier|both},
creditLimitMinor?, terms {dueDays | calendarDay}, active, deletedAt…
```
A subscriber gets a party row (created with the subscription, or linked to an existing one — a
company with five subscriptions is one party). `creditLimitMinor` lets a desk **refuse on-account
sales** when the party is over its limit; `terms` gives the default due date of a charge.
### Three signed event types (the account never stores a balance)
| Event | Meaning | Payload (signed) | Who appends |
| --- | --- | --- | --- |
| `charge` | an **accrual** — the party now owes (or is owed) | `partyId, direction {receivable\|payable}, amountMinor, currency, source {module, ref}, periodFrom?, periodTo?, dueAt, operator` | a module (subscription period, guest-night, on-account wash, supplier bill) |
| `settlement` | **money moved** against the account | as a **`payment`** at a till (`partyId` + `chargeIds[]` added) for cash/card received; a **`cash_out`** voucher with `partyId` for cash paid out; a `settlement` with `tender: "bank"` and no till for transfers either way | operator at a till / admin for bank |
| `write_off` | admin-signed **reduction with a reason** (waived period, disputed night, goodwill) | `partyId, chargeId, amountMinor, reason, operator` | admin only |
**Balance** per party and currency = Σ charges − Σ settlements − Σ write-offs, derived on read
(cached at most), never stored. **Why signed events and not a mutable `balance` column:** the
[[threat-model]] adversary is the booth/wash operator. A receivable that lives in a mutable row can
be quietly shrunk; a receivable that is a chain of signed events cannot — a statement is
re-derivable and **disputable against the chain**, the same guarantee the shift Z-report gives.
The one fraud-relevant path is the write-off, which is why it is admin-gated and permanent.
Reusing `payment` for money received (rather than inventing a parallel type) keeps the drawer,
the Z-report and the per-till folds ([[shift]] §Tills) working with **zero new summing surface** —
the same reasoning that made a subscription sale a `payment` with a `subscriptionSale` flag
([[subscription]] §Collecting the fee).
### How the four cases land on it
- **Subscriptions** — the billing-period design ([[subscription]] §Recurring billing) stays exactly
as drawn, except a billing period *is* a `charge` against the subscriber's party. Prepaid vs
postpaid is only the due-date rule. Paying a period = a till `payment` referencing the charge.
- **Hotels** — a subscription-like agreement whose **payer is the hotel party**, postpaid, whose
credential is issued per guest for N nights (the existing `"day"` plan). Each guest-night is a
charge line; the hotel receives a monthly **statement of nights**. The guest never pays.
- **Fleet washes** — the wash order gains a **third `payAt` beside `booth` and `bay`: `account`**.
The order is a charge against the fleet party; the wash till's Z-report shows on-account sales
as a separate line, *not* cash. Over the credit limit → the wash desk cannot pick `account`.
- **Suppliers and utilities** — a bill is a **payable** charge against that party (the wash's
detergent supplier, the electricity company). Paying it from the wash till is a `cash_out`
voucher that references the bill (the drawer already folds it); paying by bank is a bank
settlement. The owner sees what is owed, what was paid, and **from which till**.
### The admin view
One report over all parties: name, balance, oldest unpaid charge, **aging buckets** (current,
30, 60, 90+ days), drill-down to a **statement** for a period (every charge, settlement and
write-off, each linked to its signed event). "Uncollected dues" is a filter on it: receivables
with a balance. Payables are the same report with the direction flipped. Everything is a
projection over the ledger, like [[reporting-analytics]].
### Permissions
New core permissions, in the [[venue-modules]] matrix: `finance:read` (statements, aging),
`finance:settle` (record a bank settlement; till settlements ride the existing pay permissions),
`finance:writeoff` (admin), `party:manage` (master data). The wash desk sees only *whether* a
party is on-account-eligible, never the balance.
## Where the line is drawn
This is a **sub-ledger of receivables and payables, not bookkeeping.** No chart of accounts, no
profit-and-loss, no VAT computation, no double-entry general ledger. The accountant gets a **CSV
export** of charges and settlements per party and period. Two flags before anything is built:
- **A statement is not a fiscal invoice.** Fiscal receipts/invoices are already
[[open-questions]] #9 (tax number, sequential numbering, and — in Albania — fiscalisation).
The appliance is [[offline-first]]; fiscal invoicing needs the cloud side
([[cloud-service-saas]]) or an external fiscal device. Statements must be **labelled as
statements** so nobody mistakes them for invoices.
- **Parties are per appliance.** A fleet washing at two sites has two accounts until the
PostgreSQL sync target exists. Consolidation is a cloud-side concern.
Also deliberately **not** built: automatic card charging, dunning sequences, automatic
suspension without a grace period. The operator never types a price ([[subscription]] rule).
## Build order (each step usable on its own)
1. `parties` + the three event types + the balance/aging/statement report and CSV export.
2. Subscription billing periods on top ([[subscription]] §Recurring billing) — the renewal
off-book hole closes here.
3. `payAt: "account"` on Car Wash orders, with the credit-limit gate and the Z-report line.
4. Bills and payables (supplier / utility register; `cash_out` with a bill reference).
## Open
- Does a **guest-night** charge get appended at credential issue (N nights known up front) or per
actual entry? Issue-time matches the hotel's booking; per-entry matches reality. Lean issue-time,
with a void path if the guest never came.
- **Currency**: parties carry one currency; a charge in another is refused until the FX question
([[open-questions]] #8) is settled.
- **Who may create a party** at the wash desk vs. admin only (a fleet deal is a contract, not a
walk-in).
- Should utility bills live in this app at all, or only supplier bills paid from a till? The user
asked for both; the register is cheap, the temptation to grow it into bookkeeping is the risk.
- **Reminders to the party** (statement by email/SMS) are off-appliance — same answer as the
subscription expiry notice: the operator/owner is notified, the contact is theirs to make.
Related: [[subscription]] · [[validation-sponsorship]] (superseded sketch) · [[venue-modules]] ·
[[shift]] · [[append-only-event-chain]] · [[threat-model]] · [[reporting-analytics]]
+143
View File
@@ -0,0 +1,143 @@
---
type: entity
tags: [parking, hardware, camera, dahua, snapshot, events, bench]
sources: []
updated: 2026-09-17
---
# Dahua IPC-HFW2549T-AS-IL — the lab bench unit (inspected 2026-09-17)
A 5 MP Dahua WizSense bullet (`IPC-HFW2549T-AS-IL-0360B`, 3.6 mm, "IL" = smart dual illuminators),
firmware **`V2.880.0000000.22.R`, build 2026-05-14**, serial `9J0E4EFPAGECB23`, MAC
`fc:5f:49:48:42:ac`, processor SSC378Q. Sits on the bench at `10.0.10.11`, login `admin` / the lab
password. **It is not an ANPR camera** — plates come from the host-side [[opencv-anpr-service]]
off its snapshot, exactly as with the Hikvision units. Everything below was read off the unit
over its CGI with `curl --digest`; nothing was written to it.
**It is not factory-fresh.** Hostname `DAHUA_PORTA_KRYESORE` ("main gate"), an Alarm Server already
pointed at `10.7.8.9:8888`, DNS `8.8.8.8`, SMD tuned to vehicles only — this unit was configured
for a gate somewhere before it reached the bench. Treat its settings as inherited, not defaults.
## What the CGI surface gives us
| Need | Endpoint (all HTTP Digest, port 80; 443 is **off**) | Result on this unit |
| --- | --- | --- |
| identity | `magicBox.cgi?action=getSystemInfo` / `getSoftwareVersion` / `getSerialNo` / `getVendor` | model, firmware, serial, `vendor=Dahua` |
| snapshot | `snapshot.cgi?channel=1` | 200, `image/jpeg`, **2880×1620**, ~270 KB, ~0.5 s |
| snapshot channel `0` / `2` | same | **400** — the channel index is **1-based**; `subtype=1` is ignored (still 2880×1620) |
| clock read | `global.cgi?action=getCurrentTime` | `result=2026-09-17 09:03:50` |
| clock write | `global.cgi?action=setCurrentTime&time=YYYY-MM-DD%20HH:MM:SS` | 200 `OK`; read-back matches within 1 s (**verified**, now the Dahua clock-sync) |
| events | `eventManager.cgi?action=attach&codes=[All]&heartbeat=5` | 200, `multipart/x-mixed-replace`, a `Heartbeat` part every N s, event parts in between |
| event caps | `eventManager.cgi?action=getCaps` | snapshot/record/mail/alarm-out linkage; no HTTP push cap |
| streams | RTSP 554 `cam/realmonitor?channel=1&subtype=0` / `1` | **H.265** Main 2880×1620 @ 20 fps; sub 704×576 @ 20 fps (probed with ffprobe) |
| ports | 80 (HTTP), 554 (RTSP), 37777 (Dahua SDK/DHIP) open; 443, 37778, 5000, 8000 closed | |
### Snapshot: the driver decremented the channel — this unit said no (fixed 2026-09-17)
`dahuaDriver` (`packages/devices/src/drivers/camera.ts`) builds
`/cgi-bin/snapshot.cgi?channel=${ch-1}` on the note "Dahua channels are 0-based". On this firmware
`channel=0` → **HTTP 400**, `channel=1` → the JPEG. Dahua's HTTP API numbers `snapshot.cgi` and
`realmonitor` channels from 1 (only the `configManager` *tables* are 0-indexed — the usual source
of the confusion). So an admin who enters "channel 1" in the wizard gets a permanent **degraded
"HTTP 400"** from `healthCheck()` and no snapshot ever. The Dahua driver was never run against
hardware before today ([[lpr-camera]] §Verified only covers Hikvision). **Fixed the same day**: the
driver now sends the channel as entered (clamped to ≥1) and `camera.test.ts` pins the URL. The
fixed driver was then run against this unit: `healthCheck` → ready (≈256 KB), `captureSnapshot` →
`image/jpeg`, 273 KB, JPEG magic.
The snapshot always comes off the **main** stream at full resolution — there is no per-stream
snapshot as on Hikvision, and `subtype` on `snapshot.cgi` is ignored. Fine for us: the app
re-encodes to 1280 px on capture ([[snapshot-storage-optimization]]) and the recognizer keeps the
full frame.
### Events: Dahua PULLS-with-a-held-socket, it does not HTTP-POST
Dahua has an "Alarm Server" too (`configManager.cgi?action=getConfig&name=AlarmServer`), but its
protocol is **`DAHUA`** (proprietary, port 8888) — not the Hikvision-style HTTP POST that
`routes/hikvision-alarm.ts` consumes. The HTTP way to get events is the **subscription stream**:
the host opens `eventManager.cgi?action=attach&codes=[SmartMotionVehicle,CrossLineDetection,…]&heartbeat=5`
and keeps it open; the camera writes one multipart part per event (`Code=…;action=Start|Stop;index=…`)
and a `Heartbeat` part every 5 s. Verified on the bench: the stream stays up, heartbeats arrive,
Digest auth applies to the attach. This inverts the Hikvision model:
- the camera never needs to know the booth's address — no `pushesToBackend`, no "assign first,
then go back to the camera" step, no source-IP guard, and the WSL mirrored-mode source-IP
problem does not exist;
- the **server** owns the connection: reconnect with backoff, treat a missing heartbeat as
camera-offline, one long-lived socket per Dahua camera;
- vehicle events come from **SMD** (`SmartMotionDetect`: `Enable=true`, `ObjectTypes.Vehicle=true`,
`Human=false` on this unit — inherited, and exactly the "Detection Target = Vehicle" the Hikvision
runbook step asks for) → code `SmartMotionVehicle`; tripwire/intrusion (`CrossLineDetection`,
`CrossRegionDetection`) with `ObjectTypes=Vehicle` are the IVS equivalents, **none configured**
on this unit (only disabled FaceDetection and HeatMap rules exist).
**Verbatim event parts captured** on a 25-minute `codes=[All]` listen (bench motion + the clock
write below). Each part is `Content-Type: text/plain` with a `Code=…;action=…;index=…;data={JSON}`
body:
```
Code=VideoMotion;action=Start;index=0;data={
"EventID" : 31927,
"Id" : [ 0 ],
"RealUTC" : 1789634136,
"RegionName" : [ "Region1" ],
"SmartMotionEnable" : true,
"WithSnap" : true
}
Code=VideoMotion;action=Stop;index=0;data={ …same EventID… }
Code=VideoMotionInfo;action=State;index=0;data={ "RealUTC" : 1789634137, "WithSnap" : false }
Code=TimeChange;action=Pulse;index=0;data={
"BeforeModifyTime" : "17-09-2026 09:35:51",
"ModifiedTime" : "17-09-2026 10:35:49",
"RealUTC" : 1789637749,
"WithSnap" : false
}
```
- `action=Start` / `Stop` with a shared `EventID` is the busy/free edge (the Hikvision
`active`/`inactive` equivalent); `VideoMotionInfo State` is a per-second chatter part to ignore.
- The motion arrived as plain `VideoMotion` with `SmartMotionEnable: true`, **not** as
`SmartMotionVehicle` — whether the SMD filter suppresses `VideoMotion` for non-vehicles, or only
adds the `SmartMotion*` codes on top, is **unconfirmed** (nobody drove a car past the bench).
Subscribe to both and log which fires before gating anything on it.
- **`RealUTC` is the camera's *belief* of UTC, i.e. its wall time minus its configured offset.**
After the clock write it read 09:35:49 for a real 08:35:49 UTC (UTC+1, DST off). Never use it
as an absolute time — stamp events on receipt from the booth clock, as the Hikvision route does.
- `TimeChange` is emitted for our own clock sync; harmless, but filter it from any "activity" view.
### Clock: one hour behind, NTP off — clock-sync built the same day
`getCurrentTime` returned 09:03 while the bench wall clock read 10:03 CEST: `NTP.Enable=false`
(address `time.windows.com`, unreachable on an isolated VLAN anyway), `NTP.TimeZone=1` (Belgrade)
and **`Locales.DSTEnable=false`**, so the unit runs at UTC+1 year-round. The Hikvision units get
their clock from the booth at every offline→ready edge ([[clock-integrity]]); until today the
Dahua driver did not claim `isClockSyncable`. Now `DahuaCamera.syncClock` (camera.ts) reads
`global.cgi?action=getCurrentTime` (`result=YYYY-MM-DD HH:MM:SS`) and, past the drift limit, writes
`setCurrentTime&time=<host wall time>` — the **host's naive local wall time, no offset**, because
what has to match the booth is the OSD burned into every snapshot, not the camera's notion of UTC
(its tz/DST config is left alone, as on Hikvision). Verified on the bench with the real driver:
a 2 h-off host time set (drift 7200 → synced), set back, then read as 1 s drift → no write. The
device monitor picks it up unchanged (it gates on `isClockSyncable`, not on the driver id). A wrong
DST setting on the camera therefore no longer matters for the evidence trail — only `RealUTC` in
event bodies stays skewed (above).
### Login lockout — the device monitor must never poll with a wrong password
`General.LockLoginEnable=true`, `LockLoginTimes=5`, `LoginFailLockTime=300`: five bad Digest
logins lock `admin` out for 5 minutes. A wizard assignment with a mistyped password, polled every
few seconds by the device monitor, locks the camera and then **every** login (including the
browser) fails until the poll stops. Verify the password with one `curl` before assigning; on a
mysterious "401 then nothing works" wait five minutes.
## Bench notes
- `10.0.10.11` is the runbook's address for the lab [[k200l-printer]] ([[site-device-installation]]
§address plan) — the camera has taken it on the bench; keep the two off the wire together or
move one.
- The other HTTP APIs newer Dahua firmware carries (`RPC2` JSON, `/onvif/device_service`) were not
exercised — the CGI above covers everything the app needs.
- `devVideoInput.cgi?action=getCaps` and `magicBox.cgi?action=getProductDefinition` answer
"Bad Request" / "Not Implemented" on this firmware.
Related: [[lpr-camera]] · [[opencv-anpr-service]] · [[lane-presence-and-anpr-entry]] ·
[[clock-integrity]] · [[site-device-installation]] · [[device-registry]]
+103 -5
View File
@@ -1,8 +1,8 @@
---
type: entity
tags: [parking, hardware, readers, qr, dingtian]
sources: [dingtian-dt008]
updated: 2026-07-04
sources: [dingtian-dt008, dingtian-qr-linux-tool]
updated: 2026-10-08
status: open
---
@@ -21,12 +21,33 @@ or RFID [[subscription]]** credentials. Product page: dingtian-tech.com/en_us/qr
> (migration 0015 rewrites existing rows). All *protocol/behaviour* facts below were observed on the
> real hardware and remain correct — only the device identity was wrong.
## Configuring it from Linux (2026-10-08)
The Windows exe's Search / Get parameter / Set are a small binary **UDP protocol** (reader ports
24680 unicast, 24582 broadcast), reversed in [[dingtian-qr-linux-tool]]; **`scripts/dingtian_qr.py`**
reimplements it. `get <ip>` returns every setting (output type, server/port/language, card input
format, prefixes, Wiegand pulses, buzzer, fill light…), `set <ip> --field value` writes one, and
both are unicast — so they run **on the booth over SSH**, no site visit. The output-type write was
proven on the bench unit (struct diff = the one byte). Not in the protocol: symbologies, DHCP
(the exe never sends it either). First use: park-2's readers read back as **`WG26`** — the
"beeps but never pushes" case ([[site-device-installation]] §2 trap).
**In the app (same day):** the driver now speaks this protocol itself
(`packages/devices/src/drivers/dingtian-qr-config.ts`, Node `dgram`, runs in the host-network
server container). The [[first-run-setup|wizard]] **Scan** button lists readers with their mode
and current target ([[device-discovery]]); **Test** reports *not in HTTP mode* / *serial
mismatch* / *no UDP answer*; **Save** switches the reader to HTTP and set-networks its server to
this booth's IP + port, confirmed by re-read. All verified on the bench unit (WG26→HTTP; target
8080→8081→8080; struct byte-identical after). The scan GET stays unauthenticated — the reader is
identified by serial, so no push secret is stored for it.
## What it is
- **QR/barcode + card.** Reads **QR / simple barcode** AND **ID/IC/NFC cards** (~0.2 s, 0–10 cm).
(An earlier note guessed "ER80-EM = 125 kHz EM4100 prox" — that was part of the same mis-id.)
- **Interfaces: Wiegand 26/34, TCP/IP, USB, RS485.** (NOT RS-232 — that was a fictional-datasheet
claim.) For our integration it talks **HTTP over TCP/IP**; Wiegand is the reader's *output line*
- **Interfaces: Wiegand 26/34, TCP/IP, USB, RS485** per the product page; the box leaflet
([[dingtian-dt008-box-manual]]) also lists **RS232**. (An earlier note dismissed RS-232 as a
claim from the mis-identified GEE PDF — withdrawn 2026-09-17.) For our integration it talks **HTTP over TCP/IP**; Wiegand is the reader's *output line*
on a valid read, not the host transport.
- **Power** 9–16 V DC, 800 mA; **86×86×42 mm**; −30…70 °C. Fits the [[disk-os-hardening|appliance]].
@@ -55,7 +76,8 @@ barrier. ([[device-input-flow]] is the analogous push pattern; this one also ret
- Pushes over plain **HTTP** to our `10.0.10.x` host (on the device subnet); no serial wiring, no
Wiegand-decode hardware. Suits the host-in-the-loop model; autonomy is moot anyway
([[dingtian-relay]] has no onboard ACL).
- Default IP `192.168.1.99` (set its server IP/port to this host in the vendor tool).
- Default IP `192.168.1.99` (set its server IP/port to this host in the vendor tool or with
`scripts/dingtian_qr.py`).
## Resolved (2026-06-16)
@@ -182,6 +204,82 @@ symbology except **QR + Code128** (all our credentials); if offered, set **minim
re-enables the phantom symbologies — re-apply after any reset/replacement. Physical fallback if any
noise survives: hood/visor the window, tilt it down, avoid facing the striped arm.
## ⚠️ Two units, two card sets, no overlap — 125 kHz vs 13.56 MHz (2026-09-17, unresolved)
The product page says the DT-008 reads "ID/IC/NFC cards" and the **box leaflet**
([[dingtian-dt008-box-manual]]) claims EM-ID, M1, ISO 14443A/B and ISO 15693 in one unit. Yet on
the bench 2026-09-17, with two card sets, the two units we own read **disjoint** sets:
| Unit | Serial family | Reads | Does not read |
| --- | --- | --- | --- |
| park-buzi entry/exit (bought 2026-06) | `H05M…` (`H05M2AFA`, `H05MA5B0`) | the site's enrolled cards (**125 kHz "ID"**, EM4100-class) | 13.56 MHz cards |
| lab unit (fresh, 2026-09) | `HC002721` | **13.56 MHz "IC/NFC"** cards (e.g. UID `A238BC`) | the park-buzi card set |
**The decisive test needs no hardware:** hold each card on an NFC-capable phone. A 13.56 MHz card
is detected; a **125 kHz card is invisible to a phone**. The lab reader and the phone agreed on
exactly the same set, and the other set was invisible to both — so the park-buzi set is 125 kHz and
the park-buzi readers are the 125 kHz variant. Card bodies help too: EM4100 / TK4100 / T5577 (often
a printed 10-digit decimal) = 125 kHz; Mifare / S50 / 1K / NTAG = 13.56 MHz.
Nothing in `QRCode_v1_6_5.exe` selects the frequency (no card-type field — see the screenshot in
[[site-device-installation]] §2).
**Why the lab unit does not read them is NOT settled** — the phone test only proves the park-buzi
cards are *not* 13.56 MHz. Three explanations remain, with different fixes:
1. **The park-buzi cards are 125 kHz but not EM4100** (HID Prox / Indala / AWID / a T5577 in a
non-EM format): invisible to a phone, not decoded by an EM-only front end, but read by the older
batch. Card bodies help: EM cards usually print a 10-digit decimal; HID cards carry the HID logo.
2. **The lab unit's 125 kHz front end is dead or disabled** — the leaflet says it should be there;
a firmware setting the v1.6.5 tool does not expose is possible.
3. **The leaflet is generic and units ship per variant** — the vendor can say from the two serials.
**Decisive test (cheap):** a known **EM4100 125 kHz card/keyfob** on the lab unit, held at 1–10 cm.
Reads → its 125 kHz radio works and the park-buzi cards are a different 125 kHz format (→ 1).
Does not read → unit defect or variant (→ 2/3, vendor with the serial). A USB keyboard-wedge
EM4100 reader (~10 €) additionally says outright whether the park-buzi cards are EM4100.
**Consequences (hold regardless of which explanation wins)**
- **A site's card stock and its readers must be proven together.** A card enrolled at park-buzi
is not readable by the lab unit today, whatever the reason; a replacement reader must be tested
against the site's actual cards **before** it ships, or every enrolled card is orphaned — same
class of trap as the `Card Input format`.
- **Purchase spec must name the card technology and format** the site uses (the serial family is
only a hint: `H05M…` reads park-buzi's cards, `HC…` does not). Ask the vendor (support address in
the tool's title bar) which card types a given serial decodes.
- **Bench testing park-buzi card problems on the lab unit is meaningless** until the lab unit is
shown to read the site's card type.
- **Open:** with a 13.56 MHz unit the native UID is 4 or 7 bytes, so `Card Input format = 6H`
truncates it — check on the lab unit which bytes survive and whether two cards can collide on the
6-hex value before enrolling anything against a 13.56 MHz reader ([[open-questions]]).
Record the variant on the site record next to the serial ([[site-device-installation]] §"Record").
**A phone is not a card (2026-09-17).** Tapping a phone on the 13.56 MHz unit beeps and logs a
*different* id every time (`18CA08`, `37F108`, `D5A908` three seconds apart). Read backwards
those are `08 CA 18`, `08 F1 37`, `08 A9 D5`: a first UID byte of **`08`** is the ISO 14443
marker for a **random UID**, which every phone in card-emulation mode generates per tap so that
readers cannot track the handset. So a phone can never be enrolled as an RF credential, and a
phone tap in the logs is not a clone attempt — just noise with a fresh id each time. Same for
cards with a "random ID" feature (DESFire / Mifare Plus in random-UID mode): if a card ever
enrolls but "stops matching", check whether its id changes between taps.
Incidentally this shows what **`6H` does on a 13.56 MHz unit**: the tool prints the **first three
bytes of the 4-byte UID, byte order reversed, fourth byte dropped**. Confirm against a card with
its UID printed on the body before enrolling; the dropped byte is the collision risk in
[[open-questions]] #18.
## Bench sink — `scripts/reader-sink.py` (2026-09-17)
A stdlib-only Python HTTP server that answers the push on any `/qa/mcardsea.*` path with the SDK
verdict (`--accept` → status 1 / two beeps, default status 0 / one beep), `Connection: close`, and
prints one line per read: time, source IP, `serial`, `dev`, `dir` (from the `status` low digit),
`ch` (from the `Q:`/`K:` prefix), `cardid`, path. Point the reader's *Server address / Server Port*
at the laptop (`python3 scripts/reader-sink.py -p 3000 --accept`, port 80 needs admin rights). Use it
to see the raw `cardid` a card yields, to prove a reader pushes at all, and to time the beep against
the reply. No app, no DB, no Docker.
## ⚠️ Reply MUST set `Connection: close` (verified on hardware)
The reader sends `Connection: keep-alive` but **only acts on the verdict (beep/output) once the TCP
+107
View File
@@ -0,0 +1,107 @@
---
type: entity
tags: [parking, hardware, printer, escpos, network, usb, status]
sources: []
updated: 2026-09-09
---
# K200L thermal printer (Xprinter / ICS "XP-K200L") — the park-buzi unit
An 80 mm ESC/POS receipt printer, **USB + LAN**, sold under several names. Bottom label:
*"THERMAL RECEIPT PRINTER — Model: K200L — Paper Width: 80mm — Print Speed: 200mm/s — Power
Input: 24V 2.5A — Cash Drawer: 24V 1A — Interface: USB+LAN — Command Support: ESC/POS"*, serial
`BLU2107080238`. Identified on the dev bench 2026-09-09; **it is the printer that "goes offline
after a paper reload" at park-buzi** ([[printer-usb-transport]] §Field bug). The lab's older
"ICS XP-K200L" (10.0.10.11, the 2026-07 USB truncation work) is the same family.
Three names for one device, all seen on the bench:
| Where | What it calls itself |
| --- | --- |
| bottom label | K200L |
| USB descriptor (`lsusb`) | `1fc9:2016 NXP Semiconductors Printer-80` / "Printer POS-80" (0x1fc9 = the NXP controller chip; no brand) |
| LAN board web UI | "J-Speed Ethernet Interface Module", "Ethernet WebConfig Version 1.02", copyright "POS" |
The app driver is **`k200l`** ("K200L 80mm thermal printer (Xprinter / ICS, USB+LAN)",
`packages/devices/src/drivers/printer-k200l.ts`). It prints through the shared generic ESC/POS
path (identical bytes, TCP 9100 or `usblp`) and **adds live status from the LAN board** — see
below. Before 2026-09-09 this unit ran on the generic `escpos` driver (reachability only), which is
why the app could never show its cover/paper state.
## Network setup (the evening that was never written down)
- **Factory address `192.168.123.100/24`, DHCP OFF.** Nothing announces it; the printer just sits
there on a subnet nobody uses. To reach it, give the workstation a second address in
`192.168.123.0/24` (Windows: adapter → IPv4 → Advanced → add `192.168.123.101`), then open
`http://192.168.123.100/`.
- The web configurator (port 80, **no authentication**) is a three-frame page: *Information*
(`ip_info.htm`: MAC, IP, mask, gateway, DHCP on/off, DHCP timeout), *Configuration*
(`ip_config.htm`: DHCP client on/off + timeout, fixed IP / mask / gateway as four octet fields,
**Save**, Restore Default, cancel), *Printer Status* (`prt_status.htm`), *Printer Test*
(`prt_test.htm`), and a **Restart** button in the menu.
- **Set a fixed address on the device VLAN** (park-lab: `10.0.10.7/24`, gateway `10.0.10.1`) →
Save → Restart; then remove the temporary `192.168.123.x` address from the workstation. Keep
DHCP off — the app addresses printers by IP ([[rongta-printer]] §Deployment).
- The self-test page (`prt_test.htm` / the "Print Test Page" button on the status page) prints
the current network settings, so a unit with a forgotten address can be read back that way.
- The board's HTTP server is **tiny**: the frameset reloads its frames every 1–3 s and the status
page every 5 s, and it holds very few connections. **Close the browser tab while the app is
polling**, or connections intermittently time out (seen on the bench: `ping` fine, port open,
every second HTTP connect hanging while the page was open in a browser).
> **WSL gotcha while doing this (2026-09-09):** the dev box then carried BOTH `192.168.123.101`
> and `10.0.10.203` on `eth0`, and WSL sourced 10.0.10.x traffic from the 192.168.123 address —
> the exact [[wsl-dev-networking]] source-address bug, except `parking-net.service` pins `eth1`
> and the mirrored LAN NIC is `eth0` now. Symptom: `ping` works, `curl` times out. Run the fix for
> `eth0`, or drop the temporary address once the printer is moved.
## Live status — the `/prt_status.htm` page
The LAN board serves a five-row table the printer has already decoded from its own sensors:
```
Cover Is Open Yes/No
Cutter Error Yes/No
Paper End Yes/No
Paper Near End Yes/No
Printer Off-Line Yes/No
```
A fault is written as **`<FONT color=#ff0000>Yes</FONT>`** while a clear row is a bare, space-padded
`No` — the first parser only accepted tag-free cells, so with the cover open the booth showed
*"unexpected status page (missing coverOpen, paperEnd, offline)"*: exactly the Yes cells. Fixed
the same day (cell text is read with inner tags stripped); the verbatim markup is pinned in the
driver's tests.
**Same rows, same `<TD>label</TD><TD>Yes|No</TD>` shape as the Rongta board's `/prn_stat.htm`**
([[printer-status-monitoring]]) — only the path differs, which is why nobody found it in July
(the Rongta driver looked for `/prn_stat.htm`, got nothing, and the unit was filed as "serves no
status page → generic driver"). Verified on the bench: cover open → `Cover Is Open Yes`, `Paper End
Yes`, `Printer Off-Line Yes` within a refresh; cover closed → all `No`.
**Quirk that needs its own fetch code:** the board's HTTP reply has **no status line and no
headers** — the body starts at byte 0 (HTTP/0.9 style). Browsers render it; `curl` reports
`000` with an empty body; Node's `http` client rejects it with *"Parse Error: Expected HTTP/, RTSP/
or ICE/"*. So the `k200l` driver reads the page over a **raw TCP socket** (`GET … HTTP/1.0`, read
until the board closes) and accepts both the headerless reply and a proper one. This is the second
reason the K200L has its own driver rather than a path option on the Rongta one.
Status mapping (mirrors the Rongta driver, [[printer-status-monitoring]]): board unreachable /
timeout → **offline**; page reachable but not the table (non-200, the index page) → **degraded
"unexpected status page"**, never ready off a page we didn't read; any Yes → **degraded** naming
the faults ("cover open, paper out, printer off-line"); all No → **ready**. Over **USB** there is
no page: reachability floor only (ready/offline), same as a USB Rongta.
## What this means for the park-buzi bug
At park-buzi this unit ran **over USB** on the generic driver, i.e. monitored by "does
`/dev/usb/lpN` open". A cover-open / paper-out condition **never showed in the app at all** — the
badge stayed green. So the operators' "printer goes offline after reloading paper" was not the
cover state being reported; it was a genuine probe failure whose errno is still unread (site shut
down — [[printer-usb-transport]] §Field bug has the commands to pull first). Running the unit on
**LAN with the `k200l` driver** would give the booth a real amber "cover open / paper out" while
the roll is changed, and removes the `usblp` path from the equation altogether — a strong reason to
cable it to the device VLAN when the site reopens.
Related: [[rongta-printer]] · [[printer-status-monitoring]] · [[printer-usb-transport]] ·
[[printer-roles-failover]] · [[network-isolation]] · [[wsl-dev-networking]] · [[site-device-installation]]
+28 -10
View File
@@ -2,7 +2,7 @@
type: entity
tags: [parking, hardware, readers, offline-first]
sources: [parking-system-architecture, DS-2CD1047G3H-LIU]
updated: 2026-08-23
updated: 2026-09-17
---
# LPR Camera
@@ -38,8 +38,12 @@ the "Backend push IP" field for it (gated on the driver's `pushesToBackend` flag
- **Hikvision** uses **ISAPI**: `GET /ISAPI/Streaming/channels/<id>/picture` (`101` = ch1 main
stream) with **HTTP Digest** auth. The "Enable Hikvision-CGI" toggle (Network → Advanced →
Integration Protocol) is a *different* legacy CGI surface — **not** needed for ISAPI.
- **Dahua** uses CGI: `GET /cgi-bin/snapshot.cgi?channel=<n>` (0-based channel; the wizard's
1-based channel is decremented).
- **Dahua** uses CGI: `GET /cgi-bin/snapshot.cgi?channel=<n>`, channel **as entered (1-based)**.
Until 2026-09-17 the driver decremented it on the belief the CGI is 0-based — the bench
IPC-HFW2549T (fw 2.880) answers `channel=0` with **400** and `channel=1` with the JPEG; fixed and
verified with the real driver the same day. Clock sync exists for Dahua too (`global.cgi`,
naive wall time). Full inspection: [[dahua-ipc-hfw2549t]] (events = held `eventManager attach`
socket, not an HTTP push — the subscriber is not built yet).
**Driver / storage boundary:** the driver FETCHES the image bytes (client-side HTTP Digest in
`drivers/http-digest.ts`) and returns them on `Snapshot.bytes`; **storage is the caller's job**
@@ -227,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
+5 -1
View File
@@ -2,7 +2,7 @@
type: entity
tags: [parking, hardware, printer, device]
sources: []
updated: 2026-06-19
updated: 2026-09-09
---
# Rongta 80mm thermal printer
@@ -55,6 +55,10 @@ many ESC/POS-compatible OEM clones that share its firmware). Driver `rongta` in
- **booth-receipt** — `10.0.10.10`, inside the booth; receipts, AND the backup that prints
the entry ticket if the outside dispenser is offline. This unit is a **Rongta** (`rongta`
driver, full status-page monitoring).
- **Not a Rongta, its own driver since 2026-09-09:** the **K200L** (Xprinter/ICS XP-K200L family;
LAN board calls itself "POS-80") — the park-buzi unit and the lab's 10.0.10.11 unit. Same
five-row status table under **`/prt_status.htm`** (not `/prn_stat.htm`), served without HTTP
headers, so it has the `k200l` driver with a raw-socket fetch. See [[k200l-printer]].
## Ticket rendering
+120 -6
View File
@@ -2,7 +2,7 @@
type: entity
tags: [parking, domain, business, subscriptions, identity, pricing]
sources: []
updated: 2026-06-20
updated: 2026-09-08
aliases: [subscription-plan]
status: open
---
@@ -90,6 +90,15 @@ subscription row, one window. The amount the operator should collect is **N × t
`now` ∈ [validFrom, validTo]** — so a 3-month window simply stays valid for three months.
- An explicit **`validTo` override** is still accepted (manual end date) when `months` isn't used.
> ⚠ **Renewal is OFF-BOOK (found 2026-09-08).** "Renewing is just editing the window" means a
> renewal goes through `PUT /api/subscriptions/:id`, which by design **never re-sells and appends
> nothing to the ledger**. The first sale was put on the chain on 2026-06-20 precisely because
> 27,000 ALL had gone off-book; **every renewal since takes the same off-book path** — the
> operator collects the next month's fee and moves `validTo`, with no `payment` event. The
> recurring-billing design below closes this: a renewal becomes *paying the next billing period*,
> a signed `payment`. Until then, a renewal should be taken as a **new sale** (new subscription
> row), not an edit.
### v2 — quantity, plan timeframes (tariff bridge), reserved spots (built 2026-06-20)
Three enhancements driven by real scenarios (migration `0011`):
@@ -356,6 +365,106 @@ Intended behaviour (to design + build later):
> **Explicitly postponed.** For now this is documentation only — no schema, no enforcement. A
> subscription is valid whenever it is active and within `validFrom`/`validTo`, all day.
## Recurring billing — prepaid / postpaid, calendar or anniversary — DESIGN 2026-09-08
**Design only, nothing built.** Captured from a design conversation with the user (2026-09-08):
"a subscriber should prepay or postpay every month, on the 1st or on the day the subscription
began; a subscription fixed by a daily tariff, e.g. 300 ALL/day; for prepaid, a notice that a
subscription is about to expire so the owner/operator warns the subscriber to pay or lose access."
The financial side of this grew into its own page — the [[party-ledger]] — because a postpaid
subscriber is a *debtor*, and the site has other debtors (hotels, fleets) and creditors
(suppliers). This section is the subscription-shaped part.
### What is wrong with the one-window model
A subscription today is **one coverage window** (`validFrom`/`validTo`) sold once: a hotel model.
There is no recurring agreement, no due date, no grace, no unpaid balance; prepaid vs postpaid is
not expressible, and calendar-anchored billing can only be faked with hand-picked dates. And
renewal is off-book (callout above).
### Split the one row into three concepts
**1. Plan** — the catalog and versioning stay; a plan version gains a **billing rule**:
```
billing: {
mode: "prepaid" | "postpaid",
cycle: "day" | "week" | "month", // how often a period is billed
anchor: "calendar" | "start", // the 1st of the month, or the sale's anniversary
graceDays: number, // access continues this long past due
noticeDays: number // "about to expire" window
}
```
Recurring plans are **priced per day** (`period: "day"`): a calendar month costs
`daysInMonth × 300 ALL`, a partial first month is simply the days left, and **calendar and
anniversary anchoring share one formula** (proration falls out for free). Fixed-price monthly
plans (`period: "month"`) stay for sites that want a flat number. The hotel "N nights" sale is
unchanged (a `"day"` plan over a span, no billing rule).
**2. Agreement** — the `subscriptions` row: holder, credentials, cars, `validFrom`; for a
recurring plan **no `validTo`** (open-ended, ends by revoke/suspend). Fixed spans keep `validTo`.
The holder is (or is linked to) a **party** ([[party-ledger]]) — the payer, which for a hotel is
the hotel, not the guest.
**3. Billing periods** — one row per cycle, and each is a **`charge`** on the party ledger:
```
subscription_periods id, subscriptionId, periodFrom, periodTo,
amountMinor (from the plan version), currency, dueAt,
status {due|paid|overdue|waived}, chargeEventId, paymentEventId?
```
- **Paying a period** = the existing signed **`payment`** with `subscriptionSale: true` plus the
period/charge reference — drawer and Z-report keep working with no new summing
(§Collecting the fee). **Renewal is just paying the next period.** This closes the off-book hole.
- **Waiving** a period is a signed **$0 payment with a reason** — the same rule the Car Wash uses
for a comp ([[venue-modules]]: a comp never opens the barrier, sign the $0 payment) — or a
`write_off` on the party ledger; admin-gated either way.
- The next period is **generated ahead** (prepaid: before the current one ends, so it can be paid
early; postpaid: at period end, due `dueAt`), by a daily tick or lazily on read.
### The gate asks one function
The entry flow stops reading `validTo` for recurring plans and asks
`subscriptionAccess(sub, periods, now) → { ok, reason, accessUntil, daysLeft }`:
- **prepaid** — allowed while `now ≤ paidThrough + graceDays` (the next period must be paid
before it starts, plus grace);
- **postpaid** — allowed while no period is unpaid past `dueAt + graceDays`;
- both collapse to one derived **`accessUntil`** and **`daysLeft`** per subscriber (never stored).
This also answers the long-open **lapsed-mid-stay** question for recurring subs: a period ending
while a car is parked falls into **grace**, so nobody is trapped; only a subscriber still parked
past grace becomes a transient at exit (the tariff-bridge machinery above already prices that).
Revoked/suspended behaviour is unchanged.
### "About to expire" — derived, not stored
One endpoint (e.g. `GET /api/subscriptions/attention`) lists subscribers whose `accessUntil` falls
within the plan's `noticeDays`, those in grace, and those overdue. Surfaced in three places:
1. a **counter on the booth console** ([[booth-console]]);
2. a **badge in the subscriber list**;
3. a **line in the live feed when such a subscriber scans in** — "expires in 3 days" at the moment
the person is at the gate (a slip can print, best-effort like the window-charge notice).
Contacting the subscriber stays with the operator/owner by phone (`contact` field). SMS/email
is off-appliance ([[cloud-service-saas]]) — a separate decision.
### Not built, deliberately
Automatic card charging, invoices, dunning, auto-suspension without grace. **The operator still
never types a price.**
### Build order (after [[party-ledger]] step 1)
1. Billing rule on the plan version + `subscription_periods` (migration); period generation.
2. Pay-period route (signed `payment` + charge reference) and the `subscriptionAccess` gate
function in `subscription-flow.ts`; `PUT` stops moving `validTo` on recurring subs.
3. Attention endpoint + the three UI surfaces.
4. Wiki + [[booth-console]] docs.
## Data model (as-built 2026-06-18)
Tables (mutable master data; every *use* still produces a signed `vehicle_entry`/`vehicle_exit`):
@@ -420,10 +529,15 @@ subscription** (card/QR credential, or a bound plate) — otherwise to the trans
1. **Reader hardware** — confirm the RF reader and QR/optical reader models (procurement; [[bom]],
[[open-questions]]).
2. **Lapsed-mid-stay & revoked** policy (fall back to transient [[tariff]] vs. refuse) — confirm.
3. ~~**Subscription-fee collection**~~ — **RESOLVED + BUILT 2026-06-20.** Selling a priced
subscription appends a signed `payment` (`subscriptionSale` flag, `priceMinor × months`,
operator-chosen tender) that folds into the drawer/Z-report. Remaining sub-question: should a sale
be **hard-blocked without an open shift** (it isn't today — it warns instead)? See "Collecting the
fee".
3. ~~**Subscription-fee collection**~~ — **RESOLVED + BUILT 2026-06-20** for the *first* sale
(signed `payment`, `subscriptionSale` flag, operator-chosen tender, folds into the
drawer/Z-report). **REOPENED 2026-09-08 for RENEWALS**: a renewal is a `PUT` that appends
nothing (see the callout under "Multi-month"). Closed by the recurring-billing design (a renewal
= paying the next period). Remaining sub-question: should a sale be **hard-blocked without an
open shift** (it isn't today — it warns instead)?
4. **Time-of-day access windows** (overnight subscribers) — design + build; boundary-case policy
above (see the design note).
5. **Recurring billing** (prepaid/postpaid, calendar/anniversary anchor, grace, expiry notice) —
**designed 2026-09-08, not built**; see §Recurring billing and [[party-ledger]]. To refine: is
the next period generated by a daily tick or lazily; does a waived period sign a $0 `payment` or
a `write_off` (pick one); whether `noticeDays` is per plan or per site.
+12 -4
View File
@@ -17,7 +17,9 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
## Sources
- [[parking-system-architecture]] — design notes: stack, threat model, devices, UHPPOTE, ESP32, readers, BOM, open decisions.
- [[dingtian-dt008]] — Dingtian DT-008 product page: QR/RFID access reader (QR/barcode + ID/IC/NFC; Wiegand/TCP-IP/USB/RS485; HTTP-GET push).
- [[dingtian-dt008-box-manual]] — the leaflet from the box: claims EM-ID + M1 + ISO 14443A/B + 15693 in one unit, RS232 listed.
- [[qrcode-sdk]] — QRCode SDK v1.6.5: the reader's HTTP-GET-poll protocol + JSON verdict (beep/output).
- [[dingtian-qr-linux-tool]] — the exe's config protocol reversed (UDP 24680/24582) + `scripts/dingtian_qr.py`: read/set a DT-008 from the booth over SSH; output-type write proven on the bench.
- [[parksql2017-legacy-schema]] — predecessor SQL Server schema (Albanian market): legacy tariff/discount/membership/shift/fiscal model; confirms blocks, adds time-windows + categories, lacks postpaid sponsors.
- [[ds-2cd1047g3h-liu]] — HIKVISION DS-2CD1047G3H-LIU-F datasheet: 4MP, main stream has no MJPEG option (sub does) — likely explains the model's persistent ISAPI snapshot 503 on main; confirms ISAPI/RTSP both fully in-spec.
@@ -41,11 +43,13 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[atecc608]] — secure element; non-extractable signing key (host events + controller auth).
- [[wiegand]] — reader standard feeding the controller directly (autonomous permit-holder path).
- [[lpr-camera]] — edge-AI plate recognition; host-side casual-identity source; DS-2CD1047G3H-LIU main-stream ISAPI snapshot 503 is a firmware bug (only channel 102 ever works, ALL other IDs incl. garbage 503 identically) — firmware update tested, no fix; owner decided to replace the camera line rather than build an RTSP workaround.
- [[dingtian-dt008-reader]] — Dingtian DT-008 QR/RFID reader on hand; host-side serial → `read` bus (the QR-ticket scanner).
- [[dingtian-dt008-reader]] — Dingtian DT-008 QR/RFID reader on hand; HTTP-GET push, server replies the verdict; ⚠️ our two units read disjoint card sets (125 kHz vs 13.56 MHz) — unresolved, see open question #18.
- [[zkteco-controller]] — ❌ rejected/historical; aux-input path was a contender, not pursued.
- [[dingtian-relay]] — ✅ CHOSEN access controller; decoupled inputs solve the button blocker (driver verified on hardware); spare relays drive aux outputs (`setAux`).
- [[dahua-ipc-hfw2549t]] — first Dahua on the bench (IPC-HFW2549T-AS-IL, fw 2.880, 2026-09-17): the driver's channel decrement gave HTTP 400 (channels are 1-based — fixed + verified live); Dahua clock-sync built (`global.cgi`, naive wall time); events = held `eventManager attach` multipart stream, verbatim `VideoMotion Start/Stop` + `TimeChange` parts captured, subscriber not built; `RealUTC` is the camera's belief of UTC; 5-strike login lockout.
- [[hikvision-radar]] — vehicle-presence radar on a Dingtian input; the entry presence gate (per-input active-level caveat).
- [[rongta-printer]] — ✅ CHOSEN 80mm thermal printer; ESC/POS over raw TCP 9100 (or local USB, see [[printer-usb-transport]]); driver written, one unit reachable at 10.0.10.6.
- [[k200l-printer]] — the park-buzi printer identified (2026-09-09): Xprinter/ICS K200L, USB id 1fc9:2016 "POS-80", J-Speed LAN board at 192.168.123.100 (DHCP off, web config on :80); status page `/prt_status.htm` (Rongta's rows, headerless HTTP) → own `k200l` driver with raw-socket fetch; over USB reachability only, so cover-open never showed at park-buzi.
- [[bom]] — reference bill of materials (barrier, loops, controller, readers, payment, host, network).
## Concepts — foundational forces
@@ -65,8 +69,9 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[device-adapter-pattern]] — business logic talks to interfaces; swap hardware → new adapter.
- [[device-registry]] — catalog of selectable drivers per category (admin-configurable).
- [[first-run-setup]] — admin adds controllers + binds readers/cameras to relays from the catalog at install.
- [[site-device-installation]] — FIELD RUNBOOK (2026-09-09): per device — factory address + credentials, the tool needed, what the wizard configures itself vs what is done by hand on the device, known traps; address plan, order of work on site, gaps to fill. Dingtian relay, DT-008 readers, Hikvision camera, radar, K200L / Rongta / Cashino printers.
- [[device-input-flow]] — button → device push → backend decides → relay; backend is source of truth.
- [[device-discovery]] — optional driver capability to scan the LAN (no current driver uses it; UHPPOTE was the example).
- [[device-discovery]] — optional driver capability to scan the LAN; implemented by the DT-008 reader (2026-10-08), UHPPOTE was the historical example.
- [[barrier-not-a-door]] — never timed-close a barrier; safety lives in barrier firmware.
- [[printer-roles-failover]] — ≥2 printers by role; entry ticket falls back outside→booth.
- [[printer-status-monitoring]] — live poll of paper/cover/cutter/offline via the device's status page; SSE to the booth UI.
@@ -102,7 +107,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[site-metadata]] — optional park identity (name, operator, VAT, address, contact) in site_config; feeds the ticket header.
- [[valet-overcapacity]] — "full" is soft: operator may valet-accept over capacity (keys handed over, custody). Manned, deferred.
- [[validation-discounts]] — BUILT (2026-07-13): in-park merchant (bar/lavazh) users scan-and-validate on their device (signed event, program↔user binding); booth settles NET + prints gross/discount/net; comp/time-credit/fixed/percent, caps, /setup/site panel, /validate screen.
- [[validation-sponsorship]] — design: sponsor accounts + postpaid B2B (customers park free, business billed monthly); not a permit.
- [[validation-sponsorship]] — design: postpaid B2B sponsorship (customers park free, business billed monthly); its sponsor-account sketch is superseded by [[party-ledger]].
- [[reporting-analytics]] — revenue/occupancy/stay reports + plate-search, all projections over the signed log.
- [[clock-integrity]] — fees depend on the host clock; detect/flag backdating on an offline box.
- [[ticket-encoding]] — transient ticket id (11-digit numeric + Luhn) as Code128; printed at entry, scanned at pay station + exit; barcode geometry must fit paper width (KP-300H overflow); plate-as-ticket alt.
@@ -110,7 +115,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[device-events]] — unsigned hardware telemetry (relay/printer/camera/reader/input); separate from the signed ledger.
- [[app-logs]] — the third stream: diagnostic logs (backend warn+ pino sink + frontend errors) → app_logs; log:read viewer; pruned by age+row cap.
- [[soft-delete]] — BUILT: accidental admin deletes of master data (users/roles/subs/plans/tariffs) are soft (deleted_at) + recoverable from a recycle bin; auto-purge after N days; signed ledger out of scope.
- [[subscription]] — recurring plan (e.g. 10,000 ALL/month); RF/QR or plate identity, car-count + max-concurrent, host-in-loop; short-circuits payment. (Renamed from "permit"; time-of-day windows noted, deferred.)
- [[subscription]] — recurring plan (e.g. 10,000 ALL/month); RF/QR or plate identity, car-count + max-concurrent, host-in-loop; short-circuits payment. Plan catalog + tariff bridge built. 2026-09-08: **renewal found off-book**; recurring billing (prepaid/postpaid, calendar/anniversary, grace, expiry notice, billing periods as ledger charges) designed, not built.
- [[opencv-anpr-service]] — host-side vision microservice: ANPR (plate identity) + vehicle verification (anti-plate-spoofing witness); fast-alpr (MIT, YOLOv9+CCT/ONNX) the evaluated recognizer baseline.
- [[lane-presence-and-anpr-entry]] — camera vehicle detection → (BUILT) advisory lane busy/free booth lights + (BUILT) the ANPR "bridge" (`anpr-entry.ts`): a subscriber's plate read at the lane admits them via the existing gated subscription flow (match-before-emit; subscriber-only). Measured camera limits; rejected the queue-tracking/livestream ideas.
- [[vision-service-hardening]] — fix/hardening backlog for `apps/vision/` (2026-07-02 reviews): DoS (body-cap, pixel-bomb, event-loop-blocking inference), unauthenticated + operator-writable model weights, `0.0.0.0` default bind, + correctness/hygiene items. Not yet fixed — the to-do list.
@@ -134,9 +139,12 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[session-model]] — business layer start: session = projection; transient-first; pay-on-foot. New event types.
- [[vision-service]] — build a host-side ANPR + vehicle-verification service; replaces edge-LPR; scoped AGPL exception.
- [[bodytype-classifier-training]] — phase B (SUV vs sedan): `apps/trainer` trains on the collector host (time split, floor, features/finetune modes, feature cache) → report → publish to the Gitea generic package → `models/bodytype.version` pin bakes it into the vision image → TAG bump; sidecar = the preprocessing contract; CPU-only torch on the Xeon E3-1225 v5, Quadro FX 3800 unusable, cloud GPU rejected. Built 2026-09-07; first run waits for labels.
- [[device-discovery-roadmap]] — memo (open): how each known device class gets a wizard Scan — SADP + ONVIF for cameras (verified on the lab VLAN), 9100 sweep + fingerprint for printers, Dingtian relay multicast search, Dahua 37810; the reusable method and rules from the DT-008 work.
- [[forgiven-exit]] — decision + as-built (2026-10-08): owner opens the EXIT barrier with no payment — a signed zero-amount payment carrying the forgone fee as its own Z-report line (never in cash/card), exit only, admin permission + open shift, reason optional, prints nothing.
- [[vision-service-packaging]] — the vision service lives in this monorepo (apps/vision/), separate process, wired into Turbo via a package.json shim; uv-managed Python.
- [[event-streams-split]] — split the signed business ledger (ledger_events) from unsigned device telemetry (device_events).
- [[desktop-shell-tauri]] — ✅ Tauri v2 chosen over Electron for the desktop kiosk shell; thin wrapper, server keeps all logic. Best case Ubuntu 26.04 LTS (resolves WebKitGTK); worst case Windows+WSL → kiosk browser, no native shell. Auto-updater mirrors signed releases to public `mca/public_releases` (source repo is private — field appliances have no Gitea creds).
- [[party-ledger]] — 🟡 DESIGN (2026-09-08, not built): counterparty sub-ledger for who-owes-whom across modules — parties + signed `charge` / settlement / `write_off` events, balance derived never stored, aging + statements + CSV; lands postpaid subscriptions, hotel guest-nights, fleet washes on account, supplier/utility bills. Sub-ledger only: no bookkeeping, statements are not fiscal invoices, parties per appliance.
- [[venue-modules]] — 🟡 OPEN: optional per-site modules (Car Wash, Bar/Restaurant) with Parking as a peer module on a venue POS/audit core; manifest registry, entitled ∩ activated enablement (vendor env + site-admin config), validation kept for the Bar (Lavazh station retires with Car Wash), name stays parking-system, vision vehicle-category as an advisory anomaly flag.
- [[container-deployment]] — Docker images for the non-desktop apps: parking-server (Fastify API + bundled SPA via @fastify/static) + parking-vision (Python/uv ANPR); branch+SHA tags, per-env compose, Gitea registry, build-images.yml CI; pnpm deploy (not prune) for native better-sqlite3; migrate-at-boot.
- [[fleet-deployment-komodo]] — fleet control plane: Komodo Periphery on each booth, driven by Komodo Core over a NetBird mesh, running the same compose files. Deploys manual + pinned to dev-<sha> (no webhook); secrets Komodo-managed per-booth+unique; booth.sh demoted to break-glass. Threat-model caveats: Periphery is a root agent (mesh-bound only), EVENT_SIGNING_KEY-in-Core is a fraud-root blast radius until ATECC608 signs. komodo/ is infra-as-code.
+329
View File
@@ -3144,6 +3144,20 @@ run; the Quadro FX 3800 is unusable (cc 1.3), the HD P530 irrelevant, the Xeon E
compose seam drops the GPU reservation; cloud GPU rejected (crops stay on premises). Linked from
[[opencv-anpr-service]], [[vision-review-outbox]], index. User: "No build just yet."
## [2026-09-07] query | How to seed the admin user on a booth
Answered from [[appliance-provisioning]] §7b/§7e (`docker exec … node scripts/seed-admin.mjs`,
`FORCE=1` to reset a password). One gap filled: the container-name pattern (`<stack>-server-1`,
`park-2-server-1` on park-2), the prompting form, idempotence, and re-seeding after a reset.
## [2026-09-07] fix | reset-db drift — Car Wash tables and role_jobs were uncategorised
User asked for "the command to reset everything in the booth pc". The documented command
([[appliance-provisioning]] §7d, `docker exec … reset-db.mjs --all`) would have been refused on
park-2: the drift guard found `carwash_*` (six tables) and `role_jobs` outside every category.
Categorised (orders + review outbox → financial; prices/categories/services/config → config;
role_jobs → users), `--all` verified on a freshly migrated DB. The script ships in the server
image — fixed on the booth from the next deployed tag, or by `docker cp` until then. Table
rows updated on [[local-dev-workflow]].
## [2026-09-07] decision | Desktop v0.2.0 — a minor bump, not a patch
User: "Do you think we are ready for version 0.2.0? The actual version is 0.1.7." Yes: v0.1.x
were all shell fixes; the bundled SPA now carries the module registry, Car Wash + per-till
@@ -3199,3 +3213,318 @@ variable, deploy the collector before a booth that sends a new package kind, the
neutralisation (security review finding), and why every entry is sent. On
[[vision-service-packaging]]: CI syncs without the alpr extra — numpy in the dev group, cv2 tests
importorskip (three red runs on 2026-09-07).
## [2026-09-08] decision | Subscription recurring billing + the party ledger (design only)
User: "an subscriber should prepay or postpay every month, at the 1st or the day it began; fixed
by a daily tariff (300 ALL/day); notify when about to expire … we need a more flexible way." Then:
"the financial aspect is too simple" — postpaid agreements, hotels given daily access for guests,
Car Wash fleet deals paid per period, the wash's supplier/utility bills; the admin needs to see
uncollected dues. Assessed against the code: a subscription is ONE coverage window sold once;
**renewal is off-book** (a `PUT` that never re-sells and appends no `payment` — the same hole
closed for the first sale on 2026-06-20). Designed, not built: (a) [[subscription]] §Recurring
billing — plan billing rule {mode, cycle, anchor, graceDays, noticeDays}, recurring plans priced
per day so calendar and anniversary anchoring share one formula, open-ended agreement, a
`subscription_periods` table where each period is a ledger charge and a renewal = paying the next
period (signed `payment`), one `subscriptionAccess()` gate function (answers lapsed-mid-stay via
grace), expiry notice derived not stored (console counter, list badge, feed line at scan-in);
(b) new [[party-ledger]] decision page — parties + signed `charge` / settlement (`payment` /
`cash_out` / bank) / `write_off`, balance derived never stored (threat model), aging + statements
+ CSV, the four cases (subscriptions, hotels, fleet washes as `payAt: "account"`, supplier bills
as payables), the line drawn (sub-ledger, not bookkeeping; a statement is not a fiscal invoice;
parties per appliance), build order. [[validation-sponsorship]]'s sponsor table marked
superseded; [[open-questions]] #17 added, #3 on the subscription page reopened for renewals;
index updated. Nothing in code changed.
## [2026-09-09] ingest | Printer cover-open bug — bench result falsifies re-enumeration; park-lab rejoins the fleet
The failing park-buzi printer is on the dev bench: identified as USB `1fc9:2016` "Printer POS-80"
(NXP controller, no brand in the descriptor — hence "Generic" in the app). Attached to WSL via
usbipd-win 5.3 (busid 8-1). Cover cycled under `dmesg -w` + `lsusb`: NO disconnect, NO
re-enumeration — the leading hypothesis (cover cuts the USB board → stale container `/dev/usb`
bind-mount) is falsified for this unit; the fault is in how usblp / the open-probe reacts to the
printer's error state. Next discriminator = the monitor's offline `detail` text on park-buzi
(EBUSY vs open-timeout vs EIO). WSL caveat recorded: Microsoft's 6.6.87 kernel has
CONFIG_USB_PRINTER unset — no `/dev/usb/lpN` without a custom kernel, so the user will reproduce
on a Linux box instead. `komodo/resources.toml`: `park-lab` stack re-added for that box — copied
from park-2 then corrected (the copy carried park-2's review outbox + booth-2 token; removed — the
bench must never feed the collector under a booth id); pinned to the booth's stage-<sha>. Pages:
[[printer-usb-transport]] (identity, bench result, WSL caveat), [[fleet-deployment-komodo]]
(park-lab row).
## [2026-09-09] ingest | Printer cover-open bug — lab did NOT reproduce; park-buzi closed, evidence pending
Same printer unit on `park-lab` (real Linux host, booth image stage-2d9bb15, prod compose, dev DB
snapshot with the USB printer as booth-receipt, cards via subscription reprint): paper out → cover
→ reload → reprint — no error. Printer, USB transport and compose wiring cleared in isolation;
what remains is park-buzi's environment (kernel/USB path/power) or the container's history.
park-buzi is shut down (staff shortage). Recorded on [[printer-usb-transport]]: the three
commands to run FIRST when the box next powers on (container log transitions, kernel journal,
`lsusb -t`), how to read each answer, and two proposed no-booth follow-ups (close the
`withTimeout` handle leak; make the monitor self-document consecutive USB offline polls).
Dev-DB snapshot procedure for a lab (online backup → reset-db --financial --diagnostics → clear
backup fields → VACUUM → copy into the volume with chown) used today; not yet on a wiki page.
## [2026-09-09] build | K200L printer identified + `k200l` driver with live status; network setup recorded
The bottom label says **Model K200L** (Xprinter/ICS XP-K200L family, USB+LAN, ESC/POS); the LAN
board ("J-Speed Ethernet WebConfig 1.02") calls it "POS-80", as does the USB descriptor. User
configured it from factory 192.168.123.100 (DHCP off, web UI on :80, no auth) to 10.0.10.7 on the
lab; added as booth printer on `park-lab` on the generic driver → badge stayed green with the cover
open, because the generic driver is reachability-only by design. Found the board's status page:
**`/prt_status.htm`**, the Rongta's five rows exactly, but the reply has NO status line/headers
(node:http: "Parse Error: Expected HTTP/"; curl: 000/empty) — so a Rongta-path option would not
have worked. Per the user ("this is not rongta", "create a new printer"): the Rongta driver is
untouched; new **`printer-k200l.ts`** (`k200l`) delegates printing to the generic ESC/POS device
and reads the page over a raw socket, tolerant of both reply shapes; mapping mirrors the Rongta
(unreachable → offline, page not understood → degraded never ready, faults → degraded named, USB →
floor). Tests replay the captured headerless page (10 new, devices suite 76 green); live probe
against 10.0.10.7 → ready; bench with cover open showed "cover open, paper out, printer off-line".
Consequence for park-buzi: over USB the app never saw cover/paper state at all — the reported
"offline" is a probe failure (errno still to be pulled). Pages: new [[k200l-printer]] (names,
network setup runbook, board quirks, status page, park-buzi implication), [[rongta-printer]],
[[printer-status-monitoring]], [[printer-usb-transport]], [[wsl-dev-networking]] (parking-net
pinned to eth1 while the LAN NIC is eth0 — the source-address bug bit again), index.
## [2026-09-09] query | Field runbook: installing the devices at a site (what to know before the booth)
User: "we need a section about installing these devices in the park sites … I didn't know this
printer has initial IP 192.168.123.100 and a web interface … also dingtian relays and readers,
cashino printers — know beforehand, not struggle on site." New reference page
[[site-device-installation]], synthesised from the entity pages + memory notes: the bring list,
the site address plan (10.0.10.x convention, every device static), then per device — Dingtian
relay (factory 192.168.1.100, admin/admin, what harden() does vs the by-hand IP + UDP2 disable,
wiring I1/I2, unauthenticated CGI, session_en brick), DT-008 readers (192.168.1.99, the
QRCode_v1_6_5.exe tool: unique IP, server target, Q:/K: prefixes, 6H card format, QR+Code128
only, serial binding, re-apply after a reset), Hikvision G3H (192.168.1.64 + activation, SUB
stream mandatory, Alarm Server after assign, Vehicle target filter, close the web UI, corrupt-DB
factory reset), radar (idle level → activeLow), printers (K200L / Rongta / Cashino table; LAN over
USB; "Test" probes, print a card to verify), the on-site order of work, and the gaps still
unrecorded (Cashino/Rongta factory addresses, the reader tool screens, camera activation, where
the site record lives). Linked from [[appliance-provisioning]] and [[k200l-printer]]; indexed.
## [2026-09-09] fix | K200L status parser — a fault's "Yes" is wrapped in <FONT color=#ff0000>
First live run on park-lab (driver `k200l`, LAN, cover open) showed *degraded — unexpected status
page (missing coverOpen, paperEnd, offline)*: precisely the three Yes cells. Captured the raw page
with the cover open: the board writes `<FONT color=#ff0000>Yes</FONT>` for a fault and a bare
padded `No` otherwise; the parser accepted only tag-free cells. Fix: cell text is read with inner
tags stripped (row-anchored regex); tests pin the verbatim markup plus other shapes (devices 79).
Live after the fix: degraded "cover open, paper out, printer off-line"; closed → ready. User:
"we are good using the network with this printer." Also: park-lab Periphery was "not loaded"
after a reboot — the unit had never been enabled; `systemctl --user enable --now periphery`
recorded as a §7a gotcha on [[appliance-provisioning]]. Pages: [[k200l-printer]].
## [2026-09-16] fix | Collector DB schema migration; trainer handlers answer 500 JSON; the "trainer not reachable" incident
User: "Training — trainer not reachable: fetch failed". Read-only look at art-docker-station over
SSH: collector stage-2d9bb15 unhealthy (`/health` 500 "no such column: kind"), trainer healthy
but `/readiness` tracebacks on the same column; the volume's collector.sqlite (2026-09-07, 0
items, original columns) predates `kind` — CREATE TABLE IF NOT EXISTS never migrates an existing
table. No `/ingest` request in the container's 9-day log at all (park-2 either not sending or not
reaching the host — to check on the booth). Built: `CollectorDb.#migrate()` (PRAGMA table_info vs
the list of columns added since the first deploy → ALTER TABLE ADD COLUMN; test replays the old
schema: health, ingest, stats, legacy row reads back with defaults); trainer `Handler._guarded`
(any exception → 500 JSON naming it; test: readiness on an old-schema DB → 500 "no such column:
kind", /health still 200); the collector's training proxy includes the trainer's error text. Pages:
[[vision-review-outbox]] (incident + rule), [[bodytype-classifier-training]] (what the message
means). Deploy: nothing manual — the new collector migrates on start.
## 2026-09-17 — DT-008 comes in two RF variants; cards are not portable between them
Bench finding: the fresh lab DT-008 (`HC002721`) reads a set of cards park-buzi cannot, and cannot
read park-buzi's enrolled cards. NFC-phone test settled it: the phone and the lab reader detect
exactly the same set (13.56 MHz), the park-buzi set is invisible to both (125 kHz). One radio per
unit, no setting selects it, same model name. Rule: a site's readers, its card stock and any
replacement unit must be the same variant; name the variant in the purchase spec and on the site
record. Also recorded the tool's Setting-tab layout (three groups, each with its own Set button).
Pages: [[dingtian-dt008-reader]], [[site-device-installation]] §2, [[index]].
## 2026-09-17 — phone taps on the DT-008 are random UIDs; what `6H` keeps
Three phone taps logged three ids ending in `08` — reversed, a first byte `08` = ISO 14443 random
UID, so phones cannot be RF credentials. Side effect: `6H` on a 13.56 MHz unit prints the first three
UID bytes reversed and drops the fourth. Pages: [[dingtian-dt008-reader]], [[open-questions]] #18.
## 2026-09-17 — box leaflet says the DT-008 reads every card type; "one radio per unit" downgraded
The leaflet in the lab unit's box ([[dingtian-dt008-box-manual]]) lists EM-ID, M1, ISO 14443A/B and
15693 in one reader, so the earlier "two variants, one radio each" is now one of three explanations
(variant / dead 125 kHz front end / non-EM 125 kHz cards at park-buzi). Decisive next test: a known
EM4100 fob on the lab unit. Leaflet also lists RS232 — the old "not RS-232" dismissal is withdrawn.
Pages: [[dingtian-dt008-reader]], [[site-device-installation]] §2, [[open-questions]] #18, [[index]].
## 2026-09-17 — `scripts/reader-sink.py`: a bench sink for the DT-008 push
Stdlib Python HTTP server answering the reader's GET with the SDK verdict + `Connection: close`,
one log line per read (serial, dir, channel, cardid). Page: [[dingtian-dt008-reader]] §Bench sink.
## 2026-09-17 — first Dahua on the bench: IPC-HFW2549T-AS-IL inspected over CGI
Snapshot, identity, config, RTSP and the `eventManager attach` stream all answered. Two things the
app got wrong by assumption: the Dahua driver's channel decrement (`channel=0` → HTTP 400 on this
firmware; channels are 1-based), and "Dahua would push like Hikvision" — it holds a multipart
subscription socket instead. Clock 1 h off (DST off, NTP off); `global.cgi setCurrentTime` is the
unbuilt clock-sync. Unit is not factory-fresh (hostname "main gate", SMD = vehicle). Pages:
[[dahua-ipc-hfw2549t]], [[lpr-camera]] §Snapshot driver, [[site-device-installation]] §3, [[index]].
## 2026-09-17 — Dahua driver: channel fix + clock sync, verified on the bench unit
`dahuaDriver` now sends the channel as entered (`camera.test.ts` pins the URL) and `DahuaCamera`
implements `syncClock` over `global.cgi` get/setCurrentTime with the host's naive wall time. Both
run against the real IPC-HFW2549T: snapshot 273 KB, a 2 h-off sync set and read back. A 25-min
`eventManager attach` listen captured the verbatim `VideoMotion Start/Stop`, `VideoMotionInfo` and
`TimeChange` parts; `RealUTC` proved to be the camera's belief of UTC (1 h skewed), so events get
stamped on receipt. Still open: the server-side attach subscriber, and whether SMD emits
`SmartMotionVehicle` in addition to / instead of `VideoMotion`. Pages: [[dahua-ipc-hfw2549t]],
[[lpr-camera]], [[site-device-installation]] §3, [[index]].
## 2026-10-08 — park-lab moves to art-docker-station; stack ports become env variables
The lab stack's Periphery is now the shared `art-docker-station`, whose `:80` is another
service's. `HTTP_PORT` / `SERVER_PORT` / `VISION_HOST_PORT` now flow from the stack env through
`docker-compose.prod.yml` into Caddy (`{$HTTP_PORT:80}` / `{$SERVER_PORT:3000}`), the host-net
server (`PORT`) and vision's loopback publish; defaults reproduce the booth layout exactly. park-lab
sets 8080 / 3100 / 8189. Pages: [[container-deployment]], [[fleet-deployment-komodo]] §park-lab.
## 2026-10-08 — park-2: card enrolment "beeps but captures nothing" = the readers never push
Three capture arms at 07:37–07:38Z, 37 polls, not one reader request; the whole 21 h server log has
zero `/qa/mcardsea` hits and `device_events` has no reader category at all — the two DT-008s
(serials HC009E84 / HC00D3B0, added to the wizard 2026-09-08) have never reached the booth. The beep
is therefore local (non-HTTP output type) or another server's. Fix = the vendor tool on-site:
Output type HTTP, server `10.0.10.101`:80. Runbook §2 corrected (output type explicit; "server IP"
no longer printed as the lab's `10.0.10.203`). Pages: [[site-device-installation]] §2.
## [2026-10-08] ingest | Dingtian QR reader — Linux configuration tool (raw/dingtian_qr_linux)
The exe's UDP protocol is reversed and `dingtian_qr.py` replaces it on Linux; copied to
`scripts/dingtian_qr.py`. Verified: discover/info/get on the bench unit; `set --output-type` 3→6→3
with a struct diff of exactly byte 0x198 (the whole Format sequence is now proven on hardware).
Then, read-only over SSH from the booth, **park-2's readers answered `output_type = WG26`** — the
root cause of the morning's "beeps but captures nothing": Wiegand mode, never HTTP. Server target
was already right (`10.0.10.101:3000`). The §2 trap's "needs a Windows laptop on the VLAN" claim
from earlier today is withdrawn. Fix pending the operator's go: `set <ip> --output-type 3` on `.7`
and `.8`. Pages: [[dingtian-qr-linux-tool]], [[dingtian-dt008-reader]], [[site-device-installation]]
§2, [[qrcode-sdk]], [[index]].
## [2026-10-08] ingest | DT-008 reader discovery + auto-configuration in the app
The `dingtian-qr-reader` driver now speaks the reversed UDP protocol itself
(`dingtian-qr-config.ts`, Node dgram): `discover()` (first driver to implement
[[device-discovery]]), preconditions (output type must be HTTP — fixable; typed serial must equal
the reported one — not fixable; no UDP answer — not fixable) and `configureInputPush` (set-network
to this booth's IP + port, confirmed by polling because the reader is silent after the write and
never acks). The wizard's existing Scan / Test / Save seams carry it; discovery rows show mode +
current target; no push secret is persisted for the reader (`usesPushAuth = false`); a reader
saved without an IP warns instead of failing. Verified end to end on the bench unit (WG26→HTTP,
target 8080→8081→8080, struct byte-identical), 17 adapter + 15 protocol tests. Not yet deployed:
needs a new image (push → CI) and a stack bump; park-2's readers still await the one-line fix.
Pages: [[device-discovery]], [[first-run-setup]], [[dingtian-dt008-reader]],
[[site-device-installation]] §2, [[dingtian-qr-linux-tool]].
## [2026-10-08] query | park-2 readers switched to HTTP from the wizard
park-2 deployed `stage-b7efa08`; the operator opened each reader in Setup and saved. Server log:
`10.0.10.7: output type WG26 → HTTP` (13:34:00Z) and the same for `.8` fifteen seconds later; a
read-back from the booth confirms both in HTTP mode at `10.0.10.101:3000`; Test shows no issues.
First real scan after the change still to be observed. Pages: [[site-device-installation]] §2.
## [2026-10-08] query | Memo: discovery mechanisms for relays, printers, cameras
Asked for by the operator. Probed the lab VLAN from 10.0.10.203 first: SADP multicast → 9
Hikvision devices (model, serial, MAC, ports; the DVR adds Encrypt/Salt); ONVIF WS-Discovery → 4
of them (XAddrs + hardware scopes); the bench Dahua answered neither (ONVIF setting to check) and
a guessed 37810 frame got nothing; a parallel TCP-9100 sweep found two office printers in ~1 s
(neither Rongta nor K200L → fingerprint step mandatory); no relay present for the `05 AA`
search. Memo filed as [[device-discovery-roadmap]] (method, per-device table, rules, order:
cameras → printers → relay → Dahua → DT-008 set-IP); open question #19; [[device-discovery]] and
[[index]] updated.
## [2026-10-08] query | Container log noise on a quiet booth
park-2 right after redeploy: 128 server + 160 vision lines in 15 min, ~90 % health probes
(Docker HEALTHCHECK every 30 s; the footer chip polling vision every 8 s) logged at info. Fixed in
code, not by level: `/health` silent on both services, one request line instead of two (with an
`onError` hook so 5xx keep logging under `disableRequestLogging`), hik-alarm HIT and per-snapshot
byte lines demoted to debug via a level on `stubLog`. Pages: [[app-logs]] §Noise cut.
- 2026-10-08 — **stage-1167e27 never built**: the code fix and the TAG bump were pushed together, so CI tagged the image with the push head (`stage-32b4d9e`); Komodo deploy failed "not found". Re-pinned all four stacks to `stage-32b4d9e`; rule added to [[fleet-deployment-komodo]] (push code first, bump after the build).
## [2026-10-08] query | Review outbox never delivered — missing Netbird policy, not code
A month of silence from the collector: park-2 had 22 entry samples `queued`, all `fetch failed`
(`ENOTFOUND docker-station.nb.infra`). park-2's Netbird peer list had no docker-station and vice
versa — no policy booths → collector host. User added the access in the Netbird dashboard; the
first package went out at its next scheduled retry (16:49Z) and the collector logged the ingest.
Also clarified why camera traffic ≠ samples (only session-tied reads are sampled; barriers were
open, so almost no tickets). Troubleshooting checklist added to [[vision-review-outbox]].
## [2026-10-08] ingest | park-2 camera port forward through the booth host (iptables)
8081 → entry camera 10.0.10.9:80, 8082 → exit camera 10.0.10.10:80, DNAT + SNAT + FORWARD
ACCEPTs on park-2 (Docker's FORWARD DROP policy makes the ACCEPTs mandatory). Reachable over
Netbird as `park-2.nb.infra:8081/8082`; public only if the router forwards to 192.168.1.101.
Procedure, undo and the Netbird-only variant in [[site-device-installation]] §7.
## [2026-10-08] ingest | Review outbox: sample every detected car, not only ticketed entries
User: "I need every car that passes to be pushed to the server" — park-2's barriers were up, so
hundreds of camera pushes produced no session-tied reads and no samples. The ANPR bridge now
records one PASS sample per detection (best-framed vehicle of its poll loop → stored snapshot
`pass:<id>` + vehicle read with `deviceId`); the Car Wash sampler dedups per camera for 30 s so a
ticketed car is not sent twice. Also flushed park-2's 21 backed-off rows (`next_attempt_at = now`)
so the reviewer got the day's backlog at once. Pages: [[vision-review-outbox]] §entry stream.
## [2026-10-08] decision | Forgiven exit (owner opens the exit barrier, no money)
Discussed, narrowed to EXIT only, pinned as [[forgiven-exit]] (status: decided, not built):
zero-amount signed payment carrying `forgoneMinor` as its own Z-report line so the shift's
cash/card/drawer are untouched by construction; no-session cars get an anomaly + pulse; admin
permission, open shift, mandatory reason, prints nothing, no cap. Entry side rejected.
## [2026-10-08] ingest | Forgiven exit built (barrier:create)
"Ok, can we implement that? But the owner can give permission to other operators to do
that." Built per [[forgiven-exit]]: new permission `barrier:create` (grantable per role),
`PayStation.forgive` ($0 payment carrying `forgoneMinor`, no tender, refuses wash charges),
`ExitFlow.reopenBarrier(..., { forgiven })` + `forgiveExitNoSession`, route
`POST /api/barrier/forgive`, Z-report `forgoneTotalMinor`/`forgoneCount` + print line, modal
"Forgive & open" + booth-header "Forgive & open exit" (no ticket), en/sq. Prints nothing.
Pages: [[forgiven-exit]], [[booth-exit-flow]] §Forgiven exit, [[shift]] §Forgiven exits.
## [2026-10-09] decision | Forgiven exit: reason is optional
"We don't need to force the user to write a reason." Route no longer 400s without a note; an
empty note is signed as "(no reason given)"; modal confirm enabled with an empty box; booth
prompt: Cancel aborts, empty proceeds; en/sq texts say optional. [[forgiven-exit]] §5 updated.
## [2026-10-09] decision | Forgiven exit wording → "manual exit" / "dalje manuale"
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.
+307
View File
@@ -0,0 +1,307 @@
# Dingtian QR code / RFID reader – configuration protocol
Reverse engineered from `QRCode_v1_6_5.exe` (Dingtian-Tech QRCode V1.6.5, statically
linked Qt 5 Win32 application) by static analysis of the binary plus packet captures
against a real reader (serial HC002721, model `doorqrcode`, firmware `ver_client1_1.1`,
chip `v3s`, hardware `h42`) and a fake reader used to exercise the Set buttons.
`dingtian_qr.py` in this folder is a working, dependency-free Python 3 implementation
(discover / info / get / set / set-network) that runs on Linux.
## 1. What the exe does
The exe has two tabs.
* **Setting** – the configuration tool. It talks to readers over **UDP**:
* `Search device` broadcasts command 2 to `<interface broadcast>:24582` on every
local IPv4 interface. Readers answer with command 3 (96 byte DeviceInfo block).
Discovered readers are kept in an in-memory list (one 768 byte record per reader)
and shown by serial number.
* `Get parameter` sends commands 0 and 30 unicast to `<reader ip>:24680` and fills the
form from the 64 byte firmware block and the 720 byte parameter struct.
* The three `Set` buttons send a fixed sequence of small commands (below). Each write
is acknowledged by the reader with `cmd+1` and a 1 byte status (0 = OK); the exe
prints "... success!" when the acknowledgement arrives.
* The form shows the *stored record* of the selected reader. A new record is filled
with built-in defaults until a Get parameter reply has been received, which is the
behaviour you see as "the UI does not show the selected device params". Reading the
parameters directly (command 30) every time avoids this.
* **Test device** – a tiny HTTP (or raw TCP / UDP) server on a configurable port
(default 80) that receives the scan pushes the reader makes in HTTP output mode and
answers with the JSON documented in the SDK (`qrcode_HTTP_GET.txt`). The "TCP" and
"UDP" listener types of that tab were not analysed. The HTTP push is:
`GET /qa/mcardsea.php?cardid=<data>&mjihao=<device id>&cjihao=<serial>&status=<2 digits>&time=<unix>`
and the reply is
`{"data":[{"cardid":"...","cjihao":"...","mjihao":"...","status":1,"time":<unix>,"output":0}],"code":0,"message":"success"}`
(status 1 = valid, beep twice; 0 = invalid, beep once; `time` syncs the reader clock;
`output` 0 access, 1 WG26, 2 WG34). This part is independent of the UDP protocol.
The reader's default IP is 192.168.1.99 (see `readme.txt`). A reset hole on the back
restores factory settings.
## 2. Frame format (UDP, both directions)
```
offset size field notes
0 4 'XXXX' magic (0x58 0x58 0x58 0x58)
4 4 id little-endian u32; PC sends 0, reader echoes an arbitrary value
8 4 cmd little-endian u32; even = request/write, odd = reply (cmd + 1)
12 4 len little-endian u32; payload length in bytes
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF -> 0xFF when len == 0
17 len payload
```
All integers are little-endian. The exe sends the header and the payload as **two
separate datagrams** (17 byte header, then the raw payload). Reader replies arrive as a
single datagram (header + payload). The Python tool mimics the two-datagram write.
Ports: reader listens on **24680/udp** (unicast) and **24582/udp** (broadcast, used for
search and set-network). Replies are sent to the IP:port the request came from, but the
reader's *source* port is not fixed: unicast replies came from 24680, search replies came
from an ephemeral port (52512 in the capture). A host firewall therefore has to allow
inbound UDP to the tool's socket (or track UDP "related" traffic); filtering on the
reader's source port does not work.
Broadcast address: the exe computes `ip | ~netmask` for every local IPv4 interface and
sends the search to each one (it does not use 255.255.255.255). Readers and PC must be on
the same layer 2 segment for search and set-network; get/set commands are plain unicast
and are routable. The exe also binds its own socket to 24582 so it can receive readers
that announce themselves; two copies of the exe on one PC therefore fight over that port.
### Worked examples
Search request, no payload (checksum of nothing = 0xFF):
```
58 58 58 58 00 00 00 00 02 00 00 00 00 00 00 00 ff
magic id = 0 cmd = 2 len = 0 checksum
```
Set buzzer on (command 18, payload = u32 1): payload bytes sum to 1, checksum = 0xFF - 1 = 0xFE.
Sent as two datagrams:
```
datagram 1: 58 58 58 58 00 00 00 00 12 00 00 00 04 00 00 00 fe
datagram 2: 01 00 00 00
```
Reader acknowledgement (cmd 19 = 18 + 1, one status byte 0x00, checksum 0xFF - 0 = 0xFF):
```
58 58 58 58 00 00 00 00 13 00 00 00 01 00 00 00 ff 00
```
Only status 0 has been observed; treat anything else as an error.
Set card prefix "AB" with ASCII type (command 44, 72 byte payload):
```
01 00 00 00 card output format = 1 (ASCII)
01 00 00 00 card prefix/suffix type = 1 (ASCII)
41 42 00 .. 00 prefix "AB", 32 bytes NUL padded
00 00 .. 00 suffix empty, 32 bytes
```
Python reference: `checksum = (0xFF - sum(payload)) & 0xFF`;
`header = b'XXXX' + struct.pack('<III', 0, cmd, len(payload)) + bytes([checksum])`.
## 3. Commands
| cmd | dir | payload | meaning |
|----:|-----|---------|---------|
| 2 | PC → bcast :24582 | none | search; every reader replies with 3 |
| 3 | reader → PC | 96 B DeviceInfo | search reply |
| 0 | PC → reader | none | firmware info; reply 1 |
| 1 | reader → PC | 64 B FirmwareInfo | |
| 30 | PC → reader | none | get parameters; reply 31 |
| 31 | reader → PC | 720 B Params | |
| 32 | PC → bcast :24582 | 96 B DeviceInfo | set network parameters. Reader matches the serial in the block. Reply 33 |
| 6 | PC → reader | u32 | output type (1..10, table below) |
| 8 | PC → reader | u32 | card input format (1..5) |
| 10 | PC → reader | u32 | byte0 = "last add Enter" (0/1), byte1 = "last add new line" (0/1) |
| 38 | PC → reader | 5 × u32 | baud, data bits (5..8), stop bits (1/2), parity (0..4), QR output format (0..4) |
| 12 | PC → reader | u32 + 32 B | QR prefix/suffix type (0 HEX, 1 ASCII) + QR prefix (raw bytes, NUL padded) |
| 14 | PC → reader | u32 + 32 B | same type value + QR suffix |
| 44 | PC → reader | u32, u32, 32 B, 32 B | card output format (0 HEX, 1 ASCII), card prefix/suffix type (0 HEX, 1 ASCII), card prefix, card suffix |
| 28 | PC → reader | 2 × u32 | Wiegand high pulse / 100, low pulse / 100 (microseconds; UI shows 2000 / 400) |
| 40 | PC → reader | u32 | scan code fill light: 0 close, 1 open (Params 0x218) |
| 18 | PC → reader | u32 | work mode: 0 normal, 1 single, 2 interval (Params 0x1f0) |
| 16 | PC → reader | u32 | restart interval: 0 no, 1 every 12 h, 2 every 24 h (Params 0x1ec; the test reader rejected 2) |
| 22 | PC → reader | u32 | buzzer: 0 off, 1 on (Params 0x1f8) |
Every write is answered with `cmd+1`, `len = 1`, payload = 1 status byte:
`00` = value applied (the parameter struct changes immediately, no commit or reboot
needed), `01` = value rejected (out of range), struct unchanged. A write whose header
and payload are sent in **one** datagram gets no answer and is ignored.
The 18/22 and 40/16 assignments were confirmed on the real reader by sending each
command alone and diffing the 720 byte struct afterwards (the exe's two Set passes
alone could not tell them apart because both fields of each pair changed together).
Button → command sequence in the exe:
* **Network Set**: 32 (broadcast).
* **Format Set**: 6, 8, 10, 38, 12, 14, 44, 28 (in this order, back to back).
* **External Set**: 40, 18, 16, 22.
The exe's receive dispatcher accepts reply commands 1..41; other odd commands exist in
the jump table but are not used by the UI.
### Enumerations (values as sent on the wire)
| field | values |
|-------|--------|
| output type (cmd 6, Params 0x198) | 1 USB virtual keyboard, 2 USB virtual serial port, 3 HTTP, 4 MQTT, 5 RS232, 6 WG26, 7 WG34, 8 RS485, 9 AC Output, 10 TCP |
| card input format (cmd 8, Params 0x19c) | 1 6H, 2 8H, 3 8H10D, 4 6H10D, 5 2H3D+4H5D |
| QR output format (cmd 38[4], Params 0x214) | 0 Decimal, 1 HEX, 2 Decimal Reverse, 3 HEX Reverse, 4 ASCII |
| prefix/suffix type, card output format | 0 HEX, 1 ASCII (HEX only changes how the exe displays/enters the bytes; the wire always carries raw bytes) |
| parity (cmd 38[3], Params 0x210) | 0 Even, 1 Odd, 2 None, 3 Space, 4 Mark |
| baud (cmd 38[0]) | actual value; exe list: 110 134 150 300 600 1200 1800 2400 4800 7200 9600 14400 19200 38400 57600 115200 128000 256000 |
| restart interval | 0 No, 1 12Hours, 2 24Hours |
| work mode | 0 Normal, 1 Single, 2 Interval |
| buzzer | 0 Off, 1 On |
| fill light | 0 Close, 1 Open |
| DHCP (Params 0x000) | 0 Static IP, 1 DHCP |
| HTTP server language (Params 0x04c, DeviceInfo 92) | 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI |
## 4. Data blocks
IPv4 addresses are stored as a little-endian u32, i.e. the bytes of `inet_aton()`
reversed: 10.0.10.12 is `0c 0a 00 0a`.
### DeviceInfo – 96 bytes (reply 3, payload of 32)
```
0 20 serial number, NUL padded ASCII ("HC002721")
20 4 ip
24 4 netmask
28 4 gateway
32 4 dns1
36 4 dns2
40 48 server address, NUL padded string (hostname or IP, e.g. "10.0.10.204";
factory default is "ipc.fondvision.com")
88 4 server port (u32, e.g. 8080)
92 4 HTTP server language (0 PHP .. 4 CGI)
```
Note: the exe's set-network code builds this block by writing the 20 byte serial over
the first 20 bytes of its 80 byte network record (dhcp, ip, ..., language). The DHCP
word is therefore overwritten by the serial and **DHCP is never transmitted** by the
exe; the DHCP combobox has no effect on the wire.
### FirmwareInfo – 64 bytes (reply 1)
```
0 16 model "doorqrcode"
16 16 firmware "ver_client1_1.1"
32 8 chip "v3s"
40 8 hardware "h42"
48 16 serial "HC002721"
```
### Params – 720 bytes (reply 31)
```
0x000 4 dhcp (0 static, 1 dhcp)
0x004 4 ip
0x008 4 netmask
0x00c 4 gateway
0x010 4 dns1
0x014 4 dns2
0x018 48 server address string
0x048 4 server port
0x04c 4 HTTP server language
0x050 .. 0x197 reserved / zero on the test reader (MQTT and other hidden settings
probably live here; the exe never reads them)
0x198 1 output type (cmd 6)
0x19c 1 card input format (cmd 8)
0x1a0 1 last add Enter (cmd 10 byte 0)
0x1a1 1 last add new line (cmd 10 byte 1)
0x1a4 4 QR prefix/suffix type (cmd 12 word)
0x1a8 32 QR prefix (cmd 12 bytes)
0x1c8 4 QR prefix/suffix type again (cmd 14 word)
0x1cc 32 QR suffix (cmd 14 bytes)
0x1ec 4 restart interval (cmd 16)
0x1f0 4 work mode (cmd 18)
0x1f4 4 unknown (0 on test reader, not shown by the exe)
0x1f8 4 buzzer (cmd 22)
0x1fc 4 high pulse / 100 (cmd 28[0])
0x200 4 low pulse / 100 (cmd 28[1])
0x204 4 baud rate (cmd 38[0])
0x208 4 data bits (cmd 38[1])
0x20c 4 stop bits (cmd 38[2])
0x210 4 parity (cmd 38[3])
0x214 4 QR output format (cmd 38[4])
0x218 4 scan fill light (cmd 40)
0x21c .. 0x287 zero on the test reader
0x288 4 card output format (cmd 44[0])
0x28c 4 card prefix/suffix type (cmd 44[1])
0x290 32 card prefix (cmd 44 bytes 8..39)
0x2b0 32 card suffix (cmd 44 bytes 40..71)
```
Reference capture from the test reader (HTTP mode, server 10.0.10.204:8080, PHP,
card input 8H, add Enter on, 9600 8N1, ASCII formats, pulses 2000/400 µs, restart 12 h,
normal mode, buzzer off, fill light open):
```
0000: 00000000 0c0a000a 00ffffff 010a000a 08080808 04040808 "10.0.10.204"...
0048: 901f0000 00000000 ...
0198: 03 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 ...
01c8: 01 00 00 00 ...
01ec: 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
01fc: 14 00 00 00 04 00 00 00 80 25 00 00 08 00 00 00 01 00 00 00 02 00 00 00 04 00 00 00 01 00 00 00
0288: 01 00 00 00 01 00 00 00 ...
```
## 5. Implementation notes for other tools
* Build the header with the checksum of the payload, send header then payload (two
datagrams), then wait for a datagram whose command equals `cmd + 1`. The exe does not
retry; the Python tool retries twice with a 2 s timeout.
* Discovery: send command 2 to the subnet broadcast, collect command 3 replies for about
2 s, de-duplicate by serial. The reply block already contains the IP to use for
unicast commands.
* Reading: command 30 is enough for the whole form; command 0 only adds firmware info.
* Writing a single field: there is no "write the whole struct" command. Read the struct
first, then send only the small command that owns the field (table in section 3).
Commands 38, 12, 14 and 44 carry several fields at once, so fill the untouched ones
from the struct you just read.
* Changing IP/server: broadcast command 32 with the 96 byte block; the serial selects the
reader. Expect the reader to answer 33 (not captured on the real unit because that
would have changed its configuration).
* Prefix/suffix fields are raw bytes (max 32). "HEX" vs "ASCII" type only tells the
reader (and the exe's form) how to interpret them.
* Pulse widths are stored in units of 100 µs (2000 µs on the wire is 20).
## 6. Verification status
* Search, firmware info, get parameters and the acknowledgement format were captured
from the real reader and reproduced with `dingtian_qr.py`.
* The write payloads (commands 6, 8, 10, 12, 14, 16, 18, 22, 28, 32, 38, 40, 44) were
captured from the exe while it talked to a fake reader, with two different sets of
form values, and matched against the parameter struct and the disassembly.
* Real writes verified on the HC002721 reader: commands 18, 22 and 40 each change
exactly the struct word listed above and are acknowledged with status 0; out-of-range
values (22 ← 2, 16 ← 2) are acknowledged with status 1 and change nothing; a
single-datagram frame is ignored. The reader was restored to its original
configuration afterwards (struct byte-identical to the first capture).
* Not verified on a real reader: the Format commands (6, 8, 10, 12, 14, 28, 38, 44) and
set-network (32); their byte layouts are identical to the exe's.
* Not understood: Params 0x1f4, the reserved area 0x050..0x197 (likely MQTT settings),
and what the reader does with a DHCP = 1 flag.
## 7. Linux quick start
```
python3 dingtian_qr.py discover --broadcast 192.168.1.255
python3 dingtian_qr.py info 192.168.1.99
python3 dingtian_qr.py get 192.168.1.99
python3 dingtian_qr.py set 192.168.1.99 --output-type 3 --buzzer 1 --fill-light 1
python3 dingtian_qr.py set-network --serial HC002721 --ip 192.168.1.50 --netmask 255.255.255.0 \
--gateway 192.168.1.1 --dns1 8.8.8.8 --dns2 8.8.4.4 --server 192.168.1.10 --server-port 8080 \
--http-language 0 --broadcast 192.168.1.255
```
`set` reads the current parameters first and only changes the fields you pass, then
sends the full Format and External sequences exactly like the exe.
+63
View File
@@ -0,0 +1,63 @@
# Dingtian QR reader – Linux configuration tool
Replacement for the Windows-only `QRCode_v1_6_5.exe` shipped in the Dingtian QR code
reader SDK. Lets you find readers on the LAN, read their configuration and change
network, output-format and behaviour settings from Linux (or any OS with Python 3).
| file | purpose |
|------|---------|
| `PROTOCOL.md` | the reverse engineered UDP protocol: frame format, command list, field tables, 720 byte parameter struct, verification status |
| `dingtian_qr.py` | reference implementation and CLI (`discover`, `info`, `get`, `set`, `set-network`); importable as a module |
## Requirements
* Python 3.6 or newer, standard library only.
* The PC must be on the same layer 2 network as the readers for `discover` and
`set-network` (they use UDP broadcast). `info`, `get` and `set` are unicast and work
across routers.
* Host firewall: allow inbound UDP replies to the tool's socket. Readers reply from
arbitrary source ports, so do not filter on the reader's source port.
## Usage
```
python3 dingtian_qr.py discover --broadcast 192.168.1.255 # list readers (serial, ip, server...)
python3 dingtian_qr.py info 192.168.1.99 # model / firmware / serial
python3 dingtian_qr.py get 192.168.1.99 # full configuration (add --raw for numeric codes)
python3 dingtian_qr.py set 192.168.1.99 --output-type 3 --buzzer 1 --qr-suffix "hex:0d"
python3 dingtian_qr.py set-network --serial HC002721 --ip 192.168.1.50 --netmask 255.255.255.0 \
--gateway 192.168.1.1 --dns1 8.8.8.8 --dns2 8.8.4.4 --server 192.168.1.10 \
--server-port 8080 --http-language 0 --broadcast 192.168.1.255
python3 dingtian_qr.py set --help # every field with its numeric codes
```
`set` reads the current configuration first and only changes the fields you pass; it
then sends the same command sequence as the exe's Set button that owns those fields
(Format group and/or External group). `set-network`
broadcasts and the reader whose serial matches applies the new values, so it also works
for a reader whose current IP is in the wrong subnet.
A factory reset (pin in the RESET hole on the back) returns the reader to 192.168.1.99.
## Using it from your own code
```python
import dingtian_qr as dq
for ip, info in dq.discover(broadcast='192.168.1.255'):
print(info['serial'], ip)
params = dq.get_params('192.168.1.99') # dict, keys documented in parse_params()
params['output_type'] = 3 # HTTP
params['buzzer'] = 1
dq.set_format('192.168.1.99', params) # commands 6,8,10,38,12,14,44,28
dq.set_external('192.168.1.99', params) # commands 40,18,16,22
```
## Caveats
* The DHCP setting cannot be written: the original exe never transmits it (see
PROTOCOL.md), so the reader's behaviour for it is unknown.
* The External commands (buzzer, work mode, fill light, restart interval) were verified
on a real reader. The Format commands and set-network were validated only against
the exe's own packets and a simulated reader. Test on one reader before rolling out.
* Parameter struct words 0x1f4 and the area 0x050–0x197 are not understood (the exe
does not use them either).
+485
View File
@@ -0,0 +1,485 @@
#!/usr/bin/env python3
"""
dingtian_qr.py - cross-platform (Linux/Windows/macOS) command line tool for
Dingtian QR code / RFID readers. Replacement for the Windows-only
QRCode_v1_6_5.exe configuration tool. Pure Python 3, no dependencies.
Protocol (reverse engineered from QRCode_v1_6_5.exe + packet captures, Oct 2026)
---------------------------------------------------------------------------------
Transport: UDP. The reader listens on 24680 (unicast commands) and 24582
(broadcast search / network set). Every message starts with a 17 byte header:
off size field notes
0 4 'XXXX' magic
4 4 id LE u32, PC sends 0, reader echoes an arbitrary value
8 4 cmd LE u32, even = request, odd (cmd+1) = reply
12 4 len LE u32, payload length
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF (0xFF when no payload)
17 payload
The Windows tool sends header and payload as TWO datagrams (17 byte header
first, then the raw payload). Reader replies are a single datagram.
Commands:
2 search broadcast to :24582, no payload -> 3 96 byte DeviceInfo
0 firmware info no payload -> 1 64 bytes
30 get parameters no payload -> 31 720 byte Params
32 set network broadcast to :24582, 96 byte DeviceInfo (reader matches serial)
6 output type u32 1..10 (OUTPUT_TYPES)
8 card input format u32 1..5 (CARD_INPUT)
10 enter / newline u32 = add_enter | (add_newline << 8)
38 serial + QR format 5 x u32: baud, data bits, stop bits, parity, qr_output_format
12 QR prefix u32 prefix/suffix type (0 HEX, 1 ASCII) + 32 raw bytes
14 QR suffix u32 prefix/suffix type (same value) + 32 raw bytes
44 card output u32 card_output_format (0 HEX,1 ASCII), u32 prefix/suffix type,
32 bytes prefix, 32 bytes suffix
28 wiegand pulses 2 x u32: high_pulse/100, low_pulse/100 (units of 100 us)
40 scan fill light u32 0 close, 1 open
18 work mode u32 0 normal, 1 single, 2 interval
16 restart interval u32 0 no, 1 every 12 h, 2 every 24 h
22 buzzer u32 0 off, 1 on
Every write is acknowledged with cmd+1 and a one byte status: 0 = applied,
1 = rejected (value out of range). A frame sent as ONE datagram (header+payload
together) is ignored by the reader, so the two-datagram form is mandatory.
"""
import argparse
import json
import socket
import struct
import sys
import time
PORT_UNICAST = 24680
PORT_BCAST = 24582
MAGIC = b'XXXX'
OUTPUT_TYPES = {1: 'USB virtual keyboard', 2: 'USB virtual serial port', 3: 'HTTP', 4: 'MQTT',
5: 'RS232', 6: 'WG26', 7: 'WG34', 8: 'RS485', 9: 'AC Output', 10: 'TCP'}
CARD_INPUT = {1: '6H', 2: '8H', 3: '8H10D', 4: '6H10D', 5: '2H3D+4H5D'}
QR_FORMAT = {0: 'Decimal', 1: 'HEX', 2: 'Decimal Reverse', 3: 'HEX Reverse', 4: 'ASCII'}
HEX_ASCII = {0: 'HEX', 1: 'ASCII'}
PARITY = {0: 'Even', 1: 'Odd', 2: 'None', 3: 'Space', 4: 'Mark'}
RESTART = {0: 'No', 1: '12Hours', 2: '24Hours'}
WORKMODE = {0: 'Normal', 1: 'Single', 2: 'Interval'}
ONOFF = {0: 'Off', 1: 'On'}
FILL_LIGHT = {0: 'Close', 1: 'Open'}
DHCP = {0: 'Static IP', 1: 'DHCP'}
HTTP_LANG = {0: 'PHP', 1: 'JSP', 2: 'C#', 3: 'ASP', 4: 'CGI'}
# ---------------------------------------------------------------- framing
def checksum(payload):
return (0xFF - sum(payload)) & 0xFF
def header(cmd, payload=b'', ident=0):
return MAGIC + struct.pack('<III', ident, cmd, len(payload)) + bytes([checksum(payload)])
def parse(datagram):
"""Return (ident, cmd, payload) or None if the datagram is not a valid frame."""
if len(datagram) < 17 or datagram[:4] != MAGIC:
return None
ident, cmd, ln = struct.unpack_from('<III', datagram, 4)
payload = datagram[17:17 + ln]
if len(payload) != ln or checksum(payload) != datagram[16]:
return None
return ident, cmd, payload
def send(sock, addr, cmd, payload=b''):
"""Send exactly like the Windows tool: header datagram first, then payload datagram."""
sock.sendto(header(cmd, payload), addr)
if payload:
sock.sendto(payload, addr)
def ip2b(s):
"""IPv4 as stored by the reader: little-endian u32 (= inet_aton reversed)."""
return socket.inet_aton(s)[::-1]
def b2ip(b):
return socket.inet_ntoa(bytes(b[:4])[::-1])
def cstr(b):
return bytes(b).split(b'\0', 1)[0].decode('utf-8', 'replace')
def u32(b, off):
return struct.unpack_from('<I', b, off)[0]
# ---------------------------------------------------------------- blocks
def parse_device_info(d):
"""96 byte block: search reply (cmd 3) and set-network payload (cmd 32)."""
return {
'serial': cstr(d[0:20]),
'ip': b2ip(d[20:24]), 'netmask': b2ip(d[24:28]), 'gateway': b2ip(d[28:32]),
'dns1': b2ip(d[32:36]), 'dns2': b2ip(d[36:40]),
'server': cstr(d[40:88]),
'server_port': u32(d, 88),
'http_language': u32(d, 92),
}
def build_device_info(serial, ip, netmask, gateway, dns1, dns2, server, server_port, http_language=0):
d = bytearray(96)
d[0:20] = serial.encode()[:20].ljust(20, b'\0')
d[20:24] = ip2b(ip)
d[24:28] = ip2b(netmask)
d[28:32] = ip2b(gateway)
d[32:36] = ip2b(dns1)
d[36:40] = ip2b(dns2)
d[40:88] = server.encode()[:47].ljust(48, b'\0')
d[88:92] = struct.pack('<I', server_port)
d[92:96] = struct.pack('<I', http_language)
return bytes(d)
def parse_firmware(d):
return {'model': cstr(d[0:16]), 'firmware': cstr(d[16:32]), 'chip': cstr(d[32:40]),
'hardware': cstr(d[40:48]), 'serial': cstr(d[48:64])}
def parse_params(d):
"""720 byte parameter struct (reply 31 to cmd 30)."""
return {
'dhcp': u32(d, 0x000),
'ip': b2ip(d[0x004:0x008]),
'netmask': b2ip(d[0x008:0x00c]),
'gateway': b2ip(d[0x00c:0x010]),
'dns1': b2ip(d[0x010:0x014]),
'dns2': b2ip(d[0x014:0x018]),
'server': cstr(d[0x018:0x048]),
'server_port': u32(d, 0x048),
'http_language': u32(d, 0x04c),
'output_type': d[0x198],
'card_input_format': d[0x19c],
'last_add_enter': d[0x1a0],
'last_add_newline': d[0x1a1],
'qr_prefix_type': u32(d, 0x1a4), # 0 HEX / 1 ASCII
'qr_prefix': bytes(d[0x1a8:0x1c8]).rstrip(b'\0'),
'qr_suffix_type': u32(d, 0x1c8), # written with the same value as qr_prefix_type
'qr_suffix': bytes(d[0x1cc:0x1ec]).rstrip(b'\0'),
'restart_interval': u32(d, 0x1ec),
'work_mode': u32(d, 0x1f0),
'unknown_1f4': u32(d, 0x1f4),
'buzzer': u32(d, 0x1f8),
'high_pulse_us': u32(d, 0x1fc) * 100,
'low_pulse_us': u32(d, 0x200) * 100,
'baudrate': u32(d, 0x204),
'data_bits': u32(d, 0x208),
'stop_bits': u32(d, 0x20c),
'parity': u32(d, 0x210),
'qr_output_format': u32(d, 0x214),
'fill_light': u32(d, 0x218),
'card_output_format': u32(d, 0x288), # 0 HEX / 1 ASCII
'card_prefix_type': u32(d, 0x28c), # 0 HEX / 1 ASCII
'card_prefix': bytes(d[0x290:0x2b0]).rstrip(b'\0'),
'card_suffix': bytes(d[0x2b0:0x2d0]).rstrip(b'\0'),
}
def describe(p):
"""Human readable version of parse_params()."""
out = dict(p)
out['dhcp'] = DHCP.get(p['dhcp'], p['dhcp'])
out['http_language'] = HTTP_LANG.get(p['http_language'], p['http_language'])
out['output_type'] = OUTPUT_TYPES.get(p['output_type'], p['output_type'])
out['card_input_format'] = CARD_INPUT.get(p['card_input_format'], p['card_input_format'])
out['qr_prefix_type'] = HEX_ASCII.get(p['qr_prefix_type'], p['qr_prefix_type'])
out['qr_suffix_type'] = HEX_ASCII.get(p['qr_suffix_type'], p['qr_suffix_type'])
out['restart_interval'] = RESTART.get(p['restart_interval'], p['restart_interval'])
out['work_mode'] = WORKMODE.get(p['work_mode'], p['work_mode'])
out['buzzer'] = ONOFF.get(p['buzzer'], p['buzzer'])
out['parity'] = PARITY.get(p['parity'], p['parity'])
out['qr_output_format'] = QR_FORMAT.get(p['qr_output_format'], p['qr_output_format'])
out['fill_light'] = FILL_LIGHT.get(p['fill_light'], p['fill_light'])
out['card_output_format'] = HEX_ASCII.get(p['card_output_format'], p['card_output_format'])
out['card_prefix_type'] = HEX_ASCII.get(p['card_prefix_type'], p['card_prefix_type'])
for k in ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix'):
out[k] = p[k].decode('utf-8', 'replace') if p[k] else ''
if p[k]:
out[k + '_hex'] = p[k].hex()
return out
# ---------------------------------------------------------------- transport helpers
def open_socket(timeout=1.0, bind_ip='0.0.0.0'):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((bind_ip, 0))
s.settimeout(timeout)
return s
def discover(timeout=2.0, broadcast='255.255.255.255', bind_ip='0.0.0.0'):
"""Broadcast cmd 2 and collect cmd 3 replies. Returns list of (reply_ip, DeviceInfo)."""
s = open_socket(timeout, bind_ip)
send(s, (broadcast, PORT_BCAST), 2)
found = {}
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == 3 and len(f[2]) >= 96:
info = parse_device_info(f[2])
found[info['serial']] = (addr[0], info)
s.close()
return list(found.values())
def request(ip, cmd, payload=b'', expect=None, timeout=2.0, retries=2):
"""Send a unicast command and wait for the reply (cmd + 1 unless `expect` given).
Returns the reply payload or None on timeout. For write commands the payload is
one status byte: b'\\x00' = applied, b'\\x01' = rejected."""
expect = cmd + 1 if expect is None else expect
s = open_socket(timeout)
try:
for _ in range(retries + 1):
send(s, (ip, PORT_UNICAST), cmd, payload)
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == expect:
return f[2]
return None
finally:
s.close()
def get_firmware(ip):
d = request(ip, 0)
return parse_firmware(d) if d else None
def get_params(ip):
d = request(ip, 30)
return parse_params(d) if d else None
# ---------------------------------------------------------------- set commands
def _set(ip, cmd, payload, wait):
"""Write command; True only if the reader acknowledged with status 0."""
if wait:
r = request(ip, cmd, payload)
if r is None:
print('cmd %d: no acknowledgement' % cmd, file=sys.stderr)
elif r != b'\x00':
print('cmd %d: rejected by reader (status %s)' % (cmd, r.hex()), file=sys.stderr)
return r == b'\x00'
s = open_socket()
send(s, (ip, PORT_UNICAST), cmd, payload)
s.close()
return True
def set_simple(ip, cmd, value, wait=True):
return _set(ip, cmd, struct.pack('<I', value & 0xFFFFFFFF), wait)
def _pad32(b):
return bytes(b)[:32].ljust(32, b'\0')
def set_format(ip, p, wait=True):
"""Send the eight commands behind the 'Format parameter' Set button.
p: dict with parse_params() keys."""
ok = True
ok &= set_simple(ip, 6, p['output_type'], wait)
ok &= set_simple(ip, 8, p['card_input_format'], wait)
ok &= set_simple(ip, 10, (p['last_add_enter'] & 0xff) | ((p['last_add_newline'] & 0xff) << 8), wait)
ok &= _set(ip, 38, struct.pack('<5I', p['baudrate'], p['data_bits'], p['stop_bits'],
p['parity'], p['qr_output_format']), wait)
ok &= _set(ip, 12, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_prefix']), wait)
ok &= _set(ip, 14, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_suffix']), wait)
ok &= _set(ip, 44, struct.pack('<II', p['card_output_format'], p['card_prefix_type'])
+ _pad32(p['card_prefix']) + _pad32(p['card_suffix']), wait)
ok &= _set(ip, 28, struct.pack('<II', p['high_pulse_us'] // 100, p['low_pulse_us'] // 100), wait)
return bool(ok)
def set_external(ip, p, wait=True):
"""Send the four commands behind the 'External parameter' Set button."""
ok = True
ok &= set_simple(ip, 40, p['fill_light'], wait) # -> Params 0x218
ok &= set_simple(ip, 18, p['work_mode'], wait) # -> Params 0x1f0 (verified on real reader)
ok &= set_simple(ip, 16, p['restart_interval'], wait) # -> Params 0x1ec
ok &= set_simple(ip, 22, p['buzzer'], wait) # -> Params 0x1f8 (verified on real reader)
return bool(ok)
def set_network(info, broadcast='255.255.255.255', timeout=2.0):
"""Broadcast cmd 32 with a DeviceInfo block; the reader whose serial matches applies it.
Returns (addr, payload) of a cmd 33 reply, or None."""
payload = build_device_info(info['serial'], info['ip'], info['netmask'], info['gateway'],
info['dns1'], info['dns2'], info['server'], info['server_port'],
info.get('http_language', 0))
s = open_socket(timeout)
send(s, (broadcast, PORT_BCAST), 32, payload)
got = None
end = time.time() + timeout
while time.time() < end:
try:
data, addr = s.recvfrom(65535)
except socket.timeout:
break
f = parse(data)
if f and f[1] == 33:
got = (addr, f[2])
break
s.close()
return got
# ---------------------------------------------------------------- CLI
SET_FIELDS_INT = ('output_type', 'card_input_format', 'last_add_enter', 'last_add_newline', 'baudrate',
'data_bits', 'stop_bits', 'parity', 'qr_output_format', 'qr_prefix_type',
'card_output_format', 'card_prefix_type', 'high_pulse_us', 'low_pulse_us',
'fill_light', 'buzzer', 'restart_interval', 'work_mode')
SET_FIELDS_STR = ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix')
EXTERNAL_FIELDS = ('fill_light', 'buzzer', 'restart_interval', 'work_mode') # External Set button
# everything else in SET_FIELDS_INT / SET_FIELDS_STR belongs to the Format Set button
def _enum_help(table):
return ', '.join('%d %s' % (k, v) for k, v in table.items())
def _parse_bytes(text):
"""CLI prefix/suffix value: plain text, or 'hex:0d0a' for binary bytes. Max 32 bytes."""
if text.lower().startswith('hex:'):
b = bytes.fromhex(text[4:])
else:
b = text.encode('utf-8')
if len(b) > 32:
raise SystemExit('prefix/suffix longer than 32 bytes: %r' % text)
return b
def main(argv=None):
ap = argparse.ArgumentParser(
description='Dingtian QR/RFID reader configuration tool (UDP 24680/24582). '
'See PROTOCOL.md for the wire format.',
epilog='Examples: %(prog)s discover --broadcast 192.168.1.255 | %(prog)s get 192.168.1.99 | '
'%(prog)s set 192.168.1.99 --output-type 3 --buzzer 1')
sub = ap.add_subparsers(dest='cmd', required=True)
d = sub.add_parser('discover', help='broadcast search for readers (cmd 2)')
d.add_argument('--broadcast', default='255.255.255.255', help='broadcast address, e.g. 192.168.1.255')
d.add_argument('--timeout', type=float, default=2.0)
i = sub.add_parser('info', help='firmware info (cmd 0)')
i.add_argument('ip')
g = sub.add_parser('get', help='read all parameters (cmd 30)')
g.add_argument('ip')
g.add_argument('--raw', action='store_true', help='print numeric codes instead of names')
g.add_argument('--hexdump', action='store_true', help='also hexdump the 720 byte struct')
n = sub.add_parser('set-network', help='broadcast new network settings (cmd 32)')
for k in ('serial', 'ip', 'netmask', 'gateway', 'dns1', 'dns2', 'server'):
n.add_argument('--' + k, required=True)
n.add_argument('--server-port', type=int, required=True)
n.add_argument('--http-language', type=int, default=0, help='0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI')
n.add_argument('--broadcast', default='255.255.255.255')
f = sub.add_parser('set', help='change format/external parameters (reads current values first)',
description='Reads the reader\'s current parameters (cmd 30), applies the given '
'changes and sends the full Format (6,8,10,38,12,14,44,28) and '
'External (40,18,16,22) command sequences, exactly like the Windows tool.')
f.add_argument('ip')
helps = {
'output_type': _enum_help(OUTPUT_TYPES), 'card_input_format': _enum_help(CARD_INPUT),
'last_add_enter': '0/1 append Enter after the code', 'last_add_newline': '0/1 append new line',
'baudrate': 'e.g. 9600, 115200', 'data_bits': '5..8', 'stop_bits': '1 or 2',
'parity': _enum_help(PARITY), 'qr_output_format': _enum_help(QR_FORMAT),
'qr_prefix_type': _enum_help(HEX_ASCII) + ' (applies to QR prefix and suffix)',
'card_output_format': _enum_help(HEX_ASCII), 'card_prefix_type': _enum_help(HEX_ASCII),
'high_pulse_us': 'Wiegand high pulse in microseconds (multiple of 100, default 2000)',
'low_pulse_us': 'Wiegand low pulse in microseconds (multiple of 100, default 400)',
'fill_light': _enum_help(FILL_LIGHT), 'buzzer': _enum_help(ONOFF),
'restart_interval': _enum_help(RESTART), 'work_mode': _enum_help(WORKMODE),
}
for k in SET_FIELDS_INT:
f.add_argument('--' + k.replace('_', '-'), type=int, metavar='N', help=helps[k])
for k in SET_FIELDS_STR:
f.add_argument('--' + k.replace('_', '-'), type=str, metavar='TEXT',
help='up to 32 bytes; plain text, or "hex:0d0a" for binary bytes, "" to clear')
f.add_argument('--no-wait', action='store_true', help='do not wait for acknowledgements')
a = ap.parse_args(argv)
if a.cmd == 'discover':
for ip, info in discover(a.timeout, a.broadcast):
print(json.dumps({'reply_from': ip, **info}, indent=2))
return 0
if a.cmd == 'info':
r = get_firmware(a.ip)
print(json.dumps(r, indent=2) if r else 'no reply')
return 0 if r else 1
if a.cmd == 'get':
raw = request(a.ip, 30)
if raw is None:
print('no reply')
return 1
if a.hexdump:
for o in range(0, len(raw), 32):
print('%04x: %s' % (o, raw[o:o + 32].hex(' ')))
p = parse_params(raw)
print(json.dumps(p if a.raw else describe(p), indent=2, default=lambda b: b.hex()))
return 0
if a.cmd == 'set-network':
info = {'serial': a.serial, 'ip': a.ip, 'netmask': a.netmask, 'gateway': a.gateway,
'dns1': a.dns1, 'dns2': a.dns2, 'server': a.server, 'server_port': a.server_port,
'http_language': a.http_language}
r = set_network(info, a.broadcast)
print('acknowledged by', r[0] if r else 'nobody (no cmd 33 reply within timeout)')
return 0 if r else 1
if a.cmd == 'set':
p = get_params(a.ip)
if p is None:
print('no reply from reader')
return 1
fmt_changed = ext_changed = False
for k in SET_FIELDS_INT + SET_FIELDS_STR:
v = getattr(a, k)
if v is None:
continue
p[k] = _parse_bytes(v) if k in SET_FIELDS_STR else v
if k in EXTERNAL_FIELDS:
ext_changed = True
else:
fmt_changed = True
if not (fmt_changed or ext_changed):
print('nothing to change')
return 0
# only the button group(s) that contain a changed field are sent, like pressing that Set button
ok = True
if fmt_changed:
r = set_format(a.ip, p, not a.no_wait)
print('format parameters:', 'ok' if r else 'FAILED')
ok &= r
if ext_changed:
r = set_external(a.ip, p, not a.no_wait)
print('external parameters:', 'ok' if r else 'FAILED')
ok &= r
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())
+39
View File
@@ -0,0 +1,39 @@
---
type: source
tags: [parking, hardware, readers, qr, rfid, dingtian, manual]
sources: [dingtian-dt008-box-manual]
updated: 2026-09-17
---
# Source: DT-008 paper manual from the box ("QR Code Reader Technical Parameter")
Phone-scanned (OCR) from the leaflet packed with the fresh lab unit `HC002721`, 2026-09-17. Verbatim
as OCR'd (typos are the OCR's):
```
QR Code Reader Technical Parameter
Voltage Support: DC 5V-16V
Current: ≤0.75W
Decoding support: QR code, one dimensional code
Reading range: ID 1~10CM, IC 1~5CM
Reading card type: EM-ID, M1, 15693, 125KHZ \ ISO14443A \ ISO14443B \ ISO15693
Application environment: -10°C ~ 60°C
Humidity: 10% ~ 90%
Interface: Wiegand26, 34, RS485, RS232, [USB?]
```
## What it claims that matters
- **All card technologies in one unit:** EM-ID (125 kHz), M1 = Mifare Classic (ISO 14443A),
ISO 14443B, ISO 15693. Range differs by technology: **ID 1–10 cm, IC 1–5 cm**.
- **RS232 is listed** — the earlier wiki position "NOT RS-232, that was a fictional-datasheet claim"
came from the mis-identified GEE PDF; the box leaflet does list it. Irrelevant to us (HTTP push),
but do not treat the interface list as evidence of a mis-id any more.
- Power 5–16 V here vs 9–16 V / 800 mA on the product page ([[dingtian-dt008]]).
## What it does NOT settle
The lab unit does **not** read the park-buzi card set although the leaflet says it reads EM-ID —
see [[dingtian-dt008-reader]] §"Two RF variants". Either the leaflet is generic for the line and
units ship per variant, or the lab unit's 125 kHz front end is dead/disabled, or the park-buzi
cards are a non-EM 125 kHz format (HID Prox / Indala / AWID) that only the older batch decodes.
+86
View File
@@ -0,0 +1,86 @@
---
type: source
tags: [parking, hardware, readers, qr, dingtian, protocol, linux, tooling]
sources: [dingtian-qr-linux-tool]
updated: 2026-10-08
---
# Source: Dingtian QR reader — Linux configuration tool + reversed UDP protocol
`raw/dingtian_qr_linux/` (`README.md`, `PROTOCOL.md`, `dingtian_qr.py`; October 2026). A
reverse engineering of `QRCode_v1_6_5.exe` ([[qrcode-sdk]]) — static analysis of the Qt binary
plus captures against the bench reader `HC002721` and a fake reader — and a dependency-free
Python 3 replacement for the Windows tool. The script is copied to **`scripts/dingtian_qr.py`**
for use on booths. Entity: [[dingtian-dt008-reader]]; runbook: [[site-device-installation]] §2.
## Why it matters
Until now a DT-008's settings (IP, server target, output type, prefixes, card format) could only
be read or changed with the vendor's Windows exe on a laptop plugged into the device VLAN. The
exe's "Search device" / "Get parameter" / "Set" are a small binary **UDP** protocol; `get` and
`set` are **unicast**, so they run from the booth itself over SSH/Netbird. The 2026-10-08
park-2 enrolment failure ([[site-device-installation]] §2 trap) was diagnosed in one command
this way instead of a site visit.
## Protocol (PROTOCOL.md §2–4)
- Frame: `'XXXX'` + id u32 + cmd u32 + len u32 + checksum byte (`0xFF − Σpayload`) + payload;
all little-endian. Even cmd = request, reply = cmd+1.
- **Quirk:** the exe sends header and payload as **two datagrams**; a single-datagram frame is
silently ignored by the reader. The script mimics this.
- Ports: reader listens on **24680/udp** (unicast: 0 firmware info → 64 B, 30 get params →
720 B struct, every write) and **24582/udp** (broadcast: 2 search → 3 with a 96 B DeviceInfo,
32 set-network matched by serial). Replies come from arbitrary source ports — a host firewall
must allow inbound UDP to the tool's socket.
- Writes: one small command per field group (6 output type, 8 card input format, 10 enter/
newline, 38 serial+QR format, 12/14 QR prefix/suffix, 44 card output+prefix/suffix, 28 Wiegand
pulses; 40 fill light, 18 work mode, 16 restart interval, 22 buzzer). Ack = cmd+1 with one
status byte (0 applied immediately, 1 rejected). The exe's Format Set button sends 6, 8, 10,
38, 12, 14, 44, 28 back to back; External Set sends 40, 18, 16, 22; `set` reproduces whichever
group owns the changed field, after reading the struct so untouched fields are re-sent as-is.
- Enumerations on the wire: output type 1 USB keyboard, 2 USB serial, **3 HTTP**, 4 MQTT,
5 RS232, 6 WG26, 7 WG34, 8 RS485, 9 AC Output, 10 TCP; card input 1 6H, 2 8H, 3 8H10D,
4 6H10D, 5 2H3D+4H5D; HTTP language 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI.
- IPv4 fields are little-endian u32 (bytes of `inet_aton` reversed).
- **DHCP is never transmitted** by the exe (its set-network code overwrites the DHCP word with
the serial) — the combobox has no effect; the script cannot write it either.
- Not understood: Params `0x1f4` and the reserved area `0x050–0x197` (probably MQTT/TCP
settings). **Symbologies are not in this protocol** (the exe has no such field) — the
phantom-read fix in [[dingtian-dt008-reader]] still has no known configuration path.
## Verification status
- By the author: search/info/get and the ack format captured from the real reader; the write
payloads matched against the exe talking to a fake reader; commands 18, 22, 40 proven on the
real reader by diffing the struct.
- **Ours, 2026-10-08, bench `HC002721` @ `10.0.10.12`:** `set --output-type 6` then
`--output-type 3` — all eight Format commands acked with status 0, the diff of the 720 B struct
was exactly byte `0x198` (3 → 6 → 3), final struct byte-identical to the original. So the full
Format sequence (6, 8, 10, 38, 12, 14, 44, 28) is now proven on real hardware too.
- **Ours, park-2, read-only** from the booth over SSH: both readers answered `info` + `get`
(`HC009E84` @ `.7`, `HC00D3B0` @ `.8`, firmware `ver_client1_1.1`, chip `v3s`, hw `h42`).
- Still unverified on a real reader: `set-network` (cmd 32).
## In the app
`packages/devices/src/drivers/dingtian-qr-config.ts` is a TypeScript port of the protocol
(frame, DeviceInfo/Firmware/Params codecs, two-datagram writes, discover, set-network) with a
fake-reader test suite; `reader.ts` uses it for the DT-008 driver's `discover()`,
preconditions and `configureInputPush()` ([[first-run-setup]], [[device-discovery]]). Extra
hardware facts learned while wiring it (2026-10-08, bench HC002721): **cmd 6 alone** (no Format
group) is accepted and applied; **set-network is applied but never acknowledged**, and the
reader answers nothing for ~2–6 s afterwards (poll the params; the driver waits up to 12 s);
the Python and TS tools build byte-identical set-network payloads.
## Usage (from a booth)
```
python3 -I scripts/dingtian_qr.py discover --broadcast 10.0.10.255 # LAN search (same L2 only)
python3 -I scripts/dingtian_qr.py get 10.0.10.7 # full config, human-readable
python3 -I scripts/dingtian_qr.py get 10.0.10.7 --raw --hexdump # numeric codes + 720 B dump
python3 -I scripts/dingtian_qr.py set 10.0.10.7 --output-type 3 # HTTP mode (reads first, re-sends the Format group)
```
Booth hosts ship Python 3 (park-2: 3.14); copy the one file over `scp` and run it on the host
(the server container has no Python). Readers are per-site on `10.0.10.x`; `set-network` needs the
L2 broadcast, so it works from the booth but not across Netbird.
+2 -1
View File
@@ -11,7 +11,8 @@ Vendor SDK for the QR access reader (the Dingtian [[dingtian-dt008-reader]]). De
reader↔server **HTTP protocol** — the missing piece the datasheet omitted. Files at
`QRCode_sdk - QRCode_v1_6_5/sdk/` (config tool `QRCode_v1_6_5.exe`, demos in C#/PHP/VC++, protocol
docs `readme.txt`, `qrcode_HTTP_GET.txt`, `VC++/how to.txt`). **Not copied into `raw/`** — bulky +
binaries; this summary is the faithful capture. Entity: [[dingtian-dt008-reader]].
binaries; this summary is the faithful capture. Entity: [[dingtian-dt008-reader]]. The SDK documents
only the HTTP push; the exe's *configuration* protocol (UDP) is reversed in [[dingtian-qr-linux-tool]].
## The protocol — HTTP GET poll, server replies the verdict