refactor(setup): unify controller I/O — event-driven relays[] + generic inputs[]
Build desktop / desktop (push) Successful in 4m16s
Build & push images / images (push) Successful in 2m43s
CI / check (push) Successful in 38s

The controller new/edit modal hardcoded both its outputs and its inputs, so an
operator could neither add a generic event-driven relay nor a free-standing input
(e.g. a second radar at the exit). This unifies both into symmetric, first-class
lists. Behaviour for existing booths is unchanged (back-compat, no DB migration).

Outputs — one event→action relays[] list:
- A relay is "when EVENT X happens, do its action": entry/exit/both pulse a
  barrier; a new `radarAlert` event drives a non-barrier alert lamp (blink while
  its trigger input is active, SOLID once the camera confirms a car).
- Dropped the separate config.buttonLight block — the lamp is just a relays[] row
  with direction:"radarAlert" (triggerInput + blink cadence). `alertRelaysOf()`
  replaces `buttonLightOf()`; ButtonLightController keeps its proven 3-state
  machine (serialized UDP, fail-OFF, hot-reload), now keyed per controllerId:relay
  so several alert lamps on one controller run independently. Every barrier
  resolver skips radarAlert rows (no auto-open; barrier-not-a-door intact).

Inputs — one first-class config.inputs[] list (the twin of relays[]):
- Each row is { input, role, relay?, kind?, activeLow?, cooldownSec? } with a
  "+ Add input" button. role ∈ button | presence | alertTrigger; button/presence
  name the relay they serve. An exit radar is just another presence row.
- Keystone `inputsOf(row)`: returns config.inputs[] or SYNTHESIZES it from the
  legacy relays[].button/presenceInput/... fields, so relayForButton /
  relayForPresence resolve identically from either shape — zero-downtime, no
  migration. entry-flow.ts is unchanged (resolves through the same functions).
- Fixed a latent bug this exposed: the alert lamp's camera lock was hardcoded to
  the ENTRY camera. Added relays[].lockLane ("entry"|"exit", default entry); the
  lamp now locks on its own lane's camera, so an exit radar's lamp tracks the exit
  camera. button-light tracks both #entryBusy/#exitBusy.
- Driver: extracted activeLowFrom(config) — merges inputs[] activeLow, legacy
  relays[].presenceActiveLow, and the inputActiveLow escape hatch.

UI: the relay dropdown gained a "Radar alert" option (reveals trigger/lock/blink
inputs); InputEditor is rewritten to a generic list (role select folds loop/radar);
i18n sq+en kept at type-parity.

Tests: new device-resolve.test.ts (inputs[] resolution + legacy fallback identical
+ exit-radar resolves to the exit relay); button-light gains a two-independent-
alert-relays case and an exit-lamp lockLane case; access-dingtian gains
activeLowFrom cases. Full workspace build/lint/test green (i18n parity included).

Wiki + memory updated (button-light-indicator, entry-double-press, dingtian-relay).

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-28 11:23:15 +02:00
parent 25a72ff20a
commit 4418594af0
15 changed files with 970 additions and 444 deletions
+109 -14
View File
@@ -7,12 +7,13 @@ import { ButtonLightController } from "./button-light.js";
import { deviceEvents } from "./device-events.js";
import { silentLogger } from "./test-helpers.js";
// ButtonLightController: the entry-button lamp on a spare relay, driven by the RADAR
// input vs. the camera lane status. Truth table:
// radar present + lane busy -> SOLID on
// radar present + lane free -> BLINK (~1 Hz)
// otherwise -> OFF
// Lamp is a non-barrier aux output; fails OFF; de-dupes redundant writes.
// ButtonLightController: alert (radarAlert) relays — the entry-button lamp on a spare
// relay, driven by the lamp's trigger input vs. the camera lane status. Truth table:
// trigger active + lane busy -> SOLID on
// trigger active + lane free -> BLINK (~1 Hz)
// otherwise -> OFF
// Lamp is a non-barrier aux output; fails OFF; de-dupes redundant writes. A controller may
// carry several alert relays (each its own row + trigger input), keyed independently.
let db: Db;
const CONTROLLER = "ctl-1";
@@ -45,8 +46,8 @@ beforeEach(() => {
relays: [
{ relay: 1, direction: "entry", button: 1, presenceInput: RADAR_INPUT, presenceKind: "radar" },
{ relay: 2, direction: "exit" },
{ relay: LAMP_RELAY, direction: "radarAlert", triggerInput: RADAR_INPUT, blinkOnMs: 500, blinkOffMs: 500 },
],
buttonLight: { relay: LAMP_RELAY, blinkOnMs: 500, blinkOffMs: 500 },
},
enabled: true,
}).run();
@@ -199,8 +200,8 @@ describe("ButtonLightController truth table", () => {
ctl.stop();
});
it("ignores controllers without a buttonLight config", () => {
// A second controller, no lamp.
it("ignores controllers without an alert relay", () => {
// A second controller, no alert relay.
db.insert(devices).values({
id: "ctl-2",
category: "access",
@@ -215,8 +216,8 @@ describe("ButtonLightController truth table", () => {
ctl.stop();
});
it("picks up a button light ADDED after start() (no restart needed)", async () => {
// Fresh controller with a radar input but NO buttonLight yet.
it("picks up an alert relay ADDED after start() (no restart needed)", async () => {
// Fresh controller with a radar input but NO alert relay yet.
const calls: Array<{ ch: number; on: boolean }> = [];
const aux = fakeAux(calls);
const ctl = new ButtonLightController(db, silentLogger(), () => aux);
@@ -240,13 +241,15 @@ describe("ButtonLightController truth table", () => {
radar(false);
await flush();
// Admin saves a button light (relay 3) — without restarting the server.
// Admin saves an alert relay (relay 3, trigger I2) — without restarting the server.
db.update(devices)
.set({
config: {
host: "10.0.0.5",
relays: [{ relay: 1, direction: "entry", presenceInput: RADAR_INPUT, presenceKind: "radar" }],
buttonLight: { relay: LAMP_RELAY, blinkOnMs: 500, blinkOffMs: 500 },
relays: [
{ relay: 1, direction: "entry", presenceInput: RADAR_INPUT, presenceKind: "radar" },
{ relay: LAMP_RELAY, direction: "radarAlert", triggerInput: RADAR_INPUT, blinkOnMs: 500, blinkOffMs: 500 },
],
},
})
.where(eq(devices.id, CONTROLLER))
@@ -259,4 +262,96 @@ describe("ButtonLightController truth table", () => {
expect(ctl.confirmedOf(CONTROLLER)).toBe(true);
ctl.stop();
});
it("drives two alert relays on one controller independently", async () => {
const R3 = 3;
const R4 = 4;
const I2 = 2;
const I3 = 3;
// Controller with two alert lamps, each on its own trigger input.
db.update(devices)
.set({
config: {
host: "10.0.0.5",
relays: [
{ relay: 1, direction: "entry", presenceInput: I2, presenceKind: "radar" },
{ relay: R3, direction: "radarAlert", triggerInput: I2, blinkOnMs: 500, blinkOffMs: 500 },
{ relay: R4, direction: "radarAlert", triggerInput: I3, blinkOnMs: 500, blinkOffMs: 500 },
],
},
})
.where(eq(devices.id, CONTROLLER))
.run();
const calls: Array<{ ch: number; on: boolean }> = [];
const aux = fakeAux(calls);
const ctl = new ButtonLightController(db, silentLogger(), () => aux);
ctl.start();
await flush();
expect(ctl.stateOf(CONTROLLER, R3)).toBe("off");
expect(ctl.stateOf(CONTROLLER, R4)).toBe("off");
// I2 active → only R3 blinks; R4 stays off (different trigger).
deviceEvents.emitInput({ driverId: "dingtian", deviceId: CONTROLLER, input: I2, edge: "on", at: new Date().toISOString(), source: "poll" });
await flush();
expect(ctl.stateOf(CONTROLLER, R3)).toBe("blink");
expect(ctl.stateOf(CONTROLLER, R4)).toBe("off");
// I3 active → R4 blinks too, independently.
deviceEvents.emitInput({ driverId: "dingtian", deviceId: CONTROLLER, input: I3, edge: "on", at: new Date().toISOString(), source: "poll" });
await flush();
expect(ctl.stateOf(CONTROLLER, R3)).toBe("blink");
expect(ctl.stateOf(CONTROLLER, R4)).toBe("blink");
// Camera confirms a car → BOTH lock solid (lane-busy is site-wide).
lane(true);
await flush();
expect(ctl.stateOf(CONTROLLER, R3)).toBe("solid");
expect(ctl.stateOf(CONTROLLER, R4)).toBe("solid");
// I2 clears → R3 off, R4 still solid (its trigger still active).
deviceEvents.emitInput({ driverId: "dingtian", deviceId: CONTROLLER, input: I2, edge: "off", at: new Date().toISOString(), source: "poll" });
await flush();
expect(ctl.stateOf(CONTROLLER, R3)).toBe("off");
expect(ctl.stateOf(CONTROLLER, R4)).toBe("solid");
ctl.stop();
});
it("an EXIT alert lamp locks on the EXIT camera, not entry", async () => {
const R4 = 4;
const I5 = 5; // exit radar
db.update(devices)
.set({
config: {
host: "10.0.0.5",
relays: [
{ relay: 1, direction: "entry" },
{ relay: 2, direction: "exit" },
// Exit alert lamp: triggers on the exit radar, locks on the EXIT camera.
{ relay: R4, direction: "radarAlert", triggerInput: I5, lockLane: "exit", blinkOnMs: 500, blinkOffMs: 500 },
],
},
})
.where(eq(devices.id, CONTROLLER))
.run();
const aux = fakeAux([]);
const ctl = new ButtonLightController(db, silentLogger(), () => aux);
ctl.start();
await flush();
// Exit radar active → blink.
deviceEvents.emitInput({ driverId: "dingtian", deviceId: CONTROLLER, input: I5, edge: "on", at: new Date().toISOString(), source: "poll" });
await flush();
expect(ctl.stateOf(CONTROLLER, R4)).toBe("blink");
// ENTRY camera busy must NOT lock this exit lamp — it still blinks.
deviceEvents.emitLaneStatus({ entry: true, exit: false });
await flush();
expect(ctl.stateOf(CONTROLLER, R4)).toBe("blink");
// EXIT camera busy → SOLID.
deviceEvents.emitLaneStatus({ entry: true, exit: true });
await flush();
expect(ctl.stateOf(CONTROLLER, R4)).toBe("solid");
ctl.stop();
});
});
+99 -67
View File
@@ -2,28 +2,33 @@ import { eq, devices, type Db, type DeviceRow } from "@parking/db";
import type { FastifyBaseLogger } from "fastify";
import { hasAuxOutput, registry, type AuxOutputDevice } from "@parking/devices";
import { deviceEvents, type DeviceInputEvent, type LaneStatusEvent } from "./device-events.js";
import { buttonLightOf, relayForPresence, type ButtonLightSpec } from "./device-resolve.js";
import { alertRelaysOf, relayForPresence, type RelaySpec } from "./device-resolve.js";
// The entry button's 12 V light, driven by the RADAR input vs. the camera "car in
// zone" signal (the existing advisory lane-status). A disagreement indicator:
// radar present + lane busy (camera confirms a car) → SOLID on
// radar present + lane free (radar sees something, no car) → BLINK (~1 Hz)
// Alert (radarAlert) relays — non-barrier indicator lamps, e.g. the entry button's 12 V
// light. Each lamp is a `relays[]` row with event `radarAlert`, driven by ITS trigger
// input vs. the camera "car in zone" signal (the advisory lane-status). A disagreement
// indicator:
// trigger active + lane busy (camera confirms a car) → SOLID on
// trigger active + lane free (radar sees something, no car) → BLINK (~1 Hz)
// otherwise → OFF
// The lamp is a NON-barrier aux output (setAux latch), so holding/blinking it is fine
// — barrier-not-a-door applies only to barriers, which still only pulseOpen. The lamp
// FAILS OFF: any error / shutdown leaves it off, so a dead lamp is "no hint", never a
// misleading solid "go". See wiki/concepts/button-light-indicator.md.
// misleading solid "go". A controller may have several alert relays (each its own row +
// trigger input), keyed independently. See wiki/concepts/button-light-indicator.md.
type LightState = "off" | "solid" | "blink";
const DEFAULT_BLINK_MS = 500;
/** Per-controller live state for the lamp rule. */
/** Per-lamp live state for the alert rule (one per radarAlert relay). */
interface LampState {
/** Lamp config (relay #, blink ms). Mutable: #reconcile updates it in place when the
* admin changes the button-light config without a restart. */
spec: ButtonLightSpec;
/** Is the radar (presence input on an entry relay) currently active? */
/** The controller this lamp lives on (its deviceId) — for resolving the aux adapter. */
readonly controllerId: string;
/** Alert relay row (relay #, triggerInput, blink ms). Mutable: #reconcile updates it in
* place when the admin changes the alert config without a restart. */
spec: RelaySpec;
/** Is the lamp's trigger input (the radar) currently active? */
present: boolean;
/** The high-level state we're rendering (to avoid restarting a running blink). */
rendered: LightState | null;
@@ -50,10 +55,13 @@ export class ButtonLightController {
readonly #db: Db;
readonly #logger: FastifyBaseLogger;
readonly #resolveAux: AuxResolver;
/** Per-controller state, keyed by controller deviceId. */
/** Per-lamp state, keyed by `${controllerId}:${relay}` (a controller may have several). */
readonly #lamps = new Map<string, LampState>();
/** Latest lane status (entry busy = a camera-confirmed car in the entry zone). */
/** Latest lane status — a camera-confirmed car in the entry / exit zone. A lamp locks
* SOLID off its OWN lane's camera (`spec.lockLane`), so an exit radar's lamp tracks the
* exit camera, not the entry one. */
#entryBusy = false;
#exitBusy = false;
/** Controllers we've already warned lack the aux-output capability (warn once). */
readonly #warned = new Set<string>();
#unsubInput: (() => void) | null = null;
@@ -69,7 +77,7 @@ export class ButtonLightController {
start(): void {
this.#reconcile();
// All lamps start OFF (known-safe baseline) regardless of prior device state.
for (const [controllerId, lamp] of this.#lamps) this.#apply(controllerId, lamp);
for (const lamp of this.#lamps.values()) this.#apply(lamp);
this.#unsubInput = deviceEvents.onInput((e) => this.#onInput(e));
this.#unsubLane = deviceEvents.onLaneStatus((s) => this.#onLane(s));
@@ -86,34 +94,36 @@ export class ButtonLightController {
const seen = new Set<string>();
for (const row of rows) {
if (!row.enabled) continue;
const spec = buttonLightOf(row);
if (!spec) continue;
seen.add(row.id);
const existing = this.#lamps.get(row.id);
if (existing) {
existing.spec = spec; // pick up a changed relay # / blink cadence
} else {
this.#lamps.set(row.id, {
spec,
present: false,
rendered: null,
blink: null,
blinkOn: false,
desiredOn: false,
confirmedOn: null,
sending: false,
});
for (const spec of alertRelaysOf(row)) {
const key = lampKey(row.id, spec.relay);
seen.add(key);
const existing = this.#lamps.get(key);
if (existing) {
existing.spec = spec; // pick up a changed trigger input / blink cadence
} else {
this.#lamps.set(key, {
controllerId: row.id,
spec,
present: false,
rendered: null,
blink: null,
blinkOn: false,
desiredOn: false,
confirmedOn: null,
sending: false,
});
}
}
}
// Drop lamps whose controller no longer declares one (or was disabled/removed).
for (const [id, lamp] of this.#lamps) {
if (seen.has(id)) continue;
for (const [key, lamp] of this.#lamps) {
if (seen.has(key)) continue;
if (lamp.blink) {
clearInterval(lamp.blink);
lamp.blink = null;
}
this.#finalOff(id, lamp); // best-effort fail-OFF before forgetting it
this.#lamps.delete(id);
this.#finalOff(lamp); // best-effort fail-OFF before forgetting it
this.#lamps.delete(key);
}
}
@@ -123,28 +133,36 @@ export class ButtonLightController {
#onInput(e: DeviceInputEvent): void {
// Reconcile first so a lamp added/changed since boot (no restart) is picked up.
this.#reconcile();
const lamp = this.#lamps.get(e.deviceId);
if (!lamp) return; // no lamp on this controller
const presence = relayForPresence(this.#db, e.deviceId, e.input);
if (!presence) return; // not the presence/radar terminal
const present = e.edge === "on";
if (present === lamp.present) return;
lamp.present = present;
this.#apply(e.deviceId, lamp);
for (const lamp of this.#lamps.values()) {
if (lamp.controllerId !== e.deviceId) continue;
// A lamp's trigger is its own `triggerInput`; if unset, fall back to the controller's
// entry-relay presence terminal (resolved the SAME way the entry flow does) so the
// lamp and the one-car-one-ticket gate always agree on "a car is here".
const trigger =
lamp.spec.triggerInput ?? relayForPresence(this.#db, e.deviceId, e.input)?.presenceInput;
if (trigger !== e.input) continue; // not this lamp's trigger terminal
if (present === lamp.present) continue;
lamp.present = present;
this.#apply(lamp);
}
}
/** Lane status changed: entry busy = a camera-confirmed car in the entry zone. */
/** Lane status changed: a camera-confirmed car in the entry and/or exit zone. */
#onLane(s: LaneStatusEvent): void {
if (s.entry === this.#entryBusy) return;
if (s.entry === this.#entryBusy && s.exit === this.#exitBusy) return;
this.#entryBusy = s.entry;
// Re-render every lamp (the camera signal is site-wide entry status).
for (const [controllerId, lamp] of this.#lamps) this.#apply(controllerId, lamp);
this.#exitBusy = s.exit;
// Re-render every lamp (each picks its own lane's camera in #apply).
for (const lamp of this.#lamps.values()) this.#apply(lamp);
}
/** Compute + render the target state for one lamp. Drives are fire-and-forget (the
* timer/state machine is synchronous; the UDP write resolves on its own). */
#apply(controllerId: string, lamp: LampState): void {
const target: LightState = !lamp.present ? "off" : this.#entryBusy ? "solid" : "blink";
#apply(lamp: LampState): void {
// SOLID only once THIS lamp's lane camera confirms a car (default entry).
const laneBusy = lamp.spec.lockLane === "exit" ? this.#exitBusy : this.#entryBusy;
const target: LightState = !lamp.present ? "off" : laneBusy ? "solid" : "blink";
if (target === lamp.rendered) return; // already rendering this state
// Tear down any running blink before switching states.
@@ -156,10 +174,10 @@ export class ButtonLightController {
if (target === "off") {
lamp.desiredOn = false;
this.#pump(controllerId, lamp);
this.#pump(lamp);
} else if (target === "solid") {
lamp.desiredOn = true;
this.#pump(controllerId, lamp);
this.#pump(lamp);
} else {
// BLINK: a wall-clock timer flips ONLY the desired flag; #pump does the actual
// (serialized) UDP send. A symmetric cadence uses one interval; an asymmetric one
@@ -172,7 +190,7 @@ export class ButtonLightController {
const tick = () => {
lamp.blinkOn = !lamp.blinkOn;
lamp.desiredOn = lamp.blinkOn;
this.#pump(controllerId, lamp);
this.#pump(lamp);
if (onMs !== offMs && lamp.blink) {
clearInterval(lamp.blink);
lamp.blink = setInterval(tick, lamp.blinkOn ? onMs : offMs);
@@ -181,7 +199,7 @@ export class ButtonLightController {
};
lamp.blink = setInterval(tick, onMs);
lamp.blink.unref?.();
this.#pump(controllerId, lamp);
this.#pump(lamp);
}
}
@@ -190,10 +208,10 @@ export class ButtonLightController {
* the relay stuck on a stale packet. Here a single in-flight send is guaranteed
* (`sending` guard); when it resolves, if the desired state moved on we send again —
* so the LAST desired state is always the one finally asserted on the device. */
#pump(controllerId: string, lamp: LampState): void {
#pump(lamp: LampState): void {
if (lamp.sending) return; // a send is already in flight; it'll re-check on completion
if (lamp.confirmedOn === lamp.desiredOn) return; // already there — no redundant UDP
const aux = this.#resolveAux(controllerId);
const aux = this.#resolveAux(lamp.controllerId);
if (!aux) return;
const target = lamp.desiredOn;
lamp.sending = true;
@@ -204,13 +222,13 @@ export class ButtonLightController {
})
.catch((err: unknown) => {
// Leave confirmedOn unchanged so the next pump retries this state. Never escalates.
this.#logger.error(`button-light setAux failed (${controllerId} R${lamp.spec.relay}): ${(err as Error).message}`);
this.#logger.error(`button-light setAux failed (${lamp.controllerId} R${lamp.spec.relay}): ${(err as Error).message}`);
})
.finally(() => {
lamp.sending = false;
// Desired state may have changed (or the send failed) while we were busy —
// re-pump to converge. This is what makes the final state authoritative.
if (lamp.confirmedOn !== lamp.desiredOn) this.#pump(controllerId, lamp);
if (lamp.confirmedOn !== lamp.desiredOn) this.#pump(lamp);
});
}
@@ -242,34 +260,48 @@ export class ButtonLightController {
this.#unsubLane?.();
this.#unsubInput = null;
this.#unsubLane = null;
for (const [controllerId, lamp] of this.#lamps) {
for (const lamp of this.#lamps.values()) {
if (lamp.blink) {
clearInterval(lamp.blink);
lamp.blink = null;
}
// Best-effort fail-OFF on shutdown.
this.#finalOff(controllerId, lamp);
this.#finalOff(lamp);
}
}
/** Drive a lamp OFF as a one-shot (used when dropping/stopping a lamp): set desired
* OFF and pump. The serialized worker still applies, so this can't collide with an
* in-flight send — it converges to OFF. */
#finalOff(controllerId: string, lamp: LampState): void {
#finalOff(lamp: LampState): void {
lamp.desiredOn = false;
this.#pump(controllerId, lamp);
this.#pump(lamp);
}
/** Test seam: current high-level state being rendered for a controller. */
stateOf(controllerId: string): LightState | null {
return this.#lamps.get(controllerId)?.rendered ?? null;
/** Test seam: current high-level state being rendered for a lamp (controller + relay).
* `relay` defaults to the controller's only/first alert relay for single-lamp tests. */
stateOf(controllerId: string, relay?: number): LightState | null {
return this.#lamp(controllerId, relay)?.rendered ?? null;
}
/** Test seam: the state last CONFIRMED on the device for a controller (after a
* successful send). null = unknown / nothing sent yet. */
confirmedOf(controllerId: string): boolean | null {
return this.#lamps.get(controllerId)?.confirmedOn ?? null;
/** Test seam: the state last CONFIRMED on the device for a lamp (after a successful
* send). null = unknown / nothing sent yet. `relay` defaults to the only alert relay. */
confirmedOf(controllerId: string, relay?: number): boolean | null {
return this.#lamp(controllerId, relay)?.confirmedOn ?? null;
}
/** Resolve a lamp by controller + relay. When `relay` is omitted, returns the
* controller's single lamp (the common single-alert case); ambiguous if several. */
#lamp(controllerId: string, relay?: number): LampState | undefined {
if (relay != null) return this.#lamps.get(lampKey(controllerId, relay));
for (const lamp of this.#lamps.values()) if (lamp.controllerId === controllerId) return lamp;
return undefined;
}
}
/** Composite key for the lamp map (a controller may carry several alert relays). */
function lampKey(controllerId: string, relay: number): string {
return `${controllerId}:${relay}`;
}
/** Build a controller row's live aux device (exported for reuse/tests). */
+6 -1
View File
@@ -39,7 +39,12 @@ function roleKindOf(db: Db, row: DeviceRow): DeviceStatusEvent["roleKind"] {
return d;
}
case "access": {
const dirs = new Set(relaysOf(row).map((r) => r.direction));
// Only barrier relays carry a role direction; alert (radarAlert) relays don't.
const dirs = new Set(
relaysOf(row)
.map((r) => r.direction)
.filter((d): d is "entry" | "exit" | "both" => d !== "radarAlert"),
);
if (dirs.size === 0) return null;
if (dirs.size > 1) return "mixed";
const only = [...dirs][0]; // entry | exit | both
+91
View File
@@ -0,0 +1,91 @@
import { beforeEach, describe, expect, it } from "vitest";
import { devices, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import { inputsOf, relayForButton, relayForPresence } from "./device-resolve.js";
// device-resolve: the input resolution layer. Inputs live in config.inputs[] (the first-class
// model); a pre-inputs[] controller is back-compat-synthesized from the legacy per-relay
// button/presenceInput fields. relayForButton/relayForPresence must resolve IDENTICALLY from
// either shape, so an exit radar = just another presence row.
let db: Db;
const CTL = "ctl-1";
function seed(config: Record<string, unknown>): void {
({ db } = createTestDb());
db.insert(devices).values({ id: CTL, category: "access", driverId: "dingtian", config, enabled: true }).run();
}
describe("inputsOf back-compat synth", () => {
it("synthesizes inputs[] from legacy relay button/presence fields", () => {
seed({
relays: [
{ relay: 1, direction: "entry", button: 1, presenceInput: 2, presenceKind: "radar", presenceActiveLow: true },
{ relay: 2, direction: "exit" },
],
});
const row = db.select().from(devices).get()!;
const inputs = inputsOf(row);
expect(inputs).toEqual([
{ input: 1, role: "button", relay: 1, cooldownSec: undefined },
{ input: 2, role: "presence", relay: 1, kind: "radar", activeLow: true },
]);
});
it("prefers an explicit inputs[] over the legacy fields", () => {
seed({
relays: [{ relay: 1, direction: "entry", button: 9 /* legacy ignored */ }],
inputs: [{ input: 1, role: "button", relay: 1 }],
});
const row = db.select().from(devices).get()!;
expect(inputsOf(row)).toEqual([{ input: 1, role: "button", relay: 1 }]);
});
});
describe("relayForButton / relayForPresence", () => {
it("resolves a button + presence from inputs[]", () => {
seed({
relays: [{ relay: 1, direction: "entry" }],
inputs: [
{ input: 1, role: "button", relay: 1 },
{ input: 2, role: "presence", relay: 1, kind: "radar" },
],
});
const byBtn = relayForButton(db, CTL, 1);
expect(byBtn).toMatchObject({ relay: 1, direction: "entry", presenceInput: 2, presenceKind: "radar" });
const byPres = relayForPresence(db, CTL, 2);
expect(byPres).toMatchObject({ relay: 1, direction: "entry", presenceInput: 2 });
});
it("resolves IDENTICALLY from the legacy shape (no inputs[])", () => {
seed({ relays: [{ relay: 1, direction: "entry", button: 1, presenceInput: 2, presenceKind: "loop" }] });
expect(relayForButton(db, CTL, 1)).toMatchObject({ relay: 1, presenceInput: 2, presenceKind: "loop" });
expect(relayForPresence(db, CTL, 2)).toMatchObject({ relay: 1, presenceInput: 2 });
});
it("resolves an EXIT presence row to the exit relay (the exit radar)", () => {
seed({
relays: [
{ relay: 1, direction: "entry" },
{ relay: 2, direction: "exit" },
],
inputs: [
{ input: 2, role: "presence", relay: 1, kind: "radar" }, // entry radar
{ input: 5, role: "presence", relay: 2, kind: "radar" }, // exit radar
],
});
// NOTE: relayForPresence only gates entry/both relays (transient entry). The exit radar
// resolves to null HERE (the exit barrier has no entry gate) — but it's still a valid
// inputs[] row the lamp can trigger on. The entry radar resolves to relay 1.
expect(relayForPresence(db, CTL, 2)).toMatchObject({ relay: 1 });
expect(relayForPresence(db, CTL, 5)).toBeNull(); // exit relay isn't a transient-entry gate
});
it("a button on an exit-only relay is not a transient-entry trigger", () => {
seed({
relays: [{ relay: 2, direction: "exit" }],
inputs: [{ input: 1, role: "button", relay: 2 }],
});
expect(relayForButton(db, CTL, 1)).toBeNull();
});
});
+129 -62
View File
@@ -10,55 +10,74 @@ export type Direction = "entry" | "exit" | "both";
/** A concrete flow a credential/button drives (never "both"). */
export type FlowDirection = "entry" | "exit";
/** One relay on an access controller: which barrier it opens, in which direction,
* and (optionally) the input terminals its entry button + presence loop are wired to. */
/** The EVENT a relay reacts to. The barrier events (entry/exit/both) `pulseOpen`; the
* `radarAlert` event drives a non-barrier alert lamp (blink while the trigger input is
* active, locked SOLID by the camera). A relay is "when EVENT X happens, do its action" —
* the action is implied by the event. See wiki/concepts/button-light-indicator.md. */
export type RelayEvent = Direction | "radarAlert";
/** What a controller input terminal MEANS. `button` = a transient-entry button; `presence`
* = a one-car-one-ticket sensor (induction loop or radar); `alertTrigger` = the edge that
* starts a `radarAlert` lamp blinking. See wiki/concepts/entry-double-press.md. */
export type InputRole = "button" | "presence" | "alertTrigger";
/** One INPUT terminal the host reads, as a first-class citizen (the twin of RelaySpec).
* An exit radar is just another `presence` row serving the exit relay. */
export interface InputSpec {
/** 1-based input terminal the host reads. */
readonly input: number;
readonly role: InputRole;
/** The barrier relay this input serves. Required for `button`/`presence` (the gate is
* keyed per relay); optional for `alertTrigger` (a standalone lamp trigger). */
readonly relay?: number;
/** `presence` only — induction LOOP or RADAR. Label only (gate is identical). Default loop. */
readonly kind?: "loop" | "radar";
/** This terminal is ACTIVE-LOW (idles HIGH) — e.g. a radar wired opposite the button.
* Maps to the driver's per-input `inputActiveLow`. See wiki/entities/hikvision-radar.md. */
readonly activeLow?: boolean;
/** `button` only — presence-less fallback: suppress repeat presses for N seconds after a
* ticket. A timer (mitigation, not a guarantee); used when no `presence` row serves this relay. */
readonly cooldownSec?: number;
}
/** One relay on an access controller: the event it reacts to. Input wiring (button,
* presence) lives in `config.inputs[]`; the LEGACY per-relay fields below are still read
* (back-compat) but no longer written by the UI. */
export interface RelaySpec {
/** 1-based relay channel on the board (the driver's pulseOpen(doorId)). */
readonly relay: number;
readonly direction: Direction;
/** 1-based input terminal of the entry button that fires this relay (transient
* entry). Absent = no button at this barrier (subscriber/reader-driven only). */
/** The event this relay reacts to. entry/exit/both → pulse a barrier; `radarAlert` →
* drive an alert lamp (blink + camera-lock) via `setAux`, NEVER pulseOpen. */
readonly direction: RelayEvent;
// ── LEGACY input fields (read-only back-compat; superseded by config.inputs[]) ──
// Pre-inputs[] configs wired the entry button + presence sensor here. `inputsOf()`
// synthesizes InputSpec rows from these when a controller has no `inputs[]` yet.
readonly button?: number;
/**
* Anti-double-press for the transient entry button (one car must yield ONE ticket).
* Two modes, chosen by what barrier feedback exists at this lane:
* - PRESENCE (preferred, when a vehicle loop is wired): `presenceInput` = the
* 1-based input terminal of an induction loop / barrier presence signal on THIS
* controller. A press prints only while a car is present, and no second ticket
* issues until the loop CLEARS (car drove in) and a new car re-occupies it. This
* makes one-car-one-ticket physical.
* - COOLDOWN (fallback, no feedback): `entryCooldownSec` suppresses repeat presses
* on this relay for N seconds after a ticket prints. A pure timer — mitigation,
* not a guarantee. Used when `presenceInput` is unset (or as a secondary guard).
* Both absent = no guard (legacy behaviour). See wiki/concepts/entry-double-press.md.
*/
readonly presenceInput?: number;
/** What kind of sensor is on `presenceInput` — an induction LOOP or a RADAR. Label
* only (the gate behaviour is identical); drives UI copy + telemetry. Default loop. */
readonly presenceKind?: "loop" | "radar";
/** The presence terminal's ACTIVE level is LOW (idles HIGH). Maps to the driver's
* per-input `inputActiveLow` override so a radar wired opposite the button reads
* right. See wiki/entities/hikvision-radar.md. */
readonly presenceActiveLow?: boolean;
readonly entryCooldownSec?: number;
}
/** A non-barrier indicator lamp wired to a spare relay (e.g. the entry button's
* 12 V light). Driven by the server LightController off the radar + lane status —
* NOT a barrier. See wiki/concepts/button-light-indicator.md. */
export interface ButtonLightSpec {
/** 1-based spare relay channel the lamp is wired to. */
readonly relay: number;
// ── radarAlert-only (direction === "radarAlert") ──
// A non-barrier indicator lamp wired to this (spare) relay — e.g. the entry button's
// 12 V light. Driven by the server ButtonLightController off its trigger input vs. the
// camera lane status: blink while the trigger is active + lane free, SOLID once the
// camera confirms a car, OFF otherwise. NOT a barrier (uses setAux, never pulseOpen).
/** 1-based input terminal whose active edge starts the blink (the radar). */
readonly triggerInput?: number;
/** Which lane's camera locks this lamp SOLID — the entry or the exit camera. Default
* "entry". An exit radar's lamp must lock on the EXIT camera. */
readonly lockLane?: FlowDirection;
/** Blink cadence (ms on / ms off) for the radar-only state. Default 500/500. */
readonly blinkOnMs?: number;
readonly blinkOffMs?: number;
}
/** Access controller config (the `relays[]` map + connection fields). */
/** Access controller config (the `relays[]` + `inputs[]` maps + connection fields). */
interface AccessConfig {
readonly relays?: RelaySpec[];
/** Optional button-lamp output on a spare relay. */
readonly buttonLight?: ButtonLightSpec;
readonly inputs?: InputSpec[];
readonly [k: string]: unknown;
}
@@ -105,9 +124,49 @@ export function relaysOf(row: DeviceRow): RelaySpec[] {
}
/**
* Resolve a button press to the relay it fires: the access controller with this
* deviceId, and the relay whose `button` terminal matches the pressed input. Only
* an ENTRY (or both) relay is a transient-entry trigger. Returns null otherwise.
* The INPUT terminals declared on an access controller — the back-compat keystone. Returns
* `config.inputs[]` when present; otherwise SYNTHESIZES InputSpec rows from the LEGACY
* per-relay fields (`relays[].button` → a `button` row; `relays[].presenceInput` → a
* `presence` row) so a pre-inputs[] controller resolves identically. Everything that reads
* inputs goes through here, so the legacy fold lives in exactly one place.
*/
export function inputsOf(row: DeviceRow): InputSpec[] {
const cfg = row.config as AccessConfig;
if (Array.isArray(cfg.inputs) && cfg.inputs.length > 0) return cfg.inputs;
const synth: InputSpec[] = [];
for (const r of relaysOf(row)) {
if (typeof r.button === "number") {
synth.push({ input: r.button, role: "button", relay: r.relay, cooldownSec: r.entryCooldownSec });
}
if (typeof r.presenceInput === "number") {
synth.push({
input: r.presenceInput,
role: "presence",
relay: r.relay,
kind: r.presenceKind ?? "loop",
activeLow: r.presenceActiveLow,
});
}
}
return synth;
}
/** The barrier RelaySpec a `button`/`presence` input row serves (its `relay`), or null —
* only entry/both relays gate transient entry. Narrows `direction` to a barrier Direction. */
function barrierForInput(row: DeviceRow, spec: InputSpec): (RelaySpec & { direction: Direction }) | null {
if (typeof spec.relay !== "number") return null;
const relay = relaysOf(row).find((r) => r.relay === spec.relay);
if (!relay) return null;
if (relay.direction !== "entry" && relay.direction !== "both") return null;
return { ...relay, direction: relay.direction };
}
/**
* Resolve a button press to the relay it fires: the access controller with this deviceId,
* and the relay served by the `button` input on this terminal (via inputsOf). Only an
* ENTRY (or both) relay is a transient-entry trigger. Carries the one-car-one-ticket
* config (presence input + cooldown) for that relay so the entry flow can enforce it.
* Returns null otherwise.
*/
export function relayForButton(db: Db, controllerId: string, terminal: number): ResolvedRelay | null {
const row = db
@@ -116,24 +175,28 @@ export function relayForButton(db: Db, controllerId: string, terminal: number):
.where(and(eq(devices.id, controllerId), eq(devices.category, "access")))
.get();
if (!row || !row.enabled) return null;
const spec = relaysOf(row).find((r) => r.button === terminal);
if (!spec) return null;
if (spec.direction !== "entry" && spec.direction !== "both") return null;
const inputs = inputsOf(row);
const btn = inputs.find((i) => i.role === "button" && i.input === terminal);
if (!btn) return null;
const relay = barrierForInput(row, btn);
if (!relay) return null;
// The presence sensor (if any) serving the SAME relay supplies the gate.
const presence = inputs.find((i) => i.role === "presence" && i.relay === relay.relay);
return {
controller: row,
relay: spec.relay,
direction: spec.direction,
presenceInput: spec.presenceInput,
presenceKind: spec.presenceKind ?? "loop",
entryCooldownSec: spec.entryCooldownSec,
relay: relay.relay,
direction: relay.direction,
presenceInput: presence?.input,
presenceKind: presence?.kind ?? "loop",
entryCooldownSec: btn.cooldownSec,
};
}
/**
* Resolve a PRESENCE-LOOP input edge to the entry relay it gates: the controller with
* this deviceId, and the relay whose `presenceInput` terminal matches the fired input.
* Lets the entry flow track "a car is physically at this entry barrier" so it issues
* exactly one ticket per car. Only entry/both relays gate transient entry. Null otherwise.
* Resolve a PRESENCE input edge to the entry relay it gates: the controller with this
* deviceId, and the relay served by the `presence` input on this terminal. Lets the entry
* flow track "a car is physically at this entry barrier" so it issues exactly one ticket
* per car. Only entry/both relays gate transient entry. Null otherwise.
*/
export function relayForPresence(db: Db, controllerId: string, terminal: number): ResolvedRelay | null {
const row = db
@@ -142,23 +205,23 @@ export function relayForPresence(db: Db, controllerId: string, terminal: number)
.where(and(eq(devices.id, controllerId), eq(devices.category, "access")))
.get();
if (!row || !row.enabled) return null;
const spec = relaysOf(row).find((r) => r.presenceInput === terminal);
if (!spec) return null;
if (spec.direction !== "entry" && spec.direction !== "both") return null;
const presence = inputsOf(row).find((i) => i.role === "presence" && i.input === terminal);
if (!presence) return null;
const relay = barrierForInput(row, presence);
if (!relay) return null;
return {
controller: row,
relay: spec.relay,
direction: spec.direction,
presenceInput: spec.presenceInput,
presenceKind: spec.presenceKind ?? "loop",
relay: relay.relay,
direction: relay.direction,
presenceInput: presence.input,
presenceKind: presence.kind ?? "loop",
};
}
/** The button-lamp output declared on an access controller, or null. */
export function buttonLightOf(row: DeviceRow): ButtonLightSpec | null {
const cfg = row.config as AccessConfig;
const bl = cfg.buttonLight;
return bl && typeof bl.relay === "number" ? bl : null;
/** The alert (radarAlert) relay rows declared on an access controller — the lamps the
* ButtonLightController drives. Each is a `relays[]` row whose event is `radarAlert`. */
export function alertRelaysOf(row: DeviceRow): RelaySpec[] {
return relaysOf(row).filter((r) => r.direction === "radarAlert" && typeof r.relay === "number");
}
/**
@@ -180,7 +243,10 @@ export function relayForDevice(db: Db, deviceRow: DeviceRow): ResolvedRelay | nu
.get();
if (controller && controller.enabled) {
const spec = relaysOf(controller).find((r) => r.relay === cfg.relay);
if (spec) return { controller, relay: spec.relay, direction: spec.direction };
// Only a barrier relay opens; an alert (radarAlert) relay is never a barrier.
if (spec && spec.direction !== "radarAlert") {
return { controller, relay: spec.relay, direction: spec.direction };
}
}
return null;
}
@@ -200,7 +266,8 @@ export function relayForDevice(db: Db, deviceRow: DeviceRow): ResolvedRelay | nu
export function firstRelayByDirection(db: Db, direction: FlowDirection): ResolvedRelay | null {
for (const controller of accessRows(db)) {
const spec = relaysOf(controller).find(
(r) => r.direction === direction || r.direction === "both",
(r): r is RelaySpec & { direction: Direction } =>
r.direction === direction || r.direction === "both",
);
if (spec) return { controller, relay: spec.relay, direction: spec.direction };
}