2 Commits

Author SHA1 Message Date
julian 73ada89a13 fix(server): bound active-sessions cost, index hot paths, no phantom relay timeouts
Build & push images / images (push) Successful in 3m45s
park-2 (2026-10-24): GET /api/sessions/active ran ~2 s synchronously — PayStation.activeSessions
called quote() per open unpaid transient (664 rows), each 3-4 unindexed ledger_events scans by
identity — 2234x/day. The frozen event loop made the Dingtian driver's 2 s timer fire before the
already-received UDP reply (timers run before poll I/O), so healthy pulses logged "timeout"; the
subscription flow then unwound before firing the camera or writing the sessions row, leaving
signed entries with no snapshot. Cost grew ~120 ms/day with the operator's open-ticket count.

- pay-station: price every list row from the one ledger scan (rows grouped per identity ->
  #quoteFromRows); tariff resolver built once per request; quote(identity) wraps the same core.
  validations: sessionValidationsFromRows / liveValidationsFromRows. Test pins list == quote().
- db 0032_hot_path_indexes: ledger_events(identity,index), device_events(category,kind,
  occurred_at), device_events(kind,occurred_at), snapshots(identity), sessions(state),
  sessions(subscription_id,state). Additive.
- access-dingtian binaryUdp: defer the timeout rejection with setImmediate so a datagram that
  already arrived wins over an expired timer.
- subscription-flow: snapshot fired and session cache written/closed BEFORE the pulse.

wiki/concepts/park-2-event-loop-stall.md has the full analysis.
2026-10-24 11:17:30 +02:00
julian 6eb65361a8 docs(wiki): park-2 event-loop stall incident + bounded-request-cost decision; Dingtian firmware retired, dev-board pinout, edge-controller memo
- concepts/park-2-event-loop-stall: /api/sessions/active ~2 s synchronous (quote() per open
  unpaid transient x664, unindexed ledger scans) froze the loop; Node runs expired timers before
  queued UDP replies, so healthy Dingtian pulses reported "timeout" and signed entries lost
  their snapshot/session row. Standing decision: bounded request cost whatever the operator data.
- Dingtian: custom firmware retired (2026-10-23), runbook shelved, vendor pinout in raw/,
  relay-proxy PoC marked retired; edge-controller hardware memo (open).
2026-10-24 11:17:30 +02:00
21 changed files with 589 additions and 57 deletions
+21
View File
@@ -152,4 +152,25 @@ describe("PayStation.activeSessions", () => {
expect(list.map((s) => s.identity)).toEqual(["NEW", "OLD"]);
expect(list.every((s) => s.open)).toBe(true);
});
// The list prices each open transient from ONE whole-ledger scan (no per-row ledger
// reads — those froze park-2's server, 2026-10-24). The amounts must match the
// single-session quote() exactly, including after a payment (overstay repricing) and
// for a subscription (never quoted).
it("prices every row identically to quote() without per-session ledger reads", async () => {
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 });
await enter("UNPAID", minutesAgo(150));
await enter("PAID", minutesAgo(300));
await pay.pay("PAID", "cash"); // grace 0 → paid-but-open ⇒ overstay, re-priced from now
await enter("SUB", minutesAgo(10), { permit: true, permitId: "sub-1" });
const list = pay.activeSessions();
const by = new Map(list.map((s) => [s.identity, s]));
expect(by.get("UNPAID")!.amountMinor).toBe(pay.quote("UNPAID").amountMinor);
expect(by.get("UNPAID")!.currency).toBe(pay.quote("UNPAID").currency);
expect(by.get("PAID")!.overstay).toBe(true);
expect(by.get("PAID")!.amountMinor).toBe(pay.quote("PAID").amountMinor);
expect(by.get("SUB")!.subscription).toBe(true);
expect(by.get("SUB")!.amountMinor).toBeNull();
});
});
+56 -20
View File
@@ -4,7 +4,13 @@ import type { FastifyBaseLogger } from "fastify";
import type { EventLog } from "./event-log.js";
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
import { windowOwedBetween } from "./subscription-window.js";
import { liveValidations } from "./validations.js";
import { liveValidationsFromRows } from "./validations.js";
/** A `ledger_events` row as the pricing fold reads it. */
type LedgerRow = typeof ledgerEvents.$inferSelect;
/** Resolves the tariff version in force at an instant. Built once per request so a list
* view does not re-read the tariff tables for every row. */
type TariffResolver = (at: string) => typeof tariffVersions.$inferSelect | null;
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
// car (pay-on-foot — payment is decoupled from exit). Two steps:
@@ -200,12 +206,23 @@ export class PayStation {
* 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period
* reflects the reality and re-accrues the fee. No side effect. */
quote(identity: string): Quote {
const entry = this.#openEntry(identity);
return this.#quoteFromRows(identity, this.#identityRows(identity), this.#tariffResolver());
}
/** `quote` over the identity's ledger rows the caller already holds (oldest first) and
* a prebuilt tariff resolver. The single-session `quote()` wraps this with one
* identity-scoped read; `activeSessions()` feeds it per-identity groups of ONE whole-
* ledger scan. Both paths MUST price identically — pinned by pay-station.test.ts.
* Why: the list view used to call `quote()` per open unpaid row, each doing 3–4
* ledger scans; with ~660 such rows at park-2 the synchronous handler ran ~2 s and
* froze the event loop — relay replies then "timed out" (2026-10-24). */
#quoteFromRows(identity: string, rows: readonly LedgerRow[], tariffFor: TariffResolver): Quote {
const entry = PayStation.#openEntryFromRows(rows);
if (!entry) throw new NoOpenSessionError(identity);
// The tariff in force is keyed to ENTRY (the version frozen for this session), even
// for an overstay period — the customer keeps the rate card they entered under.
const tv = this.#tariffVersionFor(entry.occurredAt);
const tv = tariffFor(entry.occurredAt);
if (!tv) throw new NoTariffError();
const structure = tv.structure as unknown as TariffStructure;
@@ -220,8 +237,8 @@ export class PayStation {
// Merchant validations: fold the LIVE ones (applied, unvoided, not consumed by a
// prior payment) so the quote is NET — the payment then stamps their ids as
// consumed. See wiki/concepts/validation-discounts.md.
const last = this.#lastPayment(identity);
const validations = liveValidations(this.#db, identity);
const last = PayStation.#lastPaymentFromRows(rows);
const validations = liveValidationsFromRows(rows);
const p = priceSession(
entry.occurredAt,
new Date().toISOString(),
@@ -254,12 +271,17 @@ export class PayStation {
/** The latest signed `payment` for this session (time + the grace window it granted),
* or null if never paid. Folds the append-only ledger. */
#lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null {
const rows = this.#db
.select({ type: ledgerEvents.type, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload })
.from(ledgerEvents)
.where(eq(ledgerEvents.identity, identity))
.orderBy(ledgerEvents.index)
.all();
return PayStation.#lastPaymentFromRows(this.#identityRows(identity));
}
/** All ledger rows of one identity, oldest first (the fold order every helper expects). */
#identityRows(identity: string): LedgerRow[] {
return this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).orderBy(ledgerEvents.index).all();
}
static #lastPaymentFromRows(
rows: readonly Pick<LedgerRow, "type" | "occurredAt" | "payload">[],
): { paidAt: string; graceExitMin: number | null } | null {
let last: { paidAt: string; graceExitMin: number | null } | null = null;
for (const r of rows) {
if (r.type !== "payment") continue;
@@ -541,9 +563,15 @@ export class PayStation {
subscriptionId?: string | null;
};
const byId = new Map<string, Acc>();
// Every row per identity (oldest first — `rows` is index-ordered), so the quotes
// below price from THIS scan instead of re-reading the ledger per session.
const rowsById = new Map<string, LedgerRow[]>();
for (const r of rows) {
const id = r.identity;
if (!id) continue;
const group = rowsById.get(id);
if (group) group.push(r);
else rowsById.set(id, [r]);
if (r.type === "vehicle_entry") {
const a = byId.get(id) ?? { source: r.source ?? null };
a.enteredAt = r.occurredAt;
@@ -570,6 +598,8 @@ export class PayStation {
// Resolve advisory plates for all candidate identities in ONE device_events scan
// (cheaper than one lookup per row).
const plates = platesForIdentities(this.#db, byId.keys());
// One tariff read for the whole list (quotes below reuse it).
const tariffFor = this.#tariffResolver();
const now = Date.now();
const out: ActiveSession[] = [];
@@ -607,7 +637,9 @@ export class PayStation {
let currency: string | null = null;
if (open && !isSubscription && (a.paidAt == null || overstay)) {
try {
const q = this.quote(identity);
// Priced from the rows already in hand — no per-session ledger reads. The
// charge providers (car wash) still run one indexed lookup per row.
const q = this.#quoteFromRows(identity, rowsById.get(identity) ?? [], tariffFor);
amountMinor = q.amountMinor;
currency = q.currency;
} catch {
@@ -710,12 +742,10 @@ export class PayStation {
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
#openEntry(identity: string) {
const rows = this.#db
.select()
.from(ledgerEvents)
.where(eq(ledgerEvents.identity, identity))
.orderBy(ledgerEvents.index)
.all();
return PayStation.#openEntryFromRows(this.#identityRows(identity));
}
static #openEntryFromRows(rows: readonly LedgerRow[]): LedgerRow | null {
const entry = rows.find((r) => r.type === "vehicle_entry");
if (!entry) return null;
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed
@@ -725,14 +755,20 @@ export class PayStation {
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
* (single, for now) active site tariff. */
#tariffVersionFor(at: string) {
return this.#tariffResolver()(at);
}
/** Read the site tariff + its versions ONCE and return a resolver over them. A list
* view builds one resolver per request instead of two tariff reads per row. */
#tariffResolver(): TariffResolver {
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
if (!tariff) return null;
if (!tariff) return () => null;
const versions = this.#db
.select()
.from(tariffVersions)
.where(eq(tariffVersions.tariffId, tariff.id))
.orderBy(desc(tariffVersions.effectiveFrom))
.all();
return versions.find((v) => v.effectiveFrom <= at) ?? null;
return (at) => versions.find((v) => v.effectiveFrom <= at) ?? null;
}
}
+12 -5
View File
@@ -212,8 +212,9 @@ export class SubscriptionFlow {
// `permitId` carries the subscription id; `via` records which credential left.
payload: { sessionRef: occurrenceId, permitId: m.subscriptionId, via: m.via },
});
await this.#open(resolved, "exit", occurrenceId, "subscription exit");
// Cache close before the pulse, for the same reason as the entry-side insert.
this.#closeCache(occurrenceId);
await this.#open(resolved, "exit", occurrenceId, "subscription exit");
return { accepted: true, direction: "exit" };
}
@@ -269,7 +270,9 @@ export class SubscriptionFlow {
`subscription out-of-window entry marked on ${occurrenceId} (charge priced from parked minutes at exit)`,
);
}
await this.#open(resolved, "entry", occurrenceId, "subscription entry");
// Session cache BEFORE the pulse: the entry is already signed, so the projection must
// reflect it even if the relay call throws (otherwise the ledger and the sessions
// table disagree about the same read — seen at park-2, 2026-10-24).
try {
this.#db
.insert(sessions)
@@ -285,6 +288,7 @@ export class SubscriptionFlow {
} catch (err) {
this.#logger.error(`session-cache insert failed for ${occurrenceId}: ${(err as Error).message}`);
}
await this.#open(resolved, "entry", occurrenceId, "subscription entry");
// BEST-EFFORT: print the out-of-window TICKET so the subscriber has the paper the
// operator scans to settle at the booth. It carries the occurrence id as a scannable
// code; the amount is computed at settlement from the minutes actually parked
@@ -410,13 +414,16 @@ export class SubscriptionFlow {
}
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
// SNAPSHOT FIRST — fire the directional camera(s), never awaited (evidence, not a
// gate). Before the pulse, so a pulse failure (the pulse helper rethrows) still leaves
// an image for the signed event: at park-2 four signed entries had no snapshot because
// the relay timed out and this method unwound before reaching the camera (2026-10-24).
this.#fireSnapshot(dir, carKey);
const access = this.#buildAccess(resolved.controller);
if (access) {
await pulseBarrier(this.#db, this.#logger, access, resolved, { direction: dir, identity: carKey, source: "subscription" });
} else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
this.#fireSnapshot(dir, carKey);
}
#closeCache(carKey: string): void {
+21
View File
@@ -21,6 +21,16 @@ export interface AppliedValidation extends SessionValidation {
readonly consumedBy: string | null;
}
/** The ledger columns the validation fold reads. Any identity-scoped, index-ordered
* slice of `ledger_events` satisfies it (a direct query, or the per-identity group of a
* whole-ledger scan — see PayStation.activeSessions). */
export interface LedgerRowLike {
readonly id: string;
readonly type: string;
readonly occurredAt: string;
readonly payload: unknown;
}
/** All validations ever applied to a session (newest last), with voided/consumed
* state folded from the chain. One identity-scoped ledger scan. */
export function sessionValidations(db: Db, identity: string): AppliedValidation[] {
@@ -35,7 +45,13 @@ export function sessionValidations(db: Db, identity: string): AppliedValidation[
.where(eq(ledgerEvents.identity, identity))
.orderBy(ledgerEvents.index)
.all();
return sessionValidationsFromRows(rows);
}
/** Same fold over rows the caller already holds (identity-scoped, oldest first). Lets a
* list view price hundreds of sessions from ONE ledger scan instead of one per row —
* the per-row scans were what froze the booth server (park-2, 2026-10-24). */
export function sessionValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] {
const voided = new Set<string>();
const consumedBy = new Map<string, string>();
const applies: AppliedValidation[] = [];
@@ -88,6 +104,11 @@ export function liveValidations(db: Db, identity: string): AppliedValidation[] {
return sessionValidations(db, identity).filter((v) => !v.voided && v.consumedBy == null);
}
/** `liveValidations` over rows the caller already holds (see sessionValidationsFromRows). */
export function liveValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] {
return sessionValidationsFromRows(rows).filter((v) => !v.voided && v.consumedBy == null);
}
// --- Apply (shared by the merchant route and the Car Wash module) ----------------
export interface ApplyValidationInput {
@@ -0,0 +1,18 @@
-- Hot-path indexes (park-2, 2026-10-24). Every per-session read of the ledger was a full
-- scan (no index on identity), and the camera/relay telemetry queries scanned
-- device_events (no index beyond the PK). Both tables grow with the operator's traffic,
-- so request time grew with it: the booth's active-sessions call reached ~2 s and froze
-- the event loop, which surfaced as relay "timeouts". The handler was also rewritten to
-- avoid per-row reads; these indexes make the remaining identity/telemetry lookups O(log n)
-- whatever the data volume. All additive; the previous image ignores them on rollback.
CREATE INDEX IF NOT EXISTS `ledger_events_identity_idx` ON `ledger_events` (`identity`,`index`);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `device_events_cat_kind_time_idx` ON `device_events` (`category`,`kind`,`occurred_at`);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `device_events_kind_time_idx` ON `device_events` (`kind`,`occurred_at`);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `snapshots_identity_idx` ON `snapshots` (`identity`);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `sessions_state_idx` ON `sessions` (`state`);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `sessions_subscription_idx` ON `sessions` (`subscription_id`,`state`);
+7
View File
@@ -225,6 +225,13 @@
"when": 1788710000000,
"tag": "0031_carwash_review_outbox",
"breakpoints": true
},
{
"idx": 32,
"version": "6",
"when": 1788720000000,
"tag": "0032_hot_path_indexes",
"breakpoints": true
}
]
}
@@ -77,7 +77,13 @@ function binaryUdp(
sock.close();
err ? reject(err) : resolve(val!);
};
const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs);
// On expiry, defer the rejection by one loop turn. Node runs expired timers BEFORE
// it drains pending socket I/O, so if the event loop was blocked (a long synchronous
// handler) while the device's reply sat in the kernel buffer, the timer would win
// and report "timeout" for a relay that answered. The setImmediate lands in the
// check phase, after the poll phase has delivered that datagram to `message`.
// (park-2, 2026-10-24: ~2 s handler stalls produced exactly these phantom timeouts.)
const timer = setTimeout(() => setImmediate(() => done(new Error("timeout"), null)), timeoutMs);
sock.on("error", (e) => done(e, null));
sock.on("message", (m) => done(null, m));
// Bind to a specific local address (the device-facing NIC) on multi-homed
+5
View File
@@ -266,3 +266,8 @@ off the latest payment. See [[tariff]] (walk-back grace) for the pricing side of
auto-printed at payment. `POST /api/voucher`, `POST /api/receipt`.
- Open: a force-open **override** (lost ticket / equipment fault) — deferred; would be a separately
audited signed event, not folded into the validated path.
> **Performance note (2026-10-24).** `activeSessions()` prices every open unpaid transient from
> ONE ledger scan (rows grouped per identity → `#quoteFromRows`), never `quote()` per row. The
> per-row version grew with the operator's open-ticket count and froze park-2's server at ~2 s
> per call — see [[park-2-event-loop-stall]].
+38 -19
View File
@@ -2,11 +2,14 @@
type: concept
tags: [parking, hardware, runbook, esp32, dingtian]
sources: []
updated: 2026-10-22
updated: 2026-10-23
---
# Runbook — Is this ESP32 board flashable? (Dingtian DT-R0xx lock test)
> **Shelved 2026-10-23** — custom Dingtian firmware is retired (user decision, mini PCs instead).
> Kept as reference; never run on the bench unit.
A bench test that answers one question in a few minutes: **is the ESP32 on this [[dingtian-relay]]
locked (standard SKU) or open (Development Board Version)?** Run it before ordering more units or
planning any custom-firmware work (see [[dingtian-relay]] "Can we flash our own firmware?").
@@ -25,39 +28,53 @@ blocks custom firmware:
| `FLASH_CRYPT_CNT` (flash encryption) | flash contents unreadable/unwritable from outside | `espefuse summary` shows it odd/enabled |
| `ABS_DONE_0` / `ABS_DONE_1` (secure boot) | ROM only runs a vendor-signed bootloader | `espefuse summary` shows it set |
The 74HC595 / 74HC165 shift registers on the board are **not** a blocker; community firmware drives
them already.
On the 2- and 4-channel boards relays and inputs are **direct GPIOs** (DT-R004: relays IO16/IO2/IO32/IO12,
inputs IO36/IO39/IO33/IO35, UART IO1/IO3, PHY JL1101 on RMII with IO23 MDC / IO18 MDIO / IO17 clock /
IO0 PHY power); only the 8/16/32-channel boards use 74HC595/74HC165 shift registers. Neither is a
blocker; community firmware drives both.
## Equipment
- USB-to-UART adapter, **3.3 V logic** (CP2102 / CH340 / FT232). Set its jumper to 3.3 V.
- Dupont leads. Do **not** connect the 12 V supply; the adapter's 3.3 V powers the ESP32 for this test.
- USB-to-UART adapter, **3.3 V logic** (CP2102 / CH343 / FT232; a CH340 clone needs the old
WCH 3.4 driver on Windows — see [[relay-proxy-firmware]]). Set its jumper to 3.3 V.
- Dupont leads. Do **not** connect the board's 12 V supply; the adapter's 3.3 V powers the ESP32.
- A PC with Python: `pip install esptool` (gives both `esptool.py` and `espefuse.py`).
## Wiring (DT-R0xx programming header)
## The debug header (DT-R004) — from the vendor's dev-board repo
| Adapter | Board |
| --- | --- |
| GND | GND |
| 3V3 | 3V3 |
| TXD | RXD (ESP32 GPIO3) |
| RXD | TXD (ESP32 GPIO1) |
| DTR | NRST (optional; lets esptool reset the board itself) |
Source: `raw/dingtian_dev_pinout/` (photos + GPIO table from
[dtlzp/relay_dev_demo](https://github.com/dtlzp/relay_dev_demo/tree/master/gpio_pinout)).
It is the **unlabelled pin header right next to the ESP32-WROOM-32D module**, left edge of the
board under the relays. **There is no BOOT switch on the board** — the only button is `FACTORY`
(IO34, the firmware's factory-reset button) and it plays no part in flashing. Download mode is
entered the bare-ESP32 way: **IO0 held to GND while NRST is pulsed to GND** (or while power comes
up).
Header labelling varies by revision; confirm against the silkscreen. GPIO1/3 are also the board's
Modbus UART, so expect the stock firmware to chatter on them when it boots.
| Pin (from the GND end) | ESP32 | Role |
| --- | --- | --- |
| 1 | GND | ground |
| 2 | IO3 | U0RXD — adapter **TX** goes here |
| 3 | IO1 | U0TXD — adapter **RX** goes here |
| 4 | NRST | reset, active LOW (adapter DTR/RTS or a jumper to GND) |
| 5 | IO0 | boot strap — **to GND for download mode** (also RMII_RST/PWR on this board) |
| 6 | 3.3V | power in from the adapter |
| 7, 8 (V2 boards only) | IO4, IO5 | CAN_RX / CAN_TX — not used for flashing |
V1 (hw V3.6.8 photo) has the 6-pin row; V2 adds IO4/IO5 for 8 pins. The order is identical.
Confirm GND with a multimeter against the terminal-block GND before powering anything.
## Procedure
1. Wire as above, adapter unplugged.
2. **Hold the board's boot switch** while plugging the adapter into USB. Keep holding ~1 s, release.
(Without DTR wired, this is the only way into download mode.)
1. Wire as above, adapter unplugged: GND↔GND, 3V3↔3.3V, adapter TX↔IO3, adapter RX↔IO1.
2. Jumper **IO0 to GND**. Then either hold **NRST to GND** for a second and release, or simply plug
the adapter in (power-on with IO0 low = download mode). If the adapter has DTR/RTS wired to
NRST and IO0, esptool can do this itself.
3. Identify the port: `COMx` on Windows, `/dev/ttyUSB0` on Linux. On WSL, pass the device through
or run from Windows.
4. Run:
```
esptool.py --port COM5 --baud 115200 chip_id
esptool.py --port COM5 --baud 115200 chip-id
```
5. If it connects, read the eFuses:
@@ -66,6 +83,8 @@ esptool.py --port COM5 --baud 115200 chip_id
espefuse.py --port COM5 summary
```
6. Remove the IO0 jumper before a normal boot.
## Reading the result
**Open (Development SKU):**
+82
View File
@@ -0,0 +1,82 @@
---
type: concept
tags: [parking, performance, incident, booth, relay, sqlite]
sources: []
updated: 2026-10-24
---
# park-2 event-loop stall → phantom relay timeouts (2026-10-24)
An incident analysis with a durable rule: **request cost must be bounded whatever the operator's
data volume**. Found while answering "why do some of a subscriber's entries have no snapshot".
## Symptom chain (as observed on park-2, stage-9659373)
1. Four signed `vehicle_entry` events for one subscriber had **no snapshot and no `sessions` row**.
2. Each coincided with `relay pulse FAILED … timeout` on the [[dingtian-relay]] and
`subscription-flow failed: timeout`. The subscription flow signed the ledger, then awaited the
pulse; the pulse helper rethrows, so the method unwound **before** firing the camera and
writing the session cache (see [[subscription]], `subscription-flow.ts`).
3. The relay was healthy: 60/60 UDP status probes from a separate process answered in 48–52 ms;
ping < 1 ms, no loss, link clean.
4. The server process was the problem. `GET /api/sessions/active` ran **~2 s, synchronously**,
2234× in 24 h (the booth polls it). `PayStation.activeSessions()` called `quote()` **per open
unpaid transient** (664 of them), each doing 3–4 **unindexed** `ledger_events` scans by
identity. Every other request queued behind it: reader pushes at 2 s, vision calls aborting,
forgive at 2 s.
5. Node runs **expired timers before pending socket I/O**. A pulse whose reply arrived during the
stall saw its 2 s timer fire first → "timeout" for a relay that had answered (and fired).
`tookMs` of the failures were 2000–2260 ms — the 2 s timer plus loop lag.
6. Growth: open unpaid transients +50–65/day since 2026-10-09 → ~120 ms/day added to the handler.
Successful-pulse median tracked it exactly (109 ms on 10-11 → 1330 ms on 10-21; p95 2290 ms on
10-24). The curve crossed the 2 s timeout around 10-19/10-22 — when the failures began.
## Why this is OUR defect (not the operator's)
The operator's choices (an unlimited card used 70×/day by a booth operator, 664 tickets that
never exited through the system) are **theirs to make**. Our defect is any code path whose cost
grows with their data. The user's stance, verbatim: "We are not running the business, we are
providing the software." Do not propose cleaning up or deciding about operator records.
## The fix (stage, uncommitted at time of writing)
- `activeSessions()` prices every row from **one** whole-ledger scan (per-identity grouping fed to
a rows-based `#quoteFromRows`) and builds the tariff resolver once. `quote(identity)` wraps the
same core with one identity-scoped read, so both paths price identically (pinned by
`pay-station.test.ts`). `validations.ts` gained `sessionValidationsFromRows`/
`liveValidationsFromRows`.
- Migration `0032_hot_path_indexes`: `ledger_events(identity, index)`,
`device_events(category, kind, occurred_at)`, `device_events(kind, occurred_at)`,
`snapshots(identity)`, `sessions(state)`, `sessions(subscription_id, state)`. Additive; the
previous image ignores them on rollback. The snapshots index costs one identity-column pass
(~50 ms measured, the blobs live in overflow pages).
- Dingtian `binaryUdp`: the timeout rejection is deferred with `setImmediate`, so a datagram that
already arrived wins over an expired timer (check phase runs after poll).
- Subscription flow: snapshot fired **before** the pulse; session cache written/closed **before**
the pulse. Evidence and the projection no longer depend on the relay call succeeding.
Expected effect on park-2's data: the handler drops from ~2 s to ~0.1–0.15 s (ledger scan 36 ms +
plate scan 78 ms, both now index-assisted), and stops growing with open-ticket count.
## The rule going forward
- **No per-row ledger reads in list views.** Fold once, price from the fold.
- **Every identity/telemetry lookup is indexed.** `ledger_events.identity`, `device_events`
(category, kind, time), `snapshots.identity`.
- **A device timeout must not race the event loop.** Defer timeout rejections one turn.
- **Evidence and projections before the pulse.** The signed event is the decision; the pulse is a
side effect that may fail.
- Watch `tookMs` on `kind:"relay"` [[device-events]]: a rising median with a healthy device is an
event-loop stall, not a network problem.
## Open follow-ups
- `GET /api/snapshots/by-identity` still loads **all** camera snapshot/read telemetry rows and
filters in JS (45 calls/day, ~50 ms, grows with telemetry). Filter by identity in SQL.
- Other `.all()` scans over `device_events`/`ledger_events` in list routes (feed, lane status)
deserve the same bounded-work review.
- Deploy: build the stage image, bump park-2's TAG (currently stage-9659373; the four commits
since touch no app code), watch the pulse `tookMs` and `/api/sessions/active` durations.
Related: [[booth-exit-flow]] (active list semantics), [[append-only-event-chain]],
[[device-events]], [[dingtian-relay]], [[appliance-provisioning]] (park-2 host history).
+223
View File
@@ -0,0 +1,223 @@
---
type: decision
tags: [parking, hardware, edge-controller, sbc, raspberry-pi, odroid, orange-pi, watchdog, cloud, fail-state]
sources: []
updated: 2026-10-22
status: open
---
# Edge controller — hardware options for the resilient core
> **Status: open (2026-10-22).** Research memo, no purchase yet. Prices are what a web search returned
> on 2026-10-22 and mix dates and currencies; every figure is to be re-checked at the vendor before
> ordering. Nothing here is verified on hardware.
## Why a Linux controller, not a flashed Dingtian
The [[relay-proxy-firmware]] PoC proved the shape: the device that owns the barrier relay and the
button inputs reports to the cloud on its own, power-cycles the booth PC, and takes relay commands
while the PC is dead. Two things it cannot do on an ESP8266/ESP32 decided this page:
1. **Every reader push, every ticket print, still goes to the booth PC.** The DT-008 readers HTTP-GET
the booth, the printer listens on TCP 9100 for the booth. With the PC down the cloud can pulse a
relay but cannot read a card or print a ticket. The takeover only works if the controller sits
**in front of every device**: readers and buttons push to the controller, which forwards to the
booth while it answers and acts alone when it does not. That is a real proxy and needs a TCP/IP
stack, a Node runtime for the existing drivers (`dingtian`, `dingtian-qr-reader`, ESC/POS render,
ticket Luhn), and local durable storage.
2. **The autonomous minimum** decided in discussion (2026-10-22): entry prints a ticket and opens;
exit fails open with a signed degraded-exit event; everything is logged locally and reconciled when
the booth returns ([[fail-state-safety]], [[open-questions]] "Cloud takeover mode"). Internet-down
is a separate question the owner is still thinking about; the controller must work with no uplink.
Watchdog policy from the same discussion: **take over at one missed probe** (1 s cadence, 1 s
timeout, same switch as the PC, reversible, harmless if wrong); **power-cycle the PC only when it is
dead at every layer** including ICMP, over a longer window, because a mains cut mid-update corrupts
a LUKS/SQLite box and a reboot takes over a minute. ICMP alive with HTTP dead = app down, not PC down.
The bench DT-R004 is the locked standard SKU ([[dingtian-relay]] "Can we flash our own firmware?"),
so the Dingtian stays what it is: a dumb relay board, optional once the controller has its own relays.
## Requirements (derived, not yet signed off)
| # | Requirement | Why |
| --- | --- | --- |
| R1 | ≥ 3 relays with **NO and NC** contacts (entry, exit, PC mains), ≥ 4 opto-isolated inputs (buttons, loops/radar) | The PC-mains cut needs an NC contact; [[barrier-not-a-door]] stays (pulse, never timed close) |
| R2 | Ethernet on the site LAN; **a second port is optional** | The booth, devices and router share one flat switch today ([[site-device-installation]]); an uplink-side port only matters if the LAN is split later |
| R3 | Linux (Debian/Ubuntu class), arm64 or x86, enough for Node + SQLite + the drivers; no vision | Reuse the booth's code; the autonomous minimum is tiny |
| R4 | **Hardware watchdog independent of the CPU**, **RTC with battery** | The controller is the thing that restarts others; fees depend on the clock ([[clock-integrity]]) |
| R5 | eMMC or NVMe, **not microSD** as the only storage | Unclean power cuts are the normal case here (park-2 incident 2026-10-17) |
| R6 | A **secure element** (ATECC608 or TPM) for a non-extractable signing key | The takeover design needs a second signer and asymmetric keys ([[hardware-signer-options]], [[open-questions]] takeover section) |
| R7 | 9–36 V DC input, fanless, DIN rail, ≥ 0…+60 °C, ideally a battery/UPS input | Booth cabinet in an Albanian summer; the controller must outlive the PC's power |
| R8 | Vendor supply promise and mainline or vendor-LTS kernel to ~2030 | Field appliances; no re-porting every two years |
| R9 | Modest unit cost; LTE **optional**, preferably as a separate router | The owner has not decided the internet-down policy |
## Candidates
### A. Raspberry Pi 5 + relay/input HAT (lab grade)
Pi 5 (board RTC with battery connector, bcm2835 watchdog driver, PCIe x1 for NVMe) plus a Sequent
Microsystems **Four Relays Four HV Inputs** HAT (4 × NO/NC relays 8 A, 4 opto inputs 3–48 V, stackable,
~€57–65; one retailer states Pi 5 support, another lists Zero–4 only — confirm). No secure element
(add an I²C ATECC608 breakout), no DIN enclosure, board rated for a desk, not a cabinet (the Pi 5
ambient rating is 0–50 °C — *unsourced, LLM prior; check the product brief*). Pi prices rose in
April 2026 with the memory market.
**Verdict:** the right thing to put the ported firmware on **now**, in the lab; not the field unit.
### B. Raspberry Pi Compute Module on an industrial carrier
| Carrier | Compute | Relays / inputs | Net | Power / UPS | RTC / WDT / SE | Temp | Price (found) |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **Sfera Labs Iono Pi Max v2** | CM4S (CM3+/CM3 also) | **4 × 6 A NO+NC relays**, 4 DI 0–40 V, 4 DT lines (Wiegand, 1-Wire) | 1 × 10/100 | 10–50 V DC, **built-in UPS for a 12/24 V lead-acid battery** | RTC (CR1220) · **independent HW watchdog** · **ATECC608** | **-20…+60 °C** | from €695 + tax |
| **Sfera Labs Strato Pi Max** (XS/XL) | **CM5** | via X2 expansion boards; analog and RS-485 X2 boards confirmed, a **relay/DI X2 board not confirmed** by the search | **2 × Ethernet** | DC in; RP2040 power management, dual SD redundancy | RTC · WDT · (SE on CM-less Zymbit SCM variant) | industrial | from $602 + tax |
| **Seeed reComputer R1100 / R2135-12** | CM4 (R1100) / **CM5 32 GB eMMC** (R2135 industrial) | R21xx: **4 DI, 4 DO (transistor, not relays)**, 2 × RS-485, 2 × RS-232, 2 × CAN FD | 1 GbE (+ 1 × 10/100 on R1000) | 9–36 V DC | RTC · WDT (check) · no SE | -20…+65 °C (reseller; R2130 desktop variant 0–45) | ~$390 (R1100) to ~$550 (R2130-12); R2135 price not found |
| **Revolution Pi Connect 5** + **RevPi RO** | **CM5**, 32 GB eMMC | on board: 1 DI (24 V), 1 SSR; **RevPi RO** adds relays via PiBridge | **2 × GbE**, RS-485, CAN FD | 24 V DC | RTC · WDT · no SE | industrial (Kunbus) | €536–687 + RO €153 |
**Verdicts.** The **Iono Pi Max v2** is the only unit that meets R1, R4, R5, R6 and R7 **out of the
box**, UPS included, and its ATECC608 is exactly the part [[hardware-signer-options]] wanted for the
controller. Its weaknesses are a single 10/100 port (enough: readers push a few bytes, the printer a
few kB; no camera traffic ever goes through the controller) and the older CM4S. The **Strato Pi Max**
is the stronger platform (CM5, two ports) if Sfera confirms a relay/DI X2 board; ask before ruling it
out. **Seeed** is the LTE-friendly option (module slot) but its outputs need an external relay block
and it has no secure element. **RevPi** is the most PLC-like and the most expensive once relays are
added; overkill for three relays.
### C. Rockchip SBCs (Orange Pi, ODROID, Radxa, FriendlyElec)
| Board | SoC | Storage | Net | RTC | Temp | Software | Price (found) |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **ODROID-M2** | RK3588S2 | **64 GB eMMC HS400** on board, M.2 | 1 GbE | PCF8563 on board | not listed | Hardkernel Ubuntu (20.04 at launch; 24.04 promised), **Armbian standard**, 6.18 kernel | $180 (4 GB) – $300 (16 GB) |
| **ODROID-M1S** | RK3566 | 32/64 GB eMMC on board | 1 GbE | battery connector | not listed | Ubuntu 20.04/22.04 images; Armbian | $79–148 |
| **Orange Pi 5 Plus** | RK3588 | eMMC socket, M.2 | **2 × 2.5GbE** | HYM8563 | 0…+70 °C (one listing) | Armbian; Orange Pi 5 Pro mainline DT only at patch v4 in March 2026; Armbian once called the Pro/Max/Ultra "entirely unsupported" | ~$109 (8 GB) – $129 launch era |
| **Orange Pi Zero 3** | Allwinner H618 | SD + SPI | 1 GbE | no | — | **mainline since 6.5, Armbian standard** | cheap |
| **Radxa ROCK 5C** | RK3588S2 | SD, eMMC module, M.2 | 1 GbE | yes | — | **Armbian platinum** (vendor-backed) | $166 (4 GB) |
| **Radxa E24C / E54C** | RK3528A / RK3582 | eMMC options | **4 × GbE** | — | — | router form factor; GPIO exposure to confirm | $35 / $55 |
| **FriendlyElec NanoPi R3S-LTS** | RK3566 | **32 GB eMMC** | **2 × GbE** | — | 0…+80 °C "measuring" | **LTS part**, Armbian; metal case $7 | $38 (1 GB) – $53 (2 GB/32 GB + case) |
| **FriendlyElec NanoPi R6S** | RK3588S | 32 GB eMMC | 2 × 2.5GbE + 1 GbE | — | 0…+70 °C | **Armbian platinum** | $212–265 |
**Verdicts.** None has relays, a watchdog you can trust independently, a secure element or a DIN
enclosure; all of that is add-on boards and a case. What they offer is **eMMC on board at a low
price** (ODROID, NanoPi) and **two Ethernet ports** (Orange Pi 5 Plus, NanoPi, Radxa E). The
**NanoPi R3S-LTS** is the cheapest serious candidate: eMMC, two ports, an LTS promise, Armbian, under
$60 with case; relays would come from a USB or RS-485 relay module (Sfera **Iono RP**, RP2040-based,
4 × 6 A relays, 12–28 V, RS-485, is a clean fit). **Orange Pi** is the best spec per dollar and the
worst bet on software: the 5-series boards reached mainline only this year and Armbian support has
flip-flopped; the Zero 3 is well supported but has no eMMC. **ODROID-M2** is the solid middle:
eMMC and RTC on board, Armbian standard, vendor Ubuntu, pitched at embedded builders, but still a
bare board.
### D. Industrial-first boards
- **Olimex STMP157-OLinuXino-LIME2** (STM32MP157, dual Cortex-A7 650–800 MHz, 1 GB, GbE, eMMC
option, battery-backed RTC): **-EXT -25…+85 °C, -IND -45…+85 °C**, open hardware, mainline Linux,
**supply promised until 2036**, €53–71. Enough CPU for the autonomous minimum (Node on armv7 is
slow but fine for a few requests a minute), not for anything more. Relays via Olimex's own
UEXT/MOD relay boards or an Iono RP. The cheapest board that is honestly industrial.
- **Teltonika TRB255 / RUT956** (LTE gateways with DI/DO; RUT956 has a relay): RutOS is OpenWrt, custom
apps ship as `.ipk`, the SDK moves to a new build system at RutOS 7.25. Not a Node host. **Role:
the LTE router in front of whichever controller is chosen**, if the internet-down policy ever wants
cellular; not the controller.
### E. x86: ODROID-H4+ (Intel N97, 2 × 2.5GbE, 4 × SATA, M.2, fanless, $130–275 before RAM/SSD)
Runs the **existing x86 container images unchanged** (no arm64 build), has the N97's firmware TPM
for the signer, and is in effect a second, smaller booth PC. No relays, no DIN, no DC-input range
to speak of; relays via USB. Worth keeping in view only if the arm64 port turns out to be the
expensive part.
## Cross-cutting notes
- **Secure element.** Only the Sfera units ship one. Elsewhere: an I²C **ATECC608** breakout (a few
euros, the part [[atecc608]] already describes) on any board with a 40-pin header, or a Zymbit
HSM6/HSM60 module for Pi (HSM6 $125, listed sold out; HSM60 for Compute Modules released December
2025). x86 brings a TPM. Whatever is chosen, the ledger signer must go asymmetric first (today
HMAC-SHA256 in `SoftwareSigner`): a cloud or a controller cannot verify an HMAC chain without
holding the key that forges it.
- **Watchdog.** The Pi's on-SoC watchdog (bcm2835_wdt) resets the Pi itself; it does not help if the
kernel is fine and the app is wedged, and nothing external resets a Rockchip board. The Sfera
carriers put a separate watchdog chip in front of the CM; the others need the app-level watchdog
plus a power-cycle path. For the **PC-mains relay** on any board, the boot-time relay state must be
verified on the bench before field use (the Tasmota "relays blip at boot" report on Dingtian,
[[dingtian-relay]]) — with NC wiring a blip is a PC power cut.
- **arm64 images.** The booth images are built for the OptiPlex (x86). Everything except E needs an
arm64 build of a server subset in `build-images.yml` ([[container-deployment]]); better-sqlite3 has
arm64 prebuilds, the vision service is never on the controller.
- **Second Ethernet port.** Not needed while the site LAN is one flat switch; it becomes useful only
if the controller is later made the gateway between device VLAN and uplink ([[network-isolation]]).
Do not pay for it yet.
- **Raspberry Pi supply.** CM5 in production **until at least January 2036**; prices rose in April
2026 (memory). CM5 ranges $67.50 (2 GB Lite) upward; eMMC 16/32/64 GB.
## Recommendation (to confirm with the owner)
1. **Order one Sfera Labs Iono Pi Max v2** for the field candidate: relays with NC contacts, UPS,
watchdog, RTC, ATECC608, DIN, -20…+60 °C, Raspberry Pi OS. Ask Sfera in the same mail whether a
relay/DI X2 board exists for the Strato Pi Max (CM5, two ports); if yes, compare before paying.
2. **Port the relay-proxy logic to Node on a Pi 5 + Sequent HAT now**, since that work is identical
for A and B and the lab has no CM carrier yet. The Node port is also what makes the readers and the
printer proxyable.
3. **Keep NanoPi R3S-LTS + Iono RP** as the budget alternative (~$60 + the IO module) if unit cost
turns out to dominate across many sites, and **ODROID-M2** if more CPU is wanted on a bare board.
Rule out Orange Pi for field units until its mainline/Armbian status holds for a year.
4. **LTE stays a router question** (Teltonika in front), decided together with the internet-down
policy, not inside the controller.
## Relates
- [[relay-proxy-firmware]] — the PoC this replaces the hardware for; its wire-contract emulation and
watchdog logic carry over.
- [[fail-state-safety]], [[barrier-not-a-door]] — the rules the autonomous minimum must keep.
- [[hardware-signer-options]], [[atecc608]], [[append-only-event-chain]] — the signer the controller
needs, and why asymmetric.
- [[cloud-service-saas]] — the cloud the controller reports to; "cloud makes resolution nicer, not
possible".
- [[esp32-custom-controller]], [[esp32-flashability-test]] — the microcontroller path this supersedes
for the controller role.
- [[open-questions]] — #1 lane topology, #2 failure modes, #6 secure element, and the takeover section.
## Sources (web, 2026-10-22)
- Sfera Labs: [Iono Pi Max v2](https://sferalabs.cc/product/iono-pi-max-v2/) ·
[Strato Pi Max](https://sferalabs.cc/product/strato-pi-max/) ·
[Strato Pi Max on CM5](https://sferalabs.cc/blog/sfera-labs-strato-pi-max-is-now-powered-by-the-raspberry-pi-compute-module-5/) ·
[X2 analog boards](https://www.electropages.com/2025/03/new-analog-io-boards-improve-versatility-modular-industrial-controller) ·
[Iono RP](https://www.mouser.bg/new/sfera-labs/sfera-labs-iono-rp-io-module)
- Seeed: [reComputer R1000 wiki](https://wiki.seeedstudio.com/recomputer_r/) ·
[R21xx getting started](https://wiki.seeedstudio.com/recomputer_industrial_R21xx_getting_start/) ·
[R20xx getting started](https://wiki.seeedstudio.com/recomputer_industrial_r20xx_getting_start/) ·
[R1124-10 listing](https://openelab.com/products/seeed-studio-recomputer-r1124-10) ·
[R2130-12 listing](https://openelab.io/products/seeed-studio-recomputer-ai-r2130-12)
- Revolution Pi: [products and prices](https://revolutionpi.com/en/ordering/overview-products-and-prices) ·
[RevPi Connect 5](https://revolutionpi.com/shop/en/revpi-connect-5) ·
[Helmholz overview](https://www.helmholz-benelux.eu/revolution-pi/)
- Raspberry Pi: [Compute Module 5](https://www.raspberrypi.com/products/compute-module-5/) ·
[price history](https://raspberry.tips/en/raspberrypi-infos/raspberry-pi-prices-lifecycle) ·
[DigiKey CM5](https://www.digikey.com/en/product-highlight/r/raspberry-pi/raspberry-pi-compute-module-5)
- Sequent Microsystems: [Four Relays Four HV Inputs](https://sequentmicrosystems.com/products/four-relays-four-inputs-for-raspberry-pi) ·
[RobotShop listing](https://ca.robotshop.com/products/sequent-microsystems-4-relays-4-inputs-8-layer-stackable-hat-raspberry-pi) ·
[Elektronica voor Jou listing](https://elektronicavoorjou.nl/en/product/4-relay-and-4-hv-inputs-hat-rpi)
- ODROID: [M2 8 GB](https://www.hardkernel.com/shop/odroid-m2-with-8gbyte-ram/) ·
[M2 forum intro](https://forum.odroid.com/viewtopic.php?t=48953) ·
[M1S](https://www.hardkernel.com/shop/odroid-m1s-with-4gbyte-ram/) ·
[Armbian ODROID-M2](https://armbian.com/boards/odroidm2) ·
[H4 family](https://www.cnx-software.com/2024/04/16/odroid-h4-a-compact-alder-lake-n-series-sbc-with-up-to-dual-2-5gbe-and-four-sata-iii-ports/) ·
[H4 prices](https://ameridroid.com/products/odroid-h4-h4-h4-ultra)
- Orange Pi: [5 Plus specs](https://cnx-software.com/?p=113717) ·
[5 Pro mainline patches](https://lkml.iu.edu/hypermail/linux/kernel/2603.1/03319.html) ·
[Armbian 5 Pro](https://armbian.com/boards/orangepi5pro) ·
[Armbian Zero 3](https://armbian.com/boards/orangepizero3) ·
[Armbian forum on Pro/Max/Ultra](https://forum.armbian.com/topic/52148-any-working-orangepi5-pro-image/)
- Radxa: [ROCK 5C](https://radxa.com/products/rock5/5c/) · [E24C/E54C](https://www.cnx-software.com/2025/07/15/radxa-e24c-and-e54c-rockchip-rk3528a-rk3582-network-computers-features-four-gigabit-ethernet-ports/)
- FriendlyElec: [R3S-LTS](https://www.friendlyelec.com/index.php?route=product%2Fproduct&product_id=311) ·
[R6S wiki](https://wiki.friendlyelec.com/wiki/index.php/NanoPi_R6S) ·
[R3S wiki](https://wiki.friendlyelec.com/wiki/index.php/NanoPi_R3S)
- Armbian: [26.8 release](https://blog.armbian.com/armbian-release-26-8/) · [boards](https://armbian.com/boards)
- Olimex: [STMP1 family](https://www.olimex.com/Products/OLinuXino/STMP1/open-source-hardware) ·
[LIME2](https://www.olimex.com/Products/OLinuXino/STMP1/STMP157-OLinuXino-LIME2/open-source-hardware) ·
[Mouser LIME2H-EXT](https://www.mouser.com/ProductDetail/Olimex-Ltd/STMP157-OLinuXino-LIME2H-EXT?qs=TCDPyi3sCW25CD1cRx3nCA%3D%3D)
- Teltonika: [TRB255 I/O](https://wiki.teltonika-networks.com/view/TRB255_Input/Output) ·
[RUT956 I/O](https://wiki.teltonika-networks.com/index.php?mobileaction=toggle_view_desktop&title=RUT956_Input%2FOutput) ·
[RutOS SDK](https://wiki.teltonika-networks.com/view/RUTOS_Software_Development_Kit_(SDK)_Instruction) ·
[custom app as .ipk](https://community.teltonika.lt/t/rut956-application-installation-deployment-options/18735)
- Zymbit: [HSM6](https://store.zymbit.com/products/hsm6) · [docs](https://docs.zymbit.com/) ·
[SCM](https://linuxgizmos.com/zymbit-secure-module-features-raspberry-pi-cm4/)
+4
View File
@@ -186,4 +186,8 @@ events happen that the site's [[atecc608]] signer never saw. Unresolved by desig
cloud-authored, separately signed segment the booth ingests and countersigns on return, with the
gap recorded rather than hidden. Without it, takeover is a fraud lever (pull the PC's power).
Also: exit must still fail open by hardware when the uplink is down too ([[fail-state-safety]]).
Discussion 2026-10-22: the booth's signing key stays on the booth; the cloud and the controller sign
with their own keys and the booth appends one signed "ingested segment X, gap from–to" event on
return. That requires **asymmetric** ledger signing first (today HMAC-SHA256: whoever verifies holds
the key that forges). Hardware for the controller: [[edge-controller-hardware]].
+17
View File
@@ -44,3 +44,20 @@ The decisions treated as settled in the design notes. (See [[parking-system-arch
[[entry-exit-readers]]).
Unsettled items live in [[open-questions]].
## No custom firmware on the Dingtian relay (2026-10-23)
The [[dingtian-relay]] stays stock. The vendor locks the standard SKU, the bench unit was never
wired for a lock test, and the user chose to stop here: booth-PC resilience (the park-2 failures)
is pursued through **mini PCs**, not through turning the relay board into a proxy. The
[[relay-proxy-firmware]] PoC is retired; it remains a usable Dingtian **emulator** for the bench.
## Bounded request cost, whatever the operator's data (2026-10-24)
Request handlers must do work bounded by the **page they render**, never by the operator's
accumulated data. No per-row ledger reads in list views (fold once, price from the fold); every
identity/telemetry lookup indexed; device timeouts deferred one loop turn so they cannot race a
reply; evidence (snapshot) and projections written **before** the barrier pulse. We do not
propose cleaning up or deciding about the operator's records to make the software fast — the
owner runs the business, we provide the software. Origin: [[park-2-event-loop-stall]].
+20 -5
View File
@@ -2,7 +2,7 @@
type: entity
tags: [parking, hardware, access-control, relay]
sources: []
updated: 2026-10-22
updated: 2026-10-23
---
# Dingtian Relay Controller
@@ -170,12 +170,19 @@ On assign the driver runs `harden()` (the [[device-registry|HardenableDevice]] c
> drop connections (ECONNRESET), locking out the API the driver depends on — recoverable only by
> factory reset. `harden()` deliberately never touches it.
## Can we flash our own firmware? (2026-10-22)
## Can we flash our own firmware? (2026-10-22) — **RETIRED 2026-10-23**
> **Decision (user, 2026-10-23): not pursuing custom Dingtian firmware.** The bench unit is the
> standard (locked) SKU and the user chose not to wire the debug header. Booth resilience will be
> pursued with **mini PCs** instead ([[appliance-provisioning]] line); the Dingtian stays a stock,
> dumb relay+input board behind the host. The notes below remain for reference only.
The DT-R0xx boards are **ESP32-WROOM-32D** designs (the module is visible in product photos; the
community ESPHome/Tasmota configs target ESP32). Relays/inputs are behind **74HC595 / 74HC165
shift registers** (SDI GPIO13, CLK GPIO14, RCK GPIO15, PL GPIO32, Q7 GPIO16); Ethernet is a
**JL1101 PHY** (MDC 23, MDIO 18, clock out 17, power 0). Community firmware exists: Tasmota
community ESPHome/Tasmota configs target ESP32). On the 2/4-channel boards relays and inputs are **direct GPIOs**
(DT-R004: relays IO16/IO2/IO32/IO12, inputs IO36/IO39/IO33/IO35); 8/16/32-channel boards use
**74HC595 / 74HC165 shift registers** (SDI 13, CLK 14, RCK 15, PL 32, Q7 16). Ethernet is a
**JL1101 PHY** (MDC 23, MDIO 18, clock out 17, power/reset IO0). Debug header + GPIO table:
[[esp32-flashability-test]] / `raw/dingtian_dev_pinout/`. Community firmware exists: Tasmota
templates (Dingtian ships them in its own download centre) and an ESPHome external component
`dtr0xx_io`.
@@ -233,3 +240,11 @@ keep the stored value).
password → `&2&/&`). Confirmed the device validates the old creds. **Also confirmed the CGI API
needs NO auth** (config dump + `userset.cgi` return 200 unauthenticated) → rotation is cosmetic.
- ⬜ Next: wire the actual entry flow (input event → signed event + print ticket → `pulseOpen`).
## Phantom "timeout" under a server event-loop stall (2026-10-24)
A relay `timeout` with `tookMs` just over the 2 s limit, while the device answers status probes in
~50 ms, is **not** a device or network fault: the server's event loop was blocked (a ~2 s
synchronous handler) and Node ran the expired timer before the queued UDP reply. The relay did
fire. Fix: `binaryUdp` now defers the timeout rejection with `setImmediate`, and the stalling
handler was rewritten. Full analysis: [[park-2-event-loop-stall]].
+13 -3
View File
@@ -2,11 +2,16 @@
type: entity
tags: [parking, hardware, firmware, esp8266, dingtian, cloud, watchdog, poc]
sources: []
updated: 2026-10-22
status: poc
updated: 2026-10-23
status: retired
---
# relay-proxy — Dingtian emulator + cloud proxy/watchdog firmware (PoC)
# relay-proxy — Dingtian emulator + cloud proxy/watchdog firmware (PoC, retired)
> **Retired 2026-10-23.** The Dingtian-firmware path this PoC seeded is dropped (user decision:
> focus on mini PCs for booth resilience). The code stays in `firmware/relay-proxy/` as a working
> Dingtian protocol emulator — still useful as a **bench stand-in when no real relay board is on
> hand** — and the watchdog/heartbeat ideas carry over to whatever runs beside the booth PC.
Code: `firmware/relay-proxy/` (PlatformIO, Arduino framework; NodeMCU v3 / ESP8266 now, ESP32
env planned for the real [[dingtian-relay]]). Throwaway cloud stand-in: `poc/cloud-standin.mjs`.
@@ -63,6 +68,11 @@ watchdog flipped to `booth UP` the moment port 80 opened.
or `STATIC_IP`.
- ESP8266 limits (Wi-Fi only, ~40 KB heap, blocking HTTP) are PoC-only; the target is the ESP32
on the Dingtian with Ethernet. Camera traffic is never proxied by the microcontroller.
- **Superseded as a hardware target (2026-10-22):** the takeover only works if the controller also
fronts the readers and the printer, which needs a Linux box with a Node runtime; the microcontroller
cannot. Hardware options and the watchdog policy (take over at one missed probe, power-cycle only when
the PC is dead at every layer) are on [[edge-controller-hardware]]. The emulation and watchdog logic
here carry over to the port.
## Bench note: NodeMCU v3 clone CH340 vs WCH driver
+6 -4
View File
@@ -1,13 +1,13 @@
---
type: overview
tags: [parking, index]
updated: 2026-07-02
updated: 2026-10-22
---
# Index
Content catalog for the wiki. Start at [[overview]]. Maintained on every ingest.
Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
Counts: 4 sources · 19 entities · 47 concepts · 9 decision records.
## Overview & navigation
- [[overview]] — the top-level synthesis and entry point.
@@ -46,7 +46,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[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`).
- [[relay-proxy-firmware]] — PoC (2026-10-22): NodeMCU firmware that IS a DT-R004 to the booth (binary/string UDP, config CGI, userset, Digest push) + cloud heartbeat/command/watchdog (power-cycles the PC). Verified against the emulator; booth integration blocked on park-lab ufw.
- [[relay-proxy-firmware]] — RETIRED 2026-10-23 (mini PCs instead). PoC (2026-10-22): NodeMCU firmware that IS a DT-R004 to the booth (binary/string UDP, config CGI, userset, Digest push) + cloud heartbeat/command/watchdog (power-cycles the PC). Verified against the emulator and end to end at park-lab (2026-10-22, after the ufw rule).
- [[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.
@@ -71,7 +71,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[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.
- [[esp32-flashability-test]] — BENCH RUNBOOK (2026-10-22): is this ESP32 board locked? `esptool chip_id` + `espefuse summary` on the Dingtian DT-R0xx programming header; read-only; locked = standard SKU, open = Development Board Version.
- [[esp32-flashability-test]] — shelved (Dingtian flashing retired 2026-10-23). BENCH RUNBOOK (2026-10-22): is this ESP32 board locked? `esptool chip_id` + `espefuse summary` on the Dingtian DT-R0xx programming header; read-only; locked = standard SKU, open = Development Board Version.
- [[device-input-flow]] — button → device push → backend decides → relay; backend is source of truth.
- [[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.
@@ -101,6 +101,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[tariff-time-tiers]] — BUILT (V2 tariff): happy-hour/off-peak/weekend/seasonal + vehicle category + flat rate via wall-clock windowed cards; tz frozen per version.
- [[tariff-industry-survey]] — 2026-07 web survey of industry tariff structures: coverage map vs our engine; gaps = early bird (pick-table-by-entry-time) + merchant validations; per-minute & dynamic pricing ruled out.
- [[booth-exit-flow]] — manned booth: pay → voucher (self-exit later) or immediate exit; active sessions; audited barrier re-open.
- [[park-2-event-loop-stall]] — INCIDENT 2026-10-24: `/api/sessions/active` ran ~2 s synchronously (per-row unindexed ledger scans × 664 open unpaid tickets), froze the event loop, and made healthy Dingtian pulses report "timeout" (timers run before socket I/O) → signed entries with no snapshot/session row. Fix: fold-once pricing, hot-path indexes (0032), deferred UDP timeout, evidence before pulse. Rule: bounded request cost whatever the operator data.
- [[operator-issued-entry]] — operator mints an entry ticket when the physical button is broken; presence-gated (radar AND camera, both sides), flagged (source=manual + operatorInitiated + anomaly), capacity-override allowed; needs `session:create` (2026-07-01).
- [[plate-reconciliation]] — ANPR plate-as-invariant catches the ticket-swap fraud (paid car let out on a fresh $0 ticket, original lingers "inside"); exact/high-conf match vs open sessions; booth = flag + operator override, reader = log-only fail-open (2026-07-01).
- [[shift]] — manned-only accountability period; explicit Start/End; End → signed + printed Z-report; drawer float carries across shifts. Drawer cash movements (operator records, admin reviews via signed cash_review — a flag, not a reversal) live at the /drawer route (2026-07-01).
@@ -151,3 +152,4 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
- [[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.
- [[appliance-provisioning]] — booth-PC provisioning runbook (Dell 7070, i5-8500, discrete Nuvoton TPM): BIOS/Secure-Boot → direct-flash Ubuntu 26.04 USB (not Ventoy) → passphrase-LUKS install → manual PCR-7 TPM seal (workaround for the installer's dbt PCR_UNUSABLE error) → Docker. Verified on hardware 2026-06-23; TPM auto-unlock works.
- [[edge-controller-hardware]] — 🟡 OPEN (2026-10-22): research memo for the resilient core's hardware (the Linux controller that fronts every device, takes over at one missed probe, power-cycles the PC only when it is dead at every layer). Requirements R1–R9; candidates Pi 5 + HAT (lab), CM4/CM5 industrial carriers (Sfera Iono Pi Max v2 / Strato Pi Max, Seeed reComputer, RevPi), Rockchip SBCs (ODROID-M2/M1S, Orange Pi 5 Plus/Zero 3, Radxa, NanoPi R3S-LTS), Olimex, Teltonika as the LTE router, ODROID-H4+ x86. Recommendation: order an Iono Pi Max v2, port the proxy to Node on a Pi 5 now.
+37
View File
@@ -3579,3 +3579,40 @@ configured the board (relay_pw, udp2 off, login rotated, Digest push to 10.0.10.
Board registered through park-lab setup; assign flow applied every step; FLASH press → Digest push
accepted by the booth (401→200, "input 1 on (push)") and mirrored to the cloud stand-in with
booth_status 200. See [[relay-proxy-firmware]].
## [2026-10-22] query | Edge controller hardware: SBC-class options for the resilient core
Owner's conclusion after the relay-proxy PoC: the controller must process events alone, so it fronts
every device (readers, printer, relays) and takes over at **one** missed 1 s probe; the PC power-cycle
stays slow and ICMP-gated. Web survey filed as [[edge-controller-hardware]] (requirements R1–R9;
Pi 5 + Sequent HAT for the lab; Sfera Iono Pi Max v2 the only unit with relays NO+NC, UPS, independent
watchdog, RTC and ATECC608 on board, from €695; Strato Pi Max CM5 if a relay X2 board exists; Seeed
reComputer, RevPi; ODROID-M2/M1S, Orange Pi 5 Plus (software a gamble), NanoPi R3S-LTS (~$60, eMMC,
LTS), Radxa; Olimex LIME2 industrial to 2036; Teltonika only as the LTE router; ODROID-H4+ as the
x86 no-rebuild path). Recommendation: order an Iono Pi Max v2, port the proxy to Node on a Pi 5 now.
Also recorded: takeover needs asymmetric ledger signing ([[open-questions]]); index line for
[[relay-proxy-firmware]] corrected (integration verified, not blocked).
## [2026-10-23] ingest | Dingtian dev-board pinout (vendor repo dtlzp/relay_dev_demo → raw/dingtian_dev_pinout/)
DT-R004 debug header is the unlabelled row next to the ESP32: GND, IO3(RX), IO1(TX), NRST, IO0,
3.3V (+IO4/IO5 on V2). No BOOT switch exists — FACTORY (IO34) is a firmware button; download mode =
IO0 to GND + reset. 2/4ch boards are direct-GPIO (no shift registers). Runbook
[[esp32-flashability-test]] and [[dingtian-relay]] corrected.
## [2026-10-23] decision | Custom Dingtian firmware retired; booth resilience via mini PCs
User: no UART wiring, not worth pursuing. [[standing-decisions]] entry added; [[relay-proxy-firmware]]
marked retired (kept as a bench emulator); [[esp32-flashability-test]] shelved; [[dingtian-relay]]
section annotated.
## [2026-10-24] query | Why did a park-2 subscriber's entries have no snapshot? → event-loop stall
Traced on park-2 (read-only DB queries + container logs): 4 signed entries with no snapshot/session
row all coincided with Dingtian pulse "timeouts"; the relay answered 60/60 probes in ~50 ms. Root
cause: `GET /api/sessions/active` ~2 s synchronous (quote() per open unpaid transient, 664 rows,
unindexed ledger scans), 2234 calls/day; Node runs expired timers before queued UDP replies. Filed
[[park-2-event-loop-stall]]; standing decision "Bounded request cost"; notes on [[dingtian-relay]]
and [[booth-exit-flow]]. Code fix on stage (uncommitted): fold-once pricing in `pay-station.ts`,
migration 0032 indexes, `setImmediate` timeout in `access-dingtian.ts`, snapshot/cache before pulse
in `subscription-flow.ts`. 390/390 server tests, 6/6 Dingtian tests pass.
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+2
View File
@@ -0,0 +1,2 @@
Source: https://github.com/dtlzp/relay_dev_demo/tree/master/gpio_pinout (Dingtian vendor dev-board demo, MIT), fetched 2026-10-23.
debug_port_4CH.png / debug_port_4CH_V2.png = photos of the DT-R004 debug header (V1 6-pin, V2 8-pin); 4ch.png = GPIO table.
Binary file not shown.

After

Width:  |  Height:  |  Size: 508 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB