a0e0fd9118
UHPPOTE controllers self-announce via UDP broadcast, but the frontend had no way to find them — the admin had to type the serial blind. Add a generic discovery capability and surface it in the setup wizard. packages/devices: - DiscoverableDriver capability + DiscoveredDevice type + isDiscoverable() guard on the registry (optional, so any driver can opt in). - uhppote driver implements discover() via uhppoted getDevices (UDP broadcast), mapping each controller's serial/IP/firmware into a DiscoveredDevice; extract shared buildCtx(). apps/server: - GET /api/setup/discover/:driverId (admin-only): runs discover() and health-checks each found device so reachability shows before assigning. - catalog now returns a `discoverable` driver-id list. apps/web: - SetupWizard "Scan for controllers" button for discoverable drivers; lists found devices with health badges; selecting one auto-fills serial + host. api client gains discoverDevices(). wiki: new device-discovery concept; cross-link from registry/setup/uhppote; note the broadcast-permission (EACCES) deployment caveat; index + log. Verified: catalog flags uhppote discoverable; discover runs and fails gracefully without hardware; non-discoverable driver -> 400; missing token -> 401.
121 lines
4.1 KiB
TypeScript
121 lines
4.1 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import type { FastifyInstance } from "fastify";
|
|
import { eq, laneDevices, setupState, type Db } from "@parking/db";
|
|
import {
|
|
isDiscoverable,
|
|
registerBuiltinDrivers,
|
|
registry,
|
|
setDeviceLogSink,
|
|
type DeviceCategory,
|
|
} from "@parking/devices";
|
|
import { requireRole } from "../auth.js";
|
|
|
|
// First-run setup API. The admin reads the driver catalog and assigns devices
|
|
// per lane. See wiki/concepts/first-run-setup.md.
|
|
|
|
interface AssignBody {
|
|
lane: number;
|
|
category: DeviceCategory;
|
|
driverId: string;
|
|
config: Record<string, string | number | boolean>;
|
|
}
|
|
|
|
export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|
registerBuiltinDrivers();
|
|
setDeviceLogSink((line) => app.log.info(line));
|
|
|
|
// Catalog of selectable drivers per category (no secrets — schema only).
|
|
// `discoverable` flags drivers that can scan the LAN (e.g. UHPPOTE).
|
|
app.get("/api/setup/catalog", async () => {
|
|
const catalog = registry.catalog();
|
|
const discoverable = registry.list().filter(isDiscoverable).map((d) => d.id);
|
|
return { ...catalog, discoverable };
|
|
});
|
|
|
|
// Scan the LAN for devices a driver can discover (UHPPOTE UDP broadcast, etc).
|
|
// Each found device is health-checked so the admin sees reachability before
|
|
// assigning. Admin-only. See wiki/concepts/device-discovery.md.
|
|
app.get<{ Params: { driverId: string } }>(
|
|
"/api/setup/discover/:driverId",
|
|
{ preHandler: requireRole("admin") },
|
|
async (req, reply) => {
|
|
const driver = registry.get(req.params.driverId);
|
|
if (!driver) return reply.code(404).send({ error: `unknown driver: ${req.params.driverId}` });
|
|
if (!isDiscoverable(driver)) {
|
|
return reply.code(400).send({ error: `driver ${driver.id} does not support discovery` });
|
|
}
|
|
try {
|
|
const found = await driver.discover();
|
|
const withHealth = await Promise.all(
|
|
found.map(async (d) => {
|
|
let health: { status: string; detail?: string };
|
|
try {
|
|
health = await driver.create(d.config).healthCheck();
|
|
} catch (err) {
|
|
health = { status: "offline", detail: (err as Error).message };
|
|
}
|
|
return { ...d, health };
|
|
}),
|
|
);
|
|
return { driverId: driver.id, devices: withHealth };
|
|
} catch (err) {
|
|
return reply.code(502).send({ error: `discovery failed: ${(err as Error).message}` });
|
|
}
|
|
},
|
|
);
|
|
|
|
// Current setup status + assignments.
|
|
app.get(
|
|
"/api/setup/state",
|
|
{ preHandler: requireRole("admin") },
|
|
async () => {
|
|
const state = await db.select().from(setupState).where(eq(setupState.id, 1)).get();
|
|
const assignments = await db.select().from(laneDevices).all();
|
|
return { completedAt: state?.completedAt ?? null, assignments };
|
|
},
|
|
);
|
|
|
|
// Assign a device to a lane. Validates the chosen driver + config against the
|
|
// registry before persisting; rejects unknown drivers / missing config.
|
|
app.post<{ Body: AssignBody }>(
|
|
"/api/setup/assign",
|
|
{ preHandler: requireRole("admin") },
|
|
async (req, reply) => {
|
|
const { lane, category, driverId, config } = req.body;
|
|
const driver = registry.get(driverId);
|
|
if (!driver || driver.category !== category) {
|
|
return reply.code(400).send({ error: `invalid driver for ${category}: ${driverId}` });
|
|
}
|
|
try {
|
|
registry.create(driverId, config); // validates required fields
|
|
} catch (err) {
|
|
return reply.code(400).send({ error: (err as Error).message });
|
|
}
|
|
const row = {
|
|
id: randomUUID(),
|
|
lane,
|
|
category,
|
|
driverId,
|
|
config,
|
|
enabled: true,
|
|
};
|
|
await db.insert(laneDevices).values(row);
|
|
return reply.code(201).send(row);
|
|
},
|
|
);
|
|
|
|
// Mark first-run setup complete.
|
|
app.post(
|
|
"/api/setup/complete",
|
|
{ preHandler: requireRole("admin") },
|
|
async () => {
|
|
const completedAt = new Date().toISOString();
|
|
await db
|
|
.insert(setupState)
|
|
.values({ id: 1, completedAt })
|
|
.onConflictDoUpdate({ target: setupState.id, set: { completedAt } });
|
|
return { completedAt };
|
|
},
|
|
);
|
|
}
|