19 Commits

Author SHA1 Message Date
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
57 changed files with 5156 additions and 108 deletions
+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 {
+13
View File
@@ -191,6 +191,14 @@ async function configureDevice(
if (hasPushConfig(device)) {
const host = String(config.host ?? "");
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) {
@@ -211,12 +219,17 @@ async function configureDevice(
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;
}
}
} catch (err) {
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
}
+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
+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>
+3 -3
View File
@@ -532,9 +532,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 +553,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.",
+3 -3
View File
@@ -540,9 +540,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 +561,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:
+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-88f9c53
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-b7efa08
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-88f9c53
# 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-73bfc1d
# 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"],
};
+87 -2
View File
@@ -200,12 +200,97 @@ 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).toEqual({ 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");
});
});
+78 -11
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.
@@ -162,8 +166,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,
@@ -197,7 +201,7 @@ class HikvisionCamera extends HttpCamera {
* explicit offset makes the instant unambiguous regardless of that config.
*/
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}`);
}
@@ -221,7 +225,7 @@ class HikvisionCamera extends HttpCamera {
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
(timeZone ? `<timeZone>${timeZone}</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}`);
}
@@ -230,6 +234,67 @@ class HikvisionCamera extends HttpCamera {
}
}
// --- 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 };
}
}
const channelField: ConfigField = {
key: "channel",
label: "Channel",
@@ -329,15 +394,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)}`,
),
};
@@ -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";
+4
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 {
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()
+18 -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,23 @@ 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.
## UHPPOTE discovery (historical example)
+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).
+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
+304
View File
@@ -0,0 +1,304 @@
---
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.
## 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.**
+20
View File
@@ -154,6 +154,26 @@ 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.
+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)
+12 -1
View File
@@ -193,12 +193,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
+23 -1
View File
@@ -2,7 +2,7 @@
type: decision
tags: [parking, decisions, open]
sources: [parking-system-architecture]
updated: 2026-09-04
updated: 2026-09-08
status: open
---
@@ -148,3 +148,25 @@ 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".
+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]]
+7 -3
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**
+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.
+9 -3
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,6 +69,7 @@ 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).
- [[barrier-not-a-door]] — never timed-close a barrier; safety lives in barrier firmware.
@@ -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.
@@ -137,6 +142,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[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.
+216
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,205 @@ 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]].
+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