feat(sim): start and stop the decoder simulator from Settings (1.65.0)
This commit is contained in:
1 parent
0ce7280cbf
commit
e4874fd558
14 files changed
+309
-110
No files matched your search
+23
-105
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user