3 Commits

Author SHA1 Message Date
julian f4e5c5037b bump(resources): park-buzi, park-2, park-lab and wash-collector to stage-fc93db7 (log noise cut; DT-008 discovery + auto-config)
Build & push images / images (push) Failing after 27s
2026-10-08 16:11:57 +02:00
julian fc93db73c2 fix(logs): silence health probes, one line per request, demote per-event chatter to debug
Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, 60 of them the Docker
HEALTHCHECK's /health logged as "incoming request" + "request completed"; 160 vision lines,
143 of them uvicorn access lines for GET /health (Docker's probe + the booth server's footer
chip polling every 8 s). Levels were never the problem — all of it was info.

- server: /health route logLevel "silent"; disableRequestLogging + an onResponse hook that
  logs one line "METHOD url → status Nms". That flag also stops Fastify's default error
  handler from logging handler errors, so an onError hook logs 5xx with the stack
  (fastify 5.8.5 lib/error-handler.js checks the same flag). Pinned by request-logging.test.ts.
- vision: a logging.Filter on uvicorn.access drops /health access lines (tested).
- devices: stubLog gains a level; the per-snapshot "captureSnapshot (N bytes)" line is
  debug; the hik-alarm HIT line is debug (ACCEPTED/REJECTED carry everything).
  LOG_LEVEL=debug restores all of it. Wiki: app-logs §Noise cut.
2026-10-08 16:06:39 +02:00
julian 44f757ee37 docs(wiki): memo on discovery mechanisms for cameras, printers and the relay (SADP/ONVIF probed on the lab VLAN); park-2 readers switched to HTTP from the wizard 2026-10-08 15:51:45 +02:00
15 changed files with 398 additions and 19 deletions
+78
View File
@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { buildServer } from "./server.js";
// Request logging shape (2026-10-08 noise cut, wiki/concepts/app-logs.md §Noise cut):
// - /health logs NOTHING (Docker probes it every 30 s — it was half a quiet booth's log),
// - every other request logs ONE line "METHOD url → status Nms" (not pino's two),
// - a handler failure still logs the error with its stack, because
// `disableRequestLogging` also silences Fastify's default error-handler logging.
// The logger's stream is process.stdout (pinoDbStream tees warn+ into app_logs), so
// capture stdout writes and look at the JSON lines.
const lines: Record<string, unknown>[] = [];
let restore: (() => void) | null = null;
function captureStdout() {
const spy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
for (const l of text.split("\n")) {
if (!l.trim()) continue;
try {
lines.push(JSON.parse(l));
} catch {
/* non-JSON stdout noise — ignore */
}
}
return true;
}) as typeof process.stdout.write);
restore = () => spy.mockRestore();
}
afterEach(() => {
restore?.();
restore = null;
lines.length = 0;
});
const msgs = () => lines.map((l) => String(l.msg ?? ""));
describe("request logging", () => {
it("/health is silent; other requests log exactly one line; 5xx keeps the error", async () => {
const t = createTestDb();
captureStdout();
// vitest.config forces LOG_LEVEL=silent for every test; this one needs the real level.
const prevLevel = process.env.LOG_LEVEL;
process.env.LOG_LEVEL = "info";
const app = await buildServer({ db: t.db });
process.env.LOG_LEVEL = prevLevel;
app.get("/boom", async () => {
throw new Error("kaboom");
});
await app.ready();
try {
lines.length = 0; // drop startup lines
expect((await app.inject({ method: "GET", url: "/health" })).statusCode).toBe(200);
expect(msgs().filter((m) => m.includes("/health"))).toEqual([]);
expect((await app.inject({ method: "GET", url: "/api/nope" })).statusCode).toBe(404);
const notFound = msgs().filter((m) => m.includes("/api/nope"));
expect(notFound).toHaveLength(1);
expect(notFound[0]).toMatch(/^GET \/api\/nope → 404 \d+ms$/);
expect(msgs().some((m) => /incoming request|request completed/.test(m))).toBe(false);
expect((await app.inject({ method: "GET", url: "/boom" })).statusCode).toBe(500);
const boom = lines.filter((l) => String(l.msg).includes("/boom"));
// one error line (with the err object) + the one-line request summary
expect(boom.map((l) => [l.level, String(l.msg).replace(/\d+ms/, "Nms")])).toEqual([
["error", "GET /boom failed: kaboom"],
["info", "GET /boom → 500 Nms"],
]);
expect((boom[0]!.err as { message?: string })?.message).toBe("kaboom");
} finally {
await app.close();
t.close();
}
});
});
+5 -3
View File
@@ -159,9 +159,11 @@ export async function hikvisionAlarmRoutes(
const contentType = String(req.headers["content-type"] ?? "");
const raw: Buffer = Buffer.isBuffer(req.body) ? (req.body as Buffer) : Buffer.from("");
const summary = summarize(raw.toString("utf8"));
// Log EVERY hit immediately (method + ip + size), before any guard — so even a probe
// that gets rejected is visible in the dev log the instant it arrives.
app.log.info(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
// Log EVERY hit immediately (method + ip + size), before any guard — so under
// LOG_LEVEL=debug even a probe that gets rejected is visible the instant it arrives.
// debug, not info: every accepted hit is followed by the ACCEPTED line (which carries
// all of this plus the verdict) and every rejected one by the REJECTED warn.
app.log.debug(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
// Guard: must be a known hikvision device with alarm-push enabled, posting from its
// configured host IP. Source-IP is the primary guard on the LAN (like the Dingtian).
+1 -1
View File
@@ -244,7 +244,7 @@ export async function setupRoutes(
eventLog?: EventLog | null,
): Promise<void> {
registerBuiltinDrivers();
setDeviceLogSink((line) => app.log.info(line));
setDeviceLogSink((line, level) => app.log[level](line));
// Device setup is site administration — it changes which hardware the site runs
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
+22 -1
View File
@@ -82,6 +82,25 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
formatters: { level: (label) => ({ level: label }) },
stream: pinoDbStream(logService, process.stdout),
},
// ONE line per request (the onResponse hook below) instead of Fastify's default
// "incoming request" + "request completed" pair — on a quiet booth the pair was
// most of the log. NB: with this flag Fastify's default error handler ALSO stops
// logging handler errors, so the onError hook below re-adds that for 5xx.
disableRequestLogging: true,
});
// Request log, one line: method, url, status, elapsed. Routes declared with
// `logLevel: "silent"` (the /health probe) are skipped because `req.log` is theirs.
app.addHook("onResponse", async (req, reply) => {
req.log.info(`${req.method} ${req.url} → ${reply.statusCode} ${Math.round(reply.elapsedTime)}ms`);
});
// Handler failures (5xx) keep their stack in the log — disableRequestLogging would
// otherwise swallow them (fastify/lib/error-handler.js checks the same flag).
app.addHook("onError", async (req, _reply, err) => {
// onError runs BEFORE the error handler sets the reply status, so the reply still
// says 200 here; an error without its own statusCode is a 500 by definition.
const code = (err as { statusCode?: number }).statusCode ?? 500;
if (code >= 500) req.log.error({ err }, `${req.method} ${req.url} failed: ${err.message}`);
});
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
@@ -109,7 +128,9 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// Unauthenticated liveness probe. `app` lets a client (the desktop ConnectScreen
// test — apps/web/src/lib/backend-config.ts) tell THIS server apart from any
// other service that happens to answer on the address the operator typed.
app.get("/health", async () => ({ status: "ok", app: "parking-system" }));
// `logLevel: "silent"`: Docker's HEALTHCHECK hits this every 30 s; logging each
// probe was half of a quiet booth's output (park-2, 2026-10-08).
app.get("/health", { logLevel: "silent" }, async () => ({ status: "ok", app: "parking-system" }));
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
await authRoutes(app, db);
+17
View File
@@ -49,3 +49,20 @@ def test_analyze_rejects_empty_body() -> None:
headers={"content-type": "application/octet-stream"},
)
assert res.status_code == 400
def test_health_access_log_lines_are_dropped() -> None:
import logging
from vision_service.app import DropHealthAccessLog
flt = DropHealthAccessLog()
access = logging.getLogger("uvicorn.access")
# uvicorn's access record: '%s - "%s %s HTTP/%s" %d' with (client, method, path, version, status)
fmt = '%s - "%s %s HTTP/%s" %d'
health = access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, ("127.0.0.1:1", "GET", "/health", "1.1", 200), None)
analyze = access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, ("127.0.0.1:1", "POST", "/analyze", "1.1", 200), None)
assert flt.filter(health) is False
assert flt.filter(analyze) is True
# The filter is installed on the live logger at import.
assert any(isinstance(f, DropHealthAccessLog) for f in access.filters)
+18
View File
@@ -8,6 +8,7 @@ advisory, never the sole authority. See wiki/entities/opencv-anpr-service.md.
from __future__ import annotations
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
@@ -34,6 +35,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan)
class DropHealthAccessLog(logging.Filter):
"""Drop uvicorn access-log lines for GET /health.
The probe is hit every 30 s by Docker's HEALTHCHECK and every 8 s by the booth
server's footer chip; on a quiet booth those lines were ~90 % of this container's
output (park-2, 2026-10-08). /analyze and everything else still log.
"""
def filter(self, record: logging.LogRecord) -> bool:
return "/health" not in record.getMessage()
# uvicorn applies its logging config before importing the app, so a filter added here
# survives; dictConfig replaces handlers, not a logger's filters.
logging.getLogger("uvicorn.access").addFilter(DropHealthAccessLog())
# Typed accessors over the untyped `app.state` (so mypy --strict sees the real types).
def _recognizer(request: Request) -> Recognizer:
rec: Recognizer = request.app.state.recognizer
+4 -4
View File
@@ -49,7 +49,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-88f9c53
TAG=stage-fc93db7
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.
@@ -94,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-b7efa08
TAG=stage-fc93db7
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.
@@ -145,7 +145,7 @@ 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
TAG=stage-fc93db7
# 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
@@ -197,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-73bfc1d
TAG=stage-fc93db7
# 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
+3 -4
View File
@@ -143,10 +143,9 @@ class HttpCamera implements CameraDevice {
`${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}${busy}`,
);
}
stubLog(
this.driverId,
`captureSnapshot ${ctx.direction} (${res.body.length} bytes)`,
);
// Per-snapshot chatter → debug (a busy lane logs one every few seconds); the retry
// and failure lines above stay at info/throw.
stubLog(this.driverId, `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`, "debug");
return {
bytes: res.body,
contentType: res.contentType || "image/jpeg",
+8 -4
View File
@@ -32,7 +32,8 @@ export const passwordField: ConfigField = {
* Sink for stub/diagnostic device messages. Defaults to a no-op so the package
* has no host/runtime dependency; the server sets this to its Fastify logger.
*/
export type DeviceLogSink = (line: string) => void;
export type DeviceLogLevel = "debug" | "info" | "warn";
export type DeviceLogSink = (line: string, level: DeviceLogLevel) => void;
let sink: DeviceLogSink = () => {};
@@ -40,7 +41,10 @@ export function setDeviceLogSink(fn: DeviceLogSink): void {
sink = fn;
}
/** Stubs log instead of performing real I/O. Replaced with real protocols later. */
export function stubLog(driverId: string, msg: string): void {
sink(`[device:${driverId}] ${msg}`);
/** Device-side diagnostics (the sink is the server's logger). `info` for things an
* operator reading `docker logs` should see (a config write, a retry, a clock set);
* `debug` for per-event chatter (every snapshot's byte count) that only matters under
* LOG_LEVEL=debug. */
export function stubLog(driverId: string, msg: string, level: DeviceLogLevel = "info"): void {
sink(`[device:${driverId}] ${msg}`, level);
}
+19
View File
@@ -101,6 +101,25 @@ now refuses to run if any table is uncategorized). See [[local-dev-workflow]].
under diagnosis runs `LOG_LEVEL=debug` with no code change; warn+ persistence is unaffected
(it filters independently in the tee).
### Noise cut (2026-10-08)
Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, of which 60 were the
Docker HEALTHCHECK's `/health` every 30 s logged as "incoming request" + "request completed";
160 vision lines, of which 143 were uvicorn access lines for `GET /health` (Docker's probe plus
the booth server's footer-chip poll every 8 s, `DEVICE_POLL_MS`). Levels were never the problem
— all of it was `info`. Changes:
- **`/health` is silent** (`logLevel: "silent"` on the route); vision drops `/health` access
lines with a `logging.Filter` on `uvicorn.access` (`DropHealthAccessLog`, app.py).
- **One line per request**: `disableRequestLogging` + an `onResponse` hook →
`GET /api/x → 200 12ms`. ⚠ That flag also stops Fastify's default error handler from logging
handler errors (fastify/lib/error-handler.js), so an `onError` hook logs 5xx with the stack.
- **Chatter → debug**: the hik-alarm `HIT` line (ACCEPTED/REJECTED carry everything) and the
per-snapshot `captureSnapshot … (N bytes)` line; `stubLog` gained a level argument (device
diagnostics default `info`, per-event chatter passes `"debug"`). `LOG_LEVEL=debug` restores all.
Expected on a quiet booth: a handful of lines per hour instead of ~500.
## The booth viewer
A **Logs screen** under Setup (`/setup/logs`, gated by `log:read`, sq+en) — filter by
+7
View File
@@ -38,6 +38,13 @@ with the readers: works from the booth (host-network server) and the device VLAN
bridged dev container (`docker-compose.dev.yml`) nor across Netbird — there, use
`scripts/dingtian_qr.py get <ip>` on the booth instead.
## Roadmap for the other devices
Cameras (SADP + ONVIF WS-Discovery, both verified on the lab VLAN 2026-10-08), network printers
(TCP 9100 sweep + web fingerprint), the Dingtian relay's multicast search and Dahua's 37810 tool
protocol — with the method and rules distilled from the DT-008 work — are planned in
[[device-discovery-roadmap]].
## UHPPOTE discovery (historical example)
The [[uhppote-controller]] supported discovery natively: a **UDP broadcast** (`get-devices` on
+179
View File
@@ -0,0 +1,179 @@
---
type: decision
tags: [parking, decisions, devices, setup, discovery, cameras, printers, relay, readers]
sources: [dingtian-qr-linux-tool, ds-2cd1047g3h-liu]
updated: 2026-10-08
status: open
---
# Memo: discovery mechanisms for the devices we already know
**Ask (operator, 2026-10-08):** write down how we will give every known device class — relays,
printers, cameras, readers — a **Scan** in the setup wizard, the way the DT-008 reader got one
today. This memo is the plan: what exists, the method that worked, what each device can
actually answer on the wire (probed on the lab VLAN today where possible), the rules that carry
over, and the order to build in. Nothing here is built except the reader.
## 1. Why discovery is worth building (the park-2 lesson)
[[first-run-setup]] has the admin **type** what a device is — IP, serial, port. Nothing checked
that the typed picture matched the device. park-2 ran a month with two readers whose typed
config was perfect and whose *actual* output mode was Wiegand: every card "beeped" and none
reached the booth ([[site-device-installation]] §2 trap). Discovery is the reality check that
replaces typing with **what the device says about itself**, and — the part that matters more —
its companion **identity precondition**: *the serial/MAC you typed is the one the device at
that IP reports*. The same mechanism ends the Windows-tool-on-a-laptop site visits (SADP for
cameras, the Dingtian tools, printer utilities): one laptop-free wizard on the booth.
## 2. What already exists (don't rebuild)
- `DiscoverableDriver.discover() → DiscoveredDevice[]` in `@parking/devices` (`id`, `label`,
`config` to auto-fill, free-form `info`), the registry's `isDiscoverable()`, the catalog's
`discoverable` list, admin-only `GET /api/setup/discover/:driverId` (health-checks each hit),
and the wizard's **Scan** button + **Use** per row, rendering every `info` key
([[device-discovery]]).
- The write side that discovery feeds: `PreconditionDevice` (check → fixable/unfixable issues,
shown on **Test**, fixed on **Save**), `PushConfigurableDevice` (point the device at this
booth), `HardenableDevice`. The DT-008 driver is the worked example of all three together.
- Already a discovery in all but name: `GET /api/setup/usb-printers` lists `/dev/usb/lpN` with
the printer's self-reported make/model from sysfs `ieee1284_id` ([[printer-usb-transport]]).
## 3. The method that worked for the DT-008 (reuse it verbatim)
1. **Learn the protocol on the bench, never on a site.** Vendor tool + a lab unit; capture the
tool's own datagrams or read the vendor doc. Write it up as `raw/<device>/PROTOCOL.md`
(frame, ports, commands, field tables, *verification status per command*).
2. **TypeScript module + fake-device tests** (`drivers/<device>-config.ts`, `*.test.ts` with a
loopback fake that enforces the protocol's quirks — e.g. the DT-008's two-datagram writes).
3. **Driver hooks:** `discover()` (search → per-hit identity read → `config` + `info`),
`checkPreconditions()` (identity match + the one or two settings our flow depends on),
`fixPreconditions()` / `configureInputPush()` only for settings proven writable.
4. **Bench round trip with restore**: change → read back → change back → byte-diff the device's
config. Only then touch a site, and there only through the wizard.
5. Wiki: entity page, [[device-discovery]], [[first-run-setup]], the install runbook, log.
## 4. Per device: what answers on the wire
Status legend: **verified** = we saw it on the lab VLAN today (host `10.0.10.203`);
**documented** = vendor doc / wiki says so, not yet seen; **unknown** = needs a capture.
| device | mechanism | transport | returns | status |
| --- | --- | --- | --- | --- |
| DT-008 reader | vendor search cmd 2 | UDP bcast 24582 | serial, IP, server:port | **verified, built** |
| Hikvision cameras / DVR | **SADP** Probe | UDP mcast `239.255.255.250:37020`, XML | model, **serial**, **MAC**, IPv4, HTTP + command port, (activation state) | **verified**: 9 devices answered |
| Hikvision, Dahua, any IP camera | **ONVIF WS-Discovery** Probe | UDP mcast `239.255.255.250:3702`, SOAP | `XAddrs` (device-service URL), scopes: hardware model, name, sometimes MAC | **verified** on 4 Hikvision; the bench Dahua did **not** answer (see 4.2) |
| Dahua cameras | ConfigTool search ("DHIP") | UDP bcast 37810 | (per vendor tool: IP, MAC, serial, model) | **unknown** — my guessed frame got no reply; capture the ConfigTool like the DT-008 exe |
| Dingtian relay | search | UDP mcast `224.0.2.11:60000`, payload `05 AA` | "devices reply" ([[dingtian-relay]]) — reply content not recorded | **documented**; no relay on the lab VLAN to probe |
| Rongta / K200L LAN printers | no vendor discovery known to us | — | — | **unknown** (vendor utilities exist; protocol uncaptured) |
| any network ESC/POS printer | **TCP 9100 sweep** of the device subnet + web fingerprint | TCP connect ×254 in parallel, then HTTP GET | IP; model only via the board's web page | **verified**: 2 hits (`.220`, `.234`) in ~1 s — both *office* printers, neither ours → fingerprint is mandatory |
| USB printers | `/dev/usb/lpN` + `ieee1284_id` | sysfs | path, MFG/MDL | **built** |
### 4.1 Cameras — two protocols, run both, merge by MAC/serial
- **SADP** is the one that finds *everything Hikvision*, including units whose ONVIF is off
(5 of today's 9 answered SADP only) and **unactivated** units (factory `192.168.1.64`,
`<Activated>false</Activated>`) — i.e. the exact state a new G3H arrives in. Its ProbeMatch
carries `DeviceDescription` (model), `DeviceSN`, `MAC`, `IPv4Address`, `HttpPort`,
`CommandPort` (8000). Newer firmware (the DVR today) adds `<Encrypt>true</Encrypt><Salt>…`
for its *write* side; the inquiry itself stays plaintext. SADP can also **activate** a camera
and **set its IP** (password-protected) — the runbook's "activate with SADP or the browser"
step ([[site-device-installation]] §3) could become a wizard action later; discovery first.
- **WS-Discovery** is the vendor-neutral path and the only standard one Dahua offers. Scopes
give the model (`onvif://www.onvif.org/hardware/DS-2CD2T43G0-I5`) and `XAddrs` gives the
device-service URL — enough to pick the driver (`DS-…` → `hikvision`, Dahua names → `dahua`)
and the IP. **Caveat seen today:** the bench IPC-HFW2549T answered neither WS-Discovery nor
my 37810 guess; Dahua ships ONVIF switchable (web UI → Network → *Integration Protocol* /
ONVIF) — check that unit's setting before concluding anything. Record the outcome on
[[dahua-ipc-hfw2549t]].
- **Identity precondition for cameras:** on Use, store `serial` (SADP `DeviceSN` / ONVIF
scope) + `mac` next to `host`; on Test/Save compare with what the camera reports over its own
API (Hikvision `/ISAPI/System/deviceInfo` → `serialNumber`; Dahua
`magicBox.cgi?action=getSerialNo`). A swapped or re-addressed camera then fails loudly instead
of silently snapshotting the wrong lane. Further preconditions the same hook can own, all from
past incidents: clock drift ([[lpr-camera]] clock sync), ANPR push target = this booth
([[lpr-camera]] §Camera PUSH — Alarm Server), vehicle target filter on.
- Shape: keep the per-driver API; `hikvisionDriver.discover()` = SADP ∪ ONVIF filtered to
Hikvision hardware, `dahuaDriver.discover()` = ONVIF filtered ∪ (37810 once captured). Merge by
MAC, then serial; never by IP.
### 4.2 Dingtian relay — documented, unprobed
[[dingtian-relay]] records the vendor's search: multicast `224.0.2.11:60000`, payload `05 AA`,
devices reply; defaults IP `192.168.1.100`, UDP 60000 binary / 60001 string. Open before
building: (a) what the reply contains (MAC? firmware? — needed for identity; our relay config
has no serial today, identity is the IP alone); (b) whether a **hardened** board (relay_pw set,
string protocol disabled — [[dingtian-relay]] §hardening) still answers an unauthenticated
search — if not, discovery only finds *new* boards, which is still the useful case; (c) whether
the reply can come back on the host network from a multicast group (needs
`IP_ADD_MEMBERSHIP` on the device-VLAN interface, or the board may answer by unicast to the
sender — capture to know). Needs a board on the bench; one visit of the vendor tool with the
same capture method as the DT-008.
### 4.3 Printers — sweep + fingerprint, not a vendor protocol
Neither the Rongta board nor the K200L's "J-Speed" LAN module has a discovery protocol we know;
both vendors ship Windows utilities that surely broadcast something, uncaptured. The pragmatic
mechanism is already verified: **connect to TCP 9100 on every address of the device subnet in
parallel** (254 probes, ~1 s), then **fingerprint each hit over HTTP**: Rongta answers
`GET /prn_stat.htm` with its status page ([[rongta-printer]]); the K200L web configurator is a
three-frame page titled "Ethernet WebConfig" ([[k200l-printer]]); anything else is listed as
"unknown 9100 device" (today's two office printers would be). Identity: the K200L *Information*
frame shows its MAC; Rongta's pages carry none we know — fall back to the ARP entry after the
connect (`/proc/net/arp` on the host network). No ESC/POS serial exists over 9100, so the
precondition is weaker here: "a Rongta/K200L board still answers at this IP" plus the live
status page. Preconditions worth owning: USB path still present (already in the USB select),
network board reachable, paper/cover state ([[printer-status-monitoring]]).
### 4.4 DT-008 reader — built; two gaps
Discovery, identity (serial), output mode and push target are done. Still manual: giving a
factory `192.168.1.99` unit its site IP (cmd 32 `set-network` supports it — a "Set IP" action
in the discovery row would finish the laptop-free install), and prefixes / card format (cmds
12/14/44/8). Both are in `scripts/dingtian_qr.py` today ([[dingtian-qr-linux-tool]]).
## 5. Rules that carry over to every implementation
1. **Subnet-directed broadcast per interface**, never `255.255.255.255` (EACCES on some
hosts, and not what vendor tools send); **multicast needs `IP_MULTICAST_IF` per interface**
and, to *receive* group traffic, `IP_ADD_MEMBERSHIP` — SADP/ONVIF replied by unicast to the
sender today, so sending was enough; don't assume that for the relay.
2. **Replies arrive from arbitrary source ports** — match on content, not port; collect for a
window (~2 s), then stop.
3. **Dedupe and identify by a stable identity (serial, MAC) — never by IP**; the IP is the thing
most likely to be wrong.
4. **Discovery is read-only.** "Use" fills the form; writes happen only on Save, through
preconditions/push-config, each proven on the bench with a restore. Discovery must never be
periodic/background: it is an admin action in Setup, so the booth operator (our adversary,
[[threat-model]]) has no new lever.
5. **L2 only.** Works from the booth (host-network server) and the device VLAN; impossible
from a bridged dev container and across Netbird — say so in the empty-result message
(the wizard's "no devices found" text already does).
6. **Replies are untrusted input** from an unauthenticated network: cap sizes, parse XML
without entity expansion, never pass a reply string into a shell/URL unescaped, never
forward credentials to a discovered address without the identity check.
7. **Serials and MACs are site data** — they go in the device row, not in commits/wiki with
booth names ([[fleet-deployment-komodo]] pseudonymity rule).
## 6. Order of work
1. **Cameras — SADP + WS-Discovery** (protocols verified today; no bench captures needed;
biggest field pain = activation/IP of new units; two vendors covered). Half a day plus the
identity precondition.
2. **Printers — 9100 sweep + fingerprint** (verified mechanism, small code, replaces guessing
the printer's IP at park-buzi-type installs).
3. **Dingtian relay search** — when a board is on the bench; capture the reply first.
4. **Dahua 37810** — capture the ConfigTool; until then Dahua relies on ONVIF being enabled.
5. **DT-008 "Set IP" from the discovery row** (set-network is proven).
## 7. Open questions
- Does a hardened Dingtian board answer the `05 AA` search? What is in the reply?
- Is ONVIF off on the bench Dahua, or did the probe not reach it? (web UI check, then re-probe)
- SADP `Encrypt/Salt` on newer firmware: inquiry stays plaintext — confirm on a 2026 unit.
- Rongta board MAC/identity: any page or ESC/POS query that returns a stable id?
- Should the camera row offer **activate + set IP** (SADP write side), or stay read-only and
leave activation to the browser? (Leaning read-only first; writes only after a bench round trip.)
Related: [[device-discovery]] · [[device-registry]] · [[first-run-setup]] ·
[[site-device-installation]] · [[dingtian-dt008-reader]] · [[dingtian-relay]] · [[lpr-camera]] ·
[[dahua-ipc-hfw2549t]] · [[rongta-printer]] · [[k200l-printer]] · [[dingtian-qr-linux-tool]]
+9 -1
View File
@@ -2,7 +2,7 @@
type: decision
tags: [parking, decisions, open]
sources: [parking-system-architecture]
updated: 2026-09-08
updated: 2026-10-08
status: open
---
@@ -170,3 +170,11 @@ procurement. (See [[parking-system-architecture]] §10.)
`8H` is required for 13.56 MHz sites before any card is enrolled against one. (Phones present a
random `08…` UID per tap and can never be credentials.) See
[[dingtian-dt008-reader]] §"Two RF variants".
19. **Discovery for every known device class.** _(Raised by the user, 2026-10-08, after the
park-2 readers turned out to be in Wiegand mode for a month.)_ The wizard's Scan exists
generically and the DT-008 implements it; cameras (SADP + ONVIF, both verified on the lab
VLAN), network printers (9100 sweep + fingerprint), the Dingtian relay (multicast search,
reply unknown) and Dahua (37810, uncaptured) do not. Plan, rules and order of work:
[[device-discovery-roadmap]]. Settles when cameras and printers scan from the wizard and the
relay's search reply has been captured on the bench.
+2 -1
View File
@@ -71,7 +71,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[first-run-setup]] — admin adds controllers + binds readers/cameras to relays from the catalog at install.
- [[site-device-installation]] — FIELD RUNBOOK (2026-09-09): per device — factory address + credentials, the tool needed, what the wizard configures itself vs what is done by hand on the device, known traps; address plan, order of work on site, gaps to fill. Dingtian relay, DT-008 readers, Hikvision camera, radar, K200L / Rongta / Cashino printers.
- [[device-input-flow]] — button → device push → backend decides → relay; backend is source of truth.
- [[device-discovery]] — optional driver capability to scan the LAN (no current driver uses it; UHPPOTE was the example).
- [[device-discovery]] — optional driver capability to scan the LAN; implemented by the DT-008 reader (2026-10-08), UHPPOTE was the historical example.
- [[barrier-not-a-door]] — never timed-close a barrier; safety lives in barrier firmware.
- [[printer-roles-failover]] — ≥2 printers by role; entry ticket falls back outside→booth.
- [[printer-status-monitoring]] — live poll of paper/cover/cutter/offline via the device's status page; SSE to the booth UI.
@@ -139,6 +139,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[session-model]] — business layer start: session = projection; transient-first; pay-on-foot. New event types.
- [[vision-service]] — build a host-side ANPR + vehicle-verification service; replaces edge-LPR; scoped AGPL exception.
- [[bodytype-classifier-training]] — phase B (SUV vs sedan): `apps/trainer` trains on the collector host (time split, floor, features/finetune modes, feature cache) → report → publish to the Gitea generic package → `models/bodytype.version` pin bakes it into the vision image → TAG bump; sidecar = the preprocessing contract; CPU-only torch on the Xeon E3-1225 v5, Quadro FX 3800 unusable, cloud GPU rejected. Built 2026-09-07; first run waits for labels.
- [[device-discovery-roadmap]] — memo (open): how each known device class gets a wizard Scan — SADP + ONVIF for cameras (verified on the lab VLAN), 9100 sweep + fingerprint for printers, Dingtian relay multicast search, Dahua 37810; the reusable method and rules from the DT-008 work.
- [[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).
+26
View File
@@ -3415,3 +3415,29 @@ target 8080→8081→8080, struct byte-identical), 17 adapter + 15 protocol test
needs a new image (push → CI) and a stack bump; park-2's readers still await the one-line fix.
Pages: [[device-discovery]], [[first-run-setup]], [[dingtian-dt008-reader]],
[[site-device-installation]] §2, [[dingtian-qr-linux-tool]].
## [2026-10-08] query | park-2 readers switched to HTTP from the wizard
park-2 deployed `stage-b7efa08`; the operator opened each reader in Setup and saved. Server log:
`10.0.10.7: output type WG26 → HTTP` (13:34:00Z) and the same for `.8` fifteen seconds later; a
read-back from the booth confirms both in HTTP mode at `10.0.10.101:3000`; Test shows no issues.
First real scan after the change still to be observed. Pages: [[site-device-installation]] §2.
## [2026-10-08] query | Memo: discovery mechanisms for relays, printers, cameras
Asked for by the operator. Probed the lab VLAN from 10.0.10.203 first: SADP multicast → 9
Hikvision devices (model, serial, MAC, ports; the DVR adds Encrypt/Salt); ONVIF WS-Discovery → 4
of them (XAddrs + hardware scopes); the bench Dahua answered neither (ONVIF setting to check) and
a guessed 37810 frame got nothing; a parallel TCP-9100 sweep found two office printers in ~1 s
(neither Rongta nor K200L → fingerprint step mandatory); no relay present for the `05 AA`
search. Memo filed as [[device-discovery-roadmap]] (method, per-device table, rules, order:
cameras → printers → relay → Dahua → DT-008 set-IP); open question #19; [[device-discovery]] and
[[index]] updated.
## [2026-10-08] query | Container log noise on a quiet booth
park-2 right after redeploy: 128 server + 160 vision lines in 15 min, ~90 % health probes
(Docker HEALTHCHECK every 30 s; the footer chip polling vision every 8 s) logged at info. Fixed in
code, not by level: `/health` silent on both services, one request line instead of two (with an
`onError` hook so 5xx keep logging under `disableRequestLogging`), hik-alarm HIT and per-snapshot
byte lines demoted to debug via a level on `stubLog`. Pages: [[app-logs]] §Noise cut.