Files
parking_solution/packages/devices/src/registry.ts
T
julian 1efa77bf56 devices: pool-of-spaces model — drop lane, per-relay direction
A parking lot is one pool of spaces with a flexible set of entry/exit
points — no "lane". Direction is a property of each RELAY inside an access
controller; readers/cameras bind to a controller relay and inherit it.

Schema:
- drop `lane` from ledger_events, device_events, sessions
- rename lane_devices -> devices (no lane/direction columns)
- access config.relays=[{relay,direction,button?}]; reader/camera
  config.controllerId+relay binding
- fresh 0000_baseline migration (history reset; dev data was throwaway)

Signed ledger:
- remove `lane` from canonicalize(); bump signer keyId sw-hmac-v1 -> v2
  (v1 events won't verify under v2 — intentional, gated per-event by keyId)

Server:
- new device-resolve.ts (replaces lane-map.ts): relayForButton,
  relayForDevice, firstRelayByDirection, devicesByDirection
- entry-flow: button terminal -> its relay; exit/permit: reader's bound
  relay; dispatcher resolves the bound relay + inherited direction
- camera snapshots fire by direction site-wide, async, never block open
- DeviceConfig widened to nested JSON for relays[]

Web:
- wizard: no lane selector; add controllers (relay map + entry-button
  terminal) first, then bind readers/cameras/printers to a controller relay

Wiki: new entry-exit-points.md (replaces lane-direction); reworked
entry-exit-readers, parking-session, first-run-setup, device-registry,
append-only-event-chain, device-events; removed stale lane/LaneMap mentions.
2026-06-16 20:29:38 +02:00

168 lines
5.9 KiB
TypeScript

// Driver registry — the catalog of selectable device drivers.
//
// This is what makes the system admin-configurable: each category (access /
// reader / camera / printer) has multiple drivers, and the first-run setup UI
// reads this catalog to let the admin pick one per lane and fill in its config.
// Adding support for a new device = registering one more driver here; no
// business-logic changes. See wiki/concepts/device-registry.md.
import type {
AccessControlDevice,
CameraDevice,
Device,
DeviceCategory,
PrinterDevice,
ReaderDevice,
} from "./interfaces.js";
/** A single configurable connection field shown in the setup wizard. */
export interface ConfigField {
readonly key: string;
readonly label: string;
readonly type: "string" | "number" | "boolean" | "host" | "port" | "secret" | "select";
readonly required: boolean;
readonly default?: string | number | boolean;
/** For type "select". */
readonly options?: readonly { value: string; label: string }[];
readonly help?: string;
}
/** A JSON-serializable config value. Mostly flat scalars (host, port, credentials),
* but some configs carry nested structure — e.g. an access controller's
* `relays: [{ relay, direction, button? }]` map. See entry-exit-points.md. */
export type ConfigValue =
| string
| number
| boolean
| null
| ConfigValue[]
| { [k: string]: ConfigValue };
/** Opaque per-instance config the admin fills in (host, port, credentials…). */
export type DeviceConfig = Record<string, ConfigValue>;
/**
* A driver: metadata describing a supported device model/family, the config
* fields the admin must supply, and a factory that builds a live adapter.
*/
export interface DeviceDriver<T extends Device = Device> {
readonly id: string; // stable, e.g. "dingtian", "hikvision"
readonly category: DeviceCategory;
readonly label: string; // human name for the picker, e.g. "Dingtian relay controller"
readonly description: string;
/** Transports/notes surfaced in the UI, e.g. ["tcp-ip"], ["wiegand"]. */
readonly transports: readonly string[];
readonly configFields: readonly ConfigField[];
/**
* True if the device calls BACK to our backend (HTTP push) and therefore needs
* a backend IP configured at assign time. Pull-only devices (cameras poll a
* snapshot, the relay is commanded) leave this false so the setup wizard hides
* the "Backend push IP" field. See wiki/concepts/device-input-flow.md.
*/
readonly pushesToBackend?: boolean;
/** Build a live adapter instance from validated config. */
create(config: DeviceConfig): T;
}
export type AccessDriver = DeviceDriver<AccessControlDevice>;
export type ReaderDriver = DeviceDriver<ReaderDevice>;
export type CameraDriver = DeviceDriver<CameraDevice>;
export type PrinterDriver = DeviceDriver<PrinterDevice>;
/** A device found on the LAN by a driver's discovery scan. */
export interface DiscoveredDevice {
/** Identifier to pre-fill (e.g. a serial number). */
readonly id: string;
readonly label: string;
/** Config values to auto-fill into the setup form (host, serial, …). */
readonly config: DeviceConfig;
/** Extra info to show the admin (firmware, MAC, netmask, …). */
readonly info?: Record<string, string>;
}
/**
* Optional capability: a driver that can find devices on the LAN (e.g. UDP
* broadcast discovery). No bundled driver implements this yet — the Dingtian
* board uses a fixed IP; cameras (ONVIF) or other UDP-discoverable devices may
* add it later. See wiki/concepts/device-discovery.md.
*/
export interface DiscoverableDriver {
discover(): Promise<DiscoveredDevice[]>;
}
/** Type guard: does this driver support discovery? */
export function isDiscoverable(
driver: DeviceDriver,
): driver is DeviceDriver & DiscoverableDriver {
return typeof (driver as Partial<DiscoverableDriver>).discover === "function";
}
class DeviceRegistry {
readonly #drivers = new Map<string, DeviceDriver>();
register(driver: DeviceDriver): void {
if (this.#drivers.has(driver.id)) {
throw new Error(`duplicate driver id: ${driver.id}`);
}
this.#drivers.set(driver.id, driver);
}
/** All drivers, optionally filtered by category (used by the setup catalog). */
list(category?: DeviceCategory): DeviceDriver[] {
const all = [...this.#drivers.values()];
return category ? all.filter((d) => d.category === category) : all;
}
get(id: string): DeviceDriver | undefined {
return this.#drivers.get(id);
}
/** Validate config against a driver's declared fields and build the adapter. */
create(id: string, config: DeviceConfig): Device {
const driver = this.#drivers.get(id);
if (!driver) throw new Error(`unknown driver: ${id}`);
for (const field of driver.configFields) {
if (field.required && config[field.key] === undefined) {
throw new Error(`driver ${id}: missing required config "${field.key}"`);
}
}
return driver.create(config);
}
/** Catalog payload for the setup UI — drivers grouped by category, no secrets. */
catalog() {
const byCategory: Record<DeviceCategory, CatalogEntry[]> = {
access: [],
reader: [],
camera: [],
printer: [],
};
for (const d of this.#drivers.values()) {
byCategory[d.category].push({
id: d.id,
label: d.label,
description: d.description,
transports: d.transports,
configFields: d.configFields,
});
}
return byCategory;
}
/** Driver ids that push to the backend (need a backend IP at assign time). */
pushCapable(): string[] {
return [...this.#drivers.values()].filter((d) => d.pushesToBackend).map((d) => d.id);
}
}
export interface CatalogEntry {
readonly id: string;
readonly label: string;
readonly description: string;
readonly transports: readonly string[];
readonly configFields: readonly ConfigField[];
}
/** Singleton registry. Drivers self-register on import (see ./drivers). */
export const registry = new DeviceRegistry();