From e4874fd558842c7a493b367606b19568a96fd75b Mon Sep 17 00:00:00 2001 From: larssand Date: Thu, 5 Nov 2026 18:48:37 +0100 Subject: [PATCH] feat(sim): start and stop the decoder simulator from Settings (1.65.0) --- CHANGELOG.md | 6 ++ README.md | 2 +- README.sv.md | 2 +- package-lock.json | 4 +- package.json | 2 +- scripts/fake-decoder.mjs | 128 +++++++---------------------------- server.js | 27 ++++++++ server/decoder_sim.js | 136 ++++++++++++++++++++++++++++++++++++++ src/app.js | 16 +++++ src/decoder_sim_view.js | 58 ++++++++++++++++ src/runtime_services.js | 2 + src/settings.js | 3 + tests/decoder_sim.test.js | 32 +++++++++ tests/run.js | 1 + 14 files changed, 309 insertions(+), 110 deletions(-) create mode 100644 server/decoder_sim.js create mode 100644 src/decoder_sim_view.js create mode 100644 tests/decoder_sim.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a93cbe8..1b1a262 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.65.0 - 2026-11-05 + +### Added + +- Settings → "Decoder simulator (for testing)": start and stop the fake decoder from the UI. The server runs it on port 9099 and the app connects to it at once; the real decoder address is kept and put back on Stop. Lap time and spread between cars can be set; the panel shows the transponders driven and the passings sent. `npm run sim` uses the same simulator (server/decoder_sim.js). + ## 1.64.0 - 2026-11-05 ### Added diff --git a/README.md b/README.md index 2250956..f121a5d 100644 --- a/README.md +++ b/README.md @@ -431,7 +431,7 @@ AMMC sends PASSING messages like this ([AMMC docs](https://www.ammconverter.eu/d ### Testing without a decoder -`npm run sim` starts a decoder simulator on `ws://127.0.0.1:9000` (the app's default decoder address) that replaces AMMC and the decoder, so it also runs on a laptop without either. It sends passings with realistic lap times (about 18 s, a crash now and then) for the transponders in the active heat (sponsor heats: the cars), and follows when you switch heat. Start the heat on Race Day and the laps come in. Options: `npm run sim -- --lap 15 --spread 2 --tp 1001,1002 --port 9000`. If port 9000 is busy (AMMC running), stop AMMC or use `--port 9100` and set the decoder address to `ws://127.0.0.1:9100`. +Settings → "Decoder simulator" starts it from the UI (port 9099, the app connects by itself). From a terminal, `npm run sim` starts a decoder simulator on `ws://127.0.0.1:9000` (the app's default decoder address) that replaces AMMC and the decoder, so it also runs on a laptop without either. It sends passings with realistic lap times (about 18 s, a crash now and then) for the transponders in the active heat (sponsor heats: the cars), and follows when you switch heat. Start the heat on Race Day and the laps come in. Options: `npm run sim -- --lap 15 --spread 2 --tp 1001,1002 --port 9000`. If port 9000 is busy (AMMC running), stop AMMC or use `--port 9100` and set the decoder address to `ws://127.0.0.1:9100`. ## Development and tests diff --git a/README.sv.md b/README.sv.md index 72294b9..82cd4f2 100644 --- a/README.sv.md +++ b/README.sv.md @@ -444,7 +444,7 @@ AMMC skickar PASSING-meddelanden så här ([AMMC-dokumentation](https://www.ammc ### Testa utan decoder -`npm run sim` startar en decoder-simulator på `ws://127.0.0.1:9000` (appens standardadress för decodern) som ersätter AMMC och decodern, så den fungerar även på en laptop utan dem. Den skickar passeringar med realistiska varvtider (runt 18 s, en krasch ibland) för transpondrarna i det aktiva heatet (sponsorheat: bilarna) och följer med när du byter heat. Starta heatet på Race Day så kommer varven. Val: `npm run sim -- --lap 15 --spread 2 --tp 1001,1002 --port 9000`. Är port 9000 upptagen (AMMC körs) stoppar du AMMC eller kör `--port 9100` och sätter decoderadressen till `ws://127.0.0.1:9100`. +Inställningar → "Decoder-simulator" startar den från UI (port 9099, appen ansluter själv). Från en terminal startar `npm run sim` en decoder-simulator på `ws://127.0.0.1:9000` (appens standardadress för decodern) som ersätter AMMC och decodern, så den fungerar även på en laptop utan dem. Den skickar passeringar med realistiska varvtider (runt 18 s, en krasch ibland) för transpondrarna i det aktiva heatet (sponsorheat: bilarna) och följer med när du byter heat. Starta heatet på Race Day så kommer varven. Val: `npm run sim -- --lap 15 --spread 2 --tp 1001,1002 --port 9000`. Är port 9000 upptagen (AMMC körs) stoppar du AMMC eller kör `--port 9100` och sätter decoderadressen till `ws://127.0.0.1:9100`. ## Utveckling och tester diff --git a/package-lock.json b/package-lock.json index eb30add..890d52c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.64.0", + "version": "1.65.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.64.0", + "version": "1.65.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index 3d2d80d..ebaa957 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.64.0", + "version": "1.65.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/scripts/fake-decoder.mjs b/scripts/fake-decoder.mjs index 086098b..b62ca4b 100755 --- a/scripts/fake-decoder.mjs +++ b/scripts/fake-decoder.mjs @@ -1,114 +1,32 @@ #!/usr/bin/env node -// Decoder simulator for testing without a MyLaps decoder: pretends to be AMMC on -// ws://127.0.0.1:9000 (the app's default decoder address) and sends PASSING messages with -// realistic lap times. Usage: npm run sim [-- --lap 18 --spread 1.5 --tp 1001,1002 --port 9000] -// Without --tp it asks the running app which transponders are in the active heat (sponsor -// heats: the cars), and follows when you switch heat. -import { createHash } from "node:crypto"; -import { createServer } from "node:http"; +// Decoder simulator from the command line (the same one as Settings → Decoder simulator): +// npm run sim [-- --lap 18 --spread 1.5 --port 9000 --app http://127.0.0.1:8081] +// Port 9000 is the app's default decoder address, so the app connects without any change. +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const { createDecoderSimulator } = require("../server/decoder_sim.js"); const args = Object.fromEntries(process.argv.slice(2).reduce((pairs, arg, index, all) => { if (arg.startsWith("--")) pairs.push([arg.slice(2), all[index + 1] && !all[index + 1].startsWith("--") ? all[index + 1] : "true"]); return pairs; }, [])); -const PORT = Number(args.port || 9000); -const APP = String(args.app || `http://127.0.0.1:${process.env.PORT || 8081}`); -const BASE_LAP_MS = Number(args.lap || 18) * 1000; -const SPREAD_MS = Number(args.spread || 1.5) * 1000; -const FIXED_TPS = args.tp ? String(args.tp).split(",").map((value) => value.trim()).filter(Boolean) : null; +const app = String(args.app || `http://127.0.0.1:${process.env.PORT || 8081}`); +const fixed = args.tp ? String(args.tp).split(",").map((value) => value.trim()).filter(Boolean) : null; -const sockets = new Set(); -const cars = new Map(); // transponder -> { paceMs, nextAt } +const sim = createDecoderSimulator({ + // --tp: these transponders; otherwise the active heat of the running app. + getState: async () => { + if (fixed) return { drivers: fixed.map((transponder, index) => ({ id: `tp${index}`, transponder })), sessions: [] }; + const response = await fetch(`${app}/api/state`); + return (await response.json())?.state || null; + }, + log: (line) => console.log(line), +}); -function frame(text) { - const payload = Buffer.from(text); - const header = payload.length < 126 - ? Buffer.from([0x81, payload.length]) - : Buffer.from([0x81, 126, payload.length >> 8, payload.length & 0xff]); - return Buffer.concat([header, payload]); -} - -function send(message) { - const data = frame(JSON.stringify(message)); - for (const socket of sockets) socket.write(data); -} - -// A lap: the car's own pace, +-0.6 s, and now and then a crash or a marshal (+3-8 s). -function nextLapMs(car) { - const noise = (Math.random() + Math.random() - 1) * 600; - const crash = Math.random() < 0.05 ? 3000 + Math.random() * 5000 : 0; - return Math.max(4000, Math.round(car.paceMs + noise + crash)); -} - -function setTransponders(list) { - const wanted = new Set(list); - for (const tp of [...cars.keys()]) if (!wanted.has(tp)) cars.delete(tp); - list.forEach((tp, index) => { - if (cars.has(tp)) return; - const paceMs = BASE_LAP_MS + (Math.random() - 0.3) * SPREAD_MS; - cars.set(tp, { paceMs, nextAt: Date.now() + 1500 + index * 700 + Math.random() * 2000 }); +sim.start({ port: Number(args.port || 9000), host: "127.0.0.1", lapSec: Number(args.lap || 18), spreadSec: Number(args.spread ?? 1.5) }) + .then(() => console.log("Ctrl+C stops.")) + .catch((error) => { + console.error(`${error.message} - probably AMMC or the simulator started from Settings. Try: npm run sim -- --port 9100 and set the decoder address to ws://127.0.0.1:9100.`); + process.exit(1); }); -} - -async function transpondersFromApp() { - try { - const response = await fetch(`${APP}/api/state`); - const state = (await response.json())?.state; - if (!state) return null; - const sessions = state.sessions || []; - const session = sessions.find((item) => item.id === state.activeSessionId) - || sessions.find((item) => ["running", "paused"].includes(item.status)); - const driverTp = (id) => (state.drivers || []).find((driver) => driver.id === id)?.transponder; - const carTp = (id) => (state.cars || []).find((car) => car.id === id)?.transponder; - let list = []; - if (session?.carAssignments && Object.keys(session.carAssignments).length) list = Object.values(session.carAssignments).map(carTp); - else if (session?.assignments?.length) list = session.assignments.map((item) => carTp(item.carId)); - else if (session?.driverIds?.length) list = session.driverIds.map(driverTp); - if (!list.filter(Boolean).length) list = (state.drivers || []).filter((driver) => !driver.guestEventId).map((driver) => driver.transponder).slice(0, 8); - return { list: [...new Set(list.map((value) => String(value || "").trim()).filter(Boolean))], session }; - } catch { - return null; - } -} - -let lastLabel = ""; -async function refreshTransponders() { - if (FIXED_TPS) { setTransponders(FIXED_TPS); return; } - const found = await transpondersFromApp(); - const list = found?.list?.length ? found.list : ["9001", "9002", "9003", "9004"]; - const label = `${found?.session ? `heat "${found.session.name}" (${found.session.status})` : found ? "no active heat" : `app not reachable at ${APP}`}: ${list.join(", ")}`; - if (label !== lastLabel) { console.log(`Transponders - ${label}`); lastLabel = label; } - setTransponders(list); -} - -const server = createServer((_req, res) => { res.writeHead(200); res.end("Live_RC decoder simulator\n"); }); -server.on("upgrade", (req, socket) => { - const key = req.headers["sec-websocket-key"]; - if (!key) { socket.destroy(); return; } - const accept = createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); - socket.write(["HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", `Sec-WebSocket-Accept: ${accept}`, "", ""].join("\r\n")); - sockets.add(socket); - console.log(`App connected (${sockets.size} open)`); - socket.on("data", () => {}); // client frames (if any) are not needed - socket.on("error", () => sockets.delete(socket)); - socket.on("close", () => { sockets.delete(socket); console.log(`App disconnected (${sockets.size} open)`); }); -}); -server.on("error", (error) => { - if (error.code === "EADDRINUSE") console.error(`Port ${PORT} is busy - probably AMMC. Stop it (Settings → decoder → Stop AMMC) or run: npm run sim -- --port 9100 and set the decoder address to ws://127.0.0.1:9100.`); - else console.error(error.message); - process.exit(1); -}); - -server.listen(PORT, "127.0.0.1", async () => { - console.log(`Decoder simulator on ws://127.0.0.1:${PORT} - laps around ${BASE_LAP_MS / 1000} s. Ctrl+C stops.`); - await refreshTransponders(); - setInterval(refreshTransponders, 5000); - setInterval(() => { - const now = Date.now(); - for (const [tp, car] of cars) { - if (now < car.nextAt) continue; - send({ msg: "PASSING", transponder: tp, rtc_time: new Date(now).toISOString(), strength: 90 + Math.round(Math.random() * 30), loop_id: "1" }); - car.nextAt = now + nextLapMs(car); - } - }, 50); -}); diff --git a/server.js b/server.js index ecaf9ef..0303df4 100644 --- a/server.js +++ b/server.js @@ -11,6 +11,7 @@ const { createBackupService } = require("./server/backup_service"); const { createAuth, COOKIE_NAME: AUTH_COOKIE_NAME, TOKEN_MAX_AGE_MS } = require("./server/auth"); const { createTts, resolvePiperBinary } = require("./server/tts"); const { installAll: installPiperAll, VOICES: PIPER_VOICES } = require("./server/tts_install"); +const { createDecoderSimulator } = require("./server/decoder_sim"); const PORT = Number(process.env.PORT || 8081); const HOST = process.env.HOST || "0.0.0.0"; @@ -368,6 +369,32 @@ app.post("/api/ammc/stop", async (_req, res) => { } }); +// Decoder simulator (Settings → Decoder simulator): passings without a decoder, for testing. +const decoderSim = createDecoderSimulator({ + getState: () => { + const row = db.prepare("SELECT state_json FROM app_state WHERE id = 1").get(); + return row ? JSON.parse(row.state_json) : null; + }, + log: (line) => console.log(line), +}); + +app.get("/api/sim/status", (_req, res) => { + res.json(decoderSim.status()); +}); + +app.post("/api/sim/start", async (req, res) => { + try { + const status = await decoderSim.start({ port: req.body?.port || 9099, host: HOST, lapSec: req.body?.lapSec, spreadSec: req.body?.spreadSec }); + res.json({ ok: true, status }); + } catch (error) { + res.status(400).json({ error: error instanceof Error ? error.message : String(error), status: decoderSim.status() }); + } +}); + +app.post("/api/sim/stop", async (_req, res) => { + res.json({ ok: true, status: await decoderSim.stop() }); +}); + // Two admin browsers can be open at once, and each pushes its own full in-memory copy of // state on every save - whichever save lands last silently overwrites everything else, // including any other browser's edits since its own last page load. That risk is most diff --git a/server/decoder_sim.js b/server/decoder_sim.js new file mode 100644 index 0000000..6fecd69 --- /dev/null +++ b/server/decoder_sim.js @@ -0,0 +1,136 @@ +// Decoder simulator: a stand-in for AMMC + a MyLaps decoder, for testing without either. It is a +// WebSocket server that sends AMMC-style PASSING messages with realistic lap times for the +// transponders in the active heat (sponsor heats: the cars), following when the heat changes. +// Started from Settings (server.js /api/sim/*) or with npm run sim (scripts/fake-decoder.mjs). +const { createHash } = require("crypto"); +const { createServer } = require("http"); + +function frame(text) { + const payload = Buffer.from(text); + const header = payload.length < 126 + ? Buffer.from([0x81, payload.length]) + : Buffer.from([0x81, 126, payload.length >> 8, payload.length & 0xff]); + return Buffer.concat([header, payload]); +} + +// The transponders to drive: the active (or running) heat's cars or drivers, else up to 8 +// club drivers, else 9001-9004. +function pickTransponders(state) { + if (!state) return { list: ["9001", "9002", "9003", "9004"], session: null }; + const sessions = state.sessions || []; + const session = sessions.find((item) => item.id === state.activeSessionId) + || sessions.find((item) => ["running", "paused"].includes(item.status)) || null; + const driverTp = (id) => (state.drivers || []).find((driver) => driver.id === id)?.transponder; + const carTp = (id) => (state.cars || []).find((car) => car.id === id)?.transponder; + let list = []; + if (session?.carAssignments && Object.keys(session.carAssignments).length) list = Object.values(session.carAssignments).map(carTp); + else if (session?.assignments?.length) list = session.assignments.map((item) => carTp(item.carId)); + else if (session?.driverIds?.length) list = session.driverIds.map(driverTp); + if (!list.filter(Boolean).length) list = (state.drivers || []).filter((driver) => !driver.guestEventId).map((driver) => driver.transponder).slice(0, 8); + list = [...new Set(list.map((value) => String(value || "").trim()).filter(Boolean))]; + return { list: list.length ? list : ["9001", "9002", "9003", "9004"], session }; +} + +function createDecoderSimulator({ getState, log = () => {} }) { + let server = null; + let timers = []; + let options = { port: 9099, host: "127.0.0.1", lapMs: 18000, spreadMs: 1500 }; + let lastLabel = ""; + let passings = 0; + const sockets = new Set(); + const cars = new Map(); + + const send = (message) => { + const data = frame(JSON.stringify(message)); + for (const socket of sockets) socket.write(data); + }; + // The car's own pace +-0.6 s, and now and then a crash or a marshal (+3-8 s). + const nextLapMs = (car) => Math.max(4000, Math.round(car.paceMs + (Math.random() + Math.random() - 1) * 600 + (Math.random() < 0.05 ? 3000 + Math.random() * 5000 : 0))); + + async function refresh() { + const picked = pickTransponders(await Promise.resolve(getState()).catch(() => null)); + const wanted = new Set(picked.list); + for (const tp of [...cars.keys()]) if (!wanted.has(tp)) cars.delete(tp); + picked.list.forEach((tp, index) => { + if (!cars.has(tp)) cars.set(tp, { paceMs: options.lapMs + (Math.random() - 0.3) * options.spreadMs, nextAt: Date.now() + 1500 + index * 700 + Math.random() * 2000 }); + }); + const label = `${picked.session ? `heat "${picked.session.name}" (${picked.session.status})` : "no active heat"}: ${picked.list.join(", ")}`; + if (label !== lastLabel) { log(`Simulator transponders - ${label}`); lastLabel = label; } + } + + function start(next = {}) { + if (server) return Promise.resolve(status()); + options = { + port: Math.round(Number(next.port) || options.port), + host: String(next.host || options.host), + lapMs: Math.max(3000, Math.min(120000, Math.round(Number(next.lapSec) * 1000) || options.lapMs)), + spreadMs: Math.max(0, Math.min(20000, Math.round(Number(next.spreadSec ?? options.spreadMs / 1000) * 1000))), + }; + cars.clear(); + passings = 0; + lastLabel = ""; + return new Promise((resolve, reject) => { + const http = createServer((_req, res) => { res.writeHead(200); res.end("Live_RC decoder simulator\n"); }); + http.on("upgrade", (req, socket) => { + const key = req.headers["sec-websocket-key"]; + if (!key) { socket.destroy(); return; } + const accept = createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); + socket.write(["HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", `Sec-WebSocket-Accept: ${accept}`, "", ""].join("\r\n")); + sockets.add(socket); + socket.on("data", () => {}); + socket.on("error", () => sockets.delete(socket)); + socket.on("close", () => sockets.delete(socket)); + }); + http.once("error", (error) => { + reject(error.code === "EADDRINUSE" ? new Error(`Port ${options.port} is busy`) : error); + }); + http.listen(options.port, options.host, async () => { + server = http; + log(`Decoder simulator on ws://${options.host}:${options.port}, laps around ${options.lapMs / 1000} s`); + await refresh(); + timers = [ + setInterval(() => { void refresh(); }, 5000), + setInterval(() => { + const now = Date.now(); + for (const [tp, car] of cars) { + if (now < car.nextAt) continue; + send({ msg: "PASSING", transponder: tp, rtc_time: new Date(now).toISOString(), strength: 90 + Math.round(Math.random() * 30), loop_id: "1" }); + passings += 1; + car.nextAt = now + nextLapMs(car); + } + }, 50), + ]; + resolve(status()); + }); + }); + } + + function stop() { + timers.forEach(clearInterval); + timers = []; + for (const socket of sockets) socket.destroy(); + sockets.clear(); + cars.clear(); + if (!server) return Promise.resolve(status()); + const closing = server; + server = null; + log("Decoder simulator stopped"); + return new Promise((resolve) => closing.close(() => resolve(status()))); + } + + function status() { + return { + running: Boolean(server), + port: options.port, + lapSec: options.lapMs / 1000, + spreadSec: options.spreadMs / 1000, + connections: sockets.size, + transponders: [...cars.keys()], + passings, + }; + } + + return { start, stop, status }; +} + +module.exports = { createDecoderSimulator, pickTransponders }; diff --git a/src/app.js b/src/app.js index 8ced3c9..9ed51f1 100644 --- a/src/app.js +++ b/src/app.js @@ -2279,6 +2279,14 @@ const TRANSLATIONS = { "events.step_count": "{done}/{total} körda", "events.assignments": "Tilldelningar", "events.na": "ej relevant", + "sim.title": "Decoder-simulator (för test)", + "sim.hint": "Kör bilar runt banan utan decoder och AMMC, för att labba och prova UI. Den kör transpondrarna i det aktiva heatet (sponsorheat: bilarna) och följer med när du byter heat. Starta heatet på Race Day så kommer varven. Den riktiga decoderadressen sparas och sätts tillbaka när du stoppar.", + "sim.lap_sec": "Varvtid (s)", + "sim.spread_sec": "Spridning mellan bilar (s)", + "sim.start": "Starta simulator", + "sim.stop": "Stoppa simulator", + "sim.running": "Igång på {url}. Transpondrar: {cars}. Passeringar: {passings}.", + "sim.stopped": "Avstängd.", "sponsor.title": "Sponsor event - enkel setup", "sponsor.step_drivers": "1. Förare (ett namn per rad)", "sponsor.guests_placeholder": "Anna\nBosse\nCissi", @@ -4303,6 +4311,14 @@ const TRANSLATIONS = { "events.step_count": "{done}/{total} run", "events.assignments": "Assignments", "events.na": "n/a", + "sim.title": "Decoder simulator (for testing)", + "sim.hint": "Drives cars around the track without a decoder or AMMC, to try things out. It drives the transponders of the active heat (sponsor heats: the cars) and follows when you switch heat. Start the heat on Race Day and the laps come in. The real decoder address is kept and put back when you stop it.", + "sim.lap_sec": "Lap time (s)", + "sim.spread_sec": "Spread between cars (s)", + "sim.start": "Start simulator", + "sim.stop": "Stop simulator", + "sim.running": "Running on {url}. Transponders: {cars}. Passings: {passings}.", + "sim.stopped": "Off.", "sponsor.title": "Sponsor event - quick setup", "sponsor.step_drivers": "1. Drivers (one name per line)", "sponsor.guests_placeholder": "Anna\nBob\nCarla", diff --git a/src/decoder_sim_view.js b/src/decoder_sim_view.js new file mode 100644 index 0000000..984d6ac --- /dev/null +++ b/src/decoder_sim_view.js @@ -0,0 +1,58 @@ +// Settings → Decoder simulator: start/stop the server's fake decoder (server/decoder_sim.js) +// and point the app at it. The real decoder address is kept and put back on Stop. +const SIM_PORT = 9099; + +export function mountDecoderSimSettings(root, { state, t, escapeHtml, getBackendUrl, saveState, connectDecoder, renderView }) { + if (!root) return; + const call = async (path, body) => { + const response = await fetch(`${getBackendUrl()}/api/sim/${path}`, body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}); + const payload = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(payload.error || `HTTP ${response.status}`); + return payload.status || payload; + }; + const simUrl = () => `ws://${window.location.hostname || "127.0.0.1"}:${SIM_PORT}`; + + const render = (status, error = "") => { + const running = Boolean(status?.running); + root.innerHTML = ` +
+

${t("sim.title")}

+
+

${t("sim.hint")}

+
+ + +
+
+ +
+

${running + ? escapeHtml(t("sim.running", { url: simUrl(), cars: (status.transponders || []).join(", ") || "-", passings: status.passings || 0 })) + : escapeHtml(t("sim.stopped"))}

+ ${error ? `` : ""} +
+
`; + root.querySelector("#simToggle")?.addEventListener("click", async () => { + try { + if (running) { + await call("stop", {}); + // Back to the real decoder address. + state.settings.wsUrl = state.settings.simPreviousWsUrl || state.settings.wsUrl; + delete state.settings.simPreviousWsUrl; + } else { + await call("start", { lapSec: Number(root.querySelector("#simLapSec").value), spreadSec: Number(root.querySelector("#simSpreadSec").value) }); + if (state.settings.wsUrl !== simUrl()) state.settings.simPreviousWsUrl = state.settings.wsUrl; + state.settings.wsUrl = simUrl(); + } + saveState(); + connectDecoder(); + renderView(); + } catch (failure) { + render(status, failure instanceof Error ? failure.message : String(failure)); + } + }); + }; + + render(null); + call("status").then((status) => render(status)).catch(() => render(null)); +} diff --git a/src/runtime_services.js b/src/runtime_services.js index 34c9998..08647e0 100644 --- a/src/runtime_services.js +++ b/src/runtime_services.js @@ -132,6 +132,8 @@ export function applyPersistedStateHelper(persisted, deps) { state.raceDays = normalizeRaceDays(persisted.raceDays); state.settings = { wsUrl: persisted.settings?.wsUrl || state.settings.wsUrl || "ws://127.0.0.1:9000", + // The real decoder address while the decoder simulator is on (decoder_sim_view.js). + ...(persisted.settings?.simPreviousWsUrl ? { simPreviousWsUrl: String(persisted.settings.simPreviousWsUrl) } : {}), splitDecoderEnabled: persisted.settings?.splitDecoderEnabled === true, splitWsUrl: String(persisted.settings?.splitWsUrl || state.settings.splitWsUrl || "ws://127.0.0.1:9001"), pitDecoderEnabled: persisted.settings?.pitDecoderEnabled === true, diff --git a/src/settings.js b/src/settings.js index 8c13167..8aa6d8c 100644 --- a/src/settings.js +++ b/src/settings.js @@ -2,6 +2,7 @@ import { normalizePublicBaseUrl } from "./public_url.js"; import { decoderDiagnosticsMarkup, mountDecoderDiagnostics } from "./decoder_diagnostics_view.js"; import { mountAuthSettings } from "./auth_view.js"; import { mountTtsSettings } from "./tts_settings_view.js"; +import { mountDecoderSimSettings } from "./decoder_sim_view.js"; import { formatSpokenLapTime, formatShortLapCall } from "./race_audio.js"; let activeSettingsTab = "connection"; @@ -453,6 +454,7 @@ export function renderSettings(deps) { )} +
@@ -619,6 +621,7 @@ Erik Eriksson;654321;4WD;Associated;; } mountAuthSettings(document.getElementById("authSettings"), { t, escapeHtml }); mountTtsSettings(document.getElementById("ttsSettings"), { state, t, escapeHtml, saveState, speakText }); + mountDecoderSimSettings(document.getElementById("decoderSimSettings"), { state, t, escapeHtml, getBackendUrl, saveState, connectDecoder, renderView }); const applyRaceAudioFormValues = (form) => { const events = {}; diff --git a/tests/decoder_sim.test.js b/tests/decoder_sim.test.js new file mode 100644 index 0000000..9a43877 --- /dev/null +++ b/tests/decoder_sim.test.js @@ -0,0 +1,32 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const { createDecoderSimulator, pickTransponders } = require("../server/decoder_sim.js"); + +test("simulator drives the active heat: the cars in a sponsor heat, else the drivers", () => { + const state = { + activeSessionId: "s1", + sessions: [{ id: "s1", name: "Q1 H1", status: "ready", carAssignments: { a: "c1", b: "c2" } }], + cars: [{ id: "c1", transponder: "111" }, { id: "c2", transponder: "222" }], + drivers: [{ id: "x", transponder: "999" }], + }; + assert.deepEqual(pickTransponders(state).list, ["111", "222"]); + assert.deepEqual(pickTransponders({ ...state, activeSessionId: null, sessions: [] }).list, ["999"]); + assert.deepEqual(pickTransponders(null).list, ["9001", "9002", "9003", "9004"]); +}); + +test("simulator sends AMMC-style passings over a WebSocket and stops cleanly", async () => { + const sim = createDecoderSimulator({ getState: () => ({ drivers: [{ id: "a", transponder: "4242" }], sessions: [] }) }); + const status = await sim.start({ port: 39117, host: "127.0.0.1", lapSec: 3, spreadSec: 0 }); + assert.equal(status.running, true); + const message = await new Promise((resolve, reject) => { + const ws = new WebSocket("ws://127.0.0.1:39117"); + const timer = setTimeout(() => reject(new Error("no passing")), 8000); + ws.onmessage = (event) => { clearTimeout(timer); ws.close(); resolve(JSON.parse(event.data)); }; + }); + assert.equal(message.msg, "PASSING"); + assert.equal(message.transponder, "4242"); + assert.equal((await sim.stop()).running, false); +}); diff --git a/tests/run.js b/tests/run.js index 6a3d463..efa55e8 100644 --- a/tests/run.js +++ b/tests/run.js @@ -1,4 +1,5 @@ import "./auth.test.js"; +import "./decoder_sim.test.js"; import "./sponsor_event.test.js"; import "./practice_hype.test.js"; import "./race_day_fixes.test.js";