diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs index 9c3e6b8..ad60226 100644 --- a/crates/opendiag-cli/src/bmw.rs +++ b/crates/opendiag-cli/src/bmw.rs @@ -248,7 +248,7 @@ fn serve_cmd(c: &Conn, listen_port: u16) -> Result<(), String> { let (v, _mock) = vehicle_of(s); let id = v.default_ecu(); let module = VehicleModule::new(Box::new(v), id).map_err(|e| e.to_string())?; - crate::serve_module(Box::new(module), connection, simulated, listen_port) + crate::serve_module(Box::new(module), connection, simulated, false, listen_port) } fn parse_hex_u16(s: &str) -> Result { diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index fad2e45..74d68cc 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -1061,6 +1061,12 @@ fn adaptation_set( /// How the connection was made, in words for the report; and whether it is simulated. fn describe_connection(t: &Target) -> (String, bool) { + if let Some(path) = &t.replay { + return ( + format!("Replay of recorded session {}", path.display()), + false, + ); + } if t.simulate { return ("Simulated: built-in virtual UDS ECU".into(), true); } @@ -1125,7 +1131,13 @@ fn serve_cmd(target: &Target, listen_port: u16) -> Result<(), String> { // VAG connections are one module; the vehicle view makes both brands serve the same way. let vehicle = SingleModule::new(module, connection.clone()); let module = VehicleModule::new(Box::new(vehicle), 0).map_err(|e| e.to_string())?; - serve_module(Box::new(module), connection, simulated, listen_port) + serve_module( + Box::new(module), + connection, + simulated, + target.replay.is_some(), + listen_port, + ) } /// Serve any connected module read-only on localhost until stopped. @@ -1133,6 +1145,7 @@ pub(crate) fn serve_module( module: Box, connection: String, simulated: bool, + replay: bool, listen_port: u16, ) -> Result<(), String> { let mut module = module; @@ -1150,6 +1163,7 @@ pub(crate) fn serve_module( version: env!("CARGO_PKG_VERSION").to_string(), connection, simulated, + replay, module: module_name, }; let mut app = opendiag_web::App::new(module, load_data(), info, token.clone(), port); @@ -1224,6 +1238,7 @@ fn report_cmd(target: &Target, out: Option<&Path>) -> Result<(), String> { tool_version: env!("CARGO_PKG_VERSION").to_string(), connection, simulated, + replay: target.replay.is_some(), module: Some(module), ident, faults, diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index 08f97ae..8f5ea13 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1660,3 +1660,99 @@ fn replay_cannot_be_combined_with_a_live_connection() { assert!(!ok); assert!(err.contains("cannot be used with"), "{err}"); } + +// ---- serve --replay: the dashboard fed from a recording ---- + +fn json_get(srv: &Server, path: &str) -> serde_json::Value { + let host = format!("127.0.0.1:{}", srv.port); + let (status, _, body) = http(srv.port, "GET", path, &host, Some(&srv.token)); + assert_eq!(status, 200, "{path}: {body}"); + serde_json::from_str(&body).expect("json") +} + +/// The first cell's A*256+B for each of the logged rounds, from the CSV `log` writes. +fn recorded_first_cells(csv: &str) -> Vec { + csv.lines() + .skip(1) + .filter_map(|l| { + let f: Vec<&str> = l.split(',').collect(); + (f[2] == "1").then(|| f[4].parse::().unwrap() * 256 + f[5].parse::().unwrap()) + }) + .collect() +} + +#[test] +fn serve_replay_labels_itself_and_steps_through_the_recorded_readings() { + let trace = trace_path("serve-live"); + let (ok, csv, err) = run( + &[ + "log", + "--groups", + "1", + "--samples", + "3", + "--interval-ms", + "10", + "--simulate-kw1281", + "--trace", + &trace, + ], + "", + ); + assert!(ok, "{err}"); + let recorded = recorded_first_cells(&csv); + assert_eq!(recorded.len(), 3); + assert!( + recorded[0] != recorded[1], + "the simulator's values must change" + ); + + let srv = start_server(&["--replay", &trace, "--slow-init"]); + let info = json_get(&srv, "/api/info"); + assert_eq!(info["replay"], true); + assert_eq!(info["simulated"], false); + assert!( + info["connection"].as_str().unwrap().starts_with("Replay"), + "{info}" + ); + + let mut seen = Vec::new(); + for _ in 0..3 { + let live = json_get(&srv, "/api/live?groups=1"); + let c = &live["groups"][0]["cells"][0]; + seen.push(c["a"].as_u64().unwrap() as u32 * 256 + c["b"].as_u64().unwrap() as u32); + } + let _ = std::fs::remove_file(&trace); + assert_eq!( + seen, recorded, + "replay must play the readings back in recorded order" + ); +} + +#[test] +fn serve_replay_stays_alive_while_idle_and_exposes_no_write() { + let trace = trace_path("serve-idle"); + let (ok, _, err) = run(&["dtc", "read", "--simulate-kw1281", "--trace", &trace], ""); + assert!(ok, "{err}"); + let srv = start_server(&["--replay", &trace, "--slow-init"]); + // Longer than the server's 2 s idle keep-alive interval. + std::thread::sleep(std::time::Duration::from_millis(2600)); + let dtcs = json_get(&srv, "/api/dtcs"); + assert!(!dtcs.as_array().unwrap().is_empty(), "{dtcs}"); + let host = format!("127.0.0.1:{}", srv.port); + let (status, _, _) = http(srv.port, "POST", "/api/dtcs", &host, Some(&srv.token)); + let _ = std::fs::remove_file(&trace); + assert_eq!(status, 405); +} + +#[test] +fn a_replayed_report_says_so() { + let trace = trace_path("report"); + let (ok, _, err) = run(&["report", "--simulate-kw1281", "--trace", &trace], ""); + assert!(ok, "{err}"); + let (ok, html, err) = run(&["report", "--replay", &trace, "--slow-init"], ""); + let _ = std::fs::remove_file(&trace); + assert!(ok, "{err}"); + assert!(html.contains("REPLAYED DATA"), "{html}"); + assert!(!html.contains("SIMULATED DATA"), "{html}"); +} diff --git a/crates/opendiag-services/src/report.rs b/crates/opendiag-services/src/report.rs index 73be47a..6d2c7a7 100644 --- a/crates/opendiag-services/src/report.rs +++ b/crates/opendiag-services/src/report.rs @@ -28,6 +28,8 @@ pub struct Report { pub connection: String, /// True when the data came from a built-in virtual module, not a vehicle. pub simulated: bool, + /// True when the data comes from a recorded session (`--replay`), not a vehicle right now. + pub replay: bool, /// Module description, e.g. `KW1281 module 0x01`. pub module: Option, pub ident: Ident, @@ -124,6 +126,12 @@ pub fn render_html(r: &Report) -> String { ); } + if r.replay { + h.push_str( + "

REPLAYED DATA: this report comes from a recorded session, not from a vehicle right now.

\n", + ); + } + h.push_str("

Summary

\n
\n"); h.push_str(&row("Connection", &r.connection)); if let Some(m) = &r.module { diff --git a/crates/opendiag-services/tests/report.rs b/crates/opendiag-services/tests/report.rs index ef09a85..bf2b3d0 100644 --- a/crates/opendiag-services/tests/report.rs +++ b/crates/opendiag-services/tests/report.rs @@ -6,6 +6,7 @@ fn base() -> Report { tool_version: "0.0.1".into(), connection: "K-line COM3 at 10400 baud, KW1281 (5-baud init), module 0x01".into(), simulated: false, + replay: false, module: Some("KW1281 module 0x01".into()), ident: Ident { part_number: Some("1J0 906 018 AB".into()), @@ -301,3 +302,13 @@ fn the_report_warns_about_privacy_and_verification() { assert!(h.contains("VIN") && h.contains("before sharing")); assert!(h.contains("not yet been verified against real vehicles")); } + +#[test] +fn a_replayed_report_is_labelled_before_the_summary() { + let mut r = base(); + r.replay = true; + let h = render_html(&r); + assert!(h.contains("REPLAYED DATA") && h.contains("recorded session")); + assert!(h.find("REPLAYED DATA").unwrap() < h.find("

Summary

").unwrap()); + assert!(!render_html(&base()).contains("REPLAYED DATA")); +} diff --git a/crates/opendiag-web/src/app.css b/crates/opendiag-web/src/app.css index e50c4cb..cb6ba6c 100644 --- a/crates/opendiag-web/src/app.css +++ b/crates/opendiag-web/src/app.css @@ -19,6 +19,14 @@ th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid var(--line button, input { font: inherit; padding: 3px 10px; } button { cursor: pointer; } h2 button { margin-left: 8px; font-size: 13px; } -svg { width: 100%; height: auto; margin-top: 8px; border: 1px solid var(--line); } -polyline { fill: none; stroke: var(--accent); stroke-width: 1.5; } +.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin: 8px 0 12px; } +select { font: inherit; padding: 3px 6px; } +button:disabled { cursor: not-allowed; } +#tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; } +.tile { border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; } +.tile .name { color: var(--muted); font-size: 13px; } +.tile .value { font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums; } +.tile .range { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; } +.tile svg { width: 100%; height: 44px; display: block; margin-top: 4px; } +.tile polyline { fill: none; stroke: var(--accent); stroke-width: 1.5; vector-effect: non-scaling-stroke; } @media (max-width: 480px) { dl { grid-template-columns: 1fr; } } diff --git a/crates/opendiag-web/src/app.js b/crates/opendiag-web/src/app.js index 29837c3..316c899 100644 --- a/crates/opendiag-web/src/app.js +++ b/crates/opendiag-web/src/app.js @@ -36,8 +36,10 @@ async function loadInfo() { $("version").textContent = "v" + i.version; fillDl($("info"), [["Connection", i.connection], ["Module", i.module]]); const b = $("banner"); - b.hidden = !i.simulated; - if (i.simulated) b.textContent = "SIMULATED: this is a built-in virtual module, not a car."; + b.hidden = !(i.simulated || i.replay); + if (i.replay) b.textContent = "REPLAY: this is a recorded session, not a car right now."; + else if (i.simulated) b.textContent = "SIMULATED: this is a built-in virtual module, not a car."; + $("replay-note").hidden = !i.replay; const id = await api("/api/ident"); const rows = []; if (id.part_number) rows.push(["Part number", id.part_number]); @@ -65,54 +67,90 @@ async function loadDtcs() { } } -// Live data +// Live data: one tile per measuring-block cell, each with its own scale. let timer = null; -const history = new Map(); // "group.cell" -> [values] +let busy = false; const MAX_POINTS = 120; +const tiles = new Map(); // "group.cell" -> { values, formula, node parts } +const samples = []; // every reading this session, for the CSV download +let startedAt = 0; -function drawChart() { - const svg = $("chart"); - svg.replaceChildren(); - const series = [...history.values()]; - let max = 1; - for (const s of series) for (const v of s) max = Math.max(max, v); - for (const s of series) { - const pts = s.map((v, i) => { - const x = (i / (MAX_POINTS - 1)) * 600; - const y = 155 - (v / max) * 150; - return x.toFixed(1) + "," + y.toFixed(1); - }); - const pl = document.createElementNS("http://www.w3.org/2000/svg", "polyline"); - pl.setAttribute("points", pts.join(" ")); - svg.append(pl); +const SVG_NS = "http://www.w3.org/2000/svg"; + +function makeTile(key, group, cell) { + const root = document.createElement("div"); + root.className = "tile"; + const name = el("div", "Group " + group + ", cell " + cell); + name.className = "name"; + const value = el("div", ""); + value.className = "value"; + const range = el("div", ""); + range.className = "range"; + const svg = document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("viewBox", "0 0 200 44"); + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("role", "img"); + svg.setAttribute("aria-label", "Recent values of group " + group + " cell " + cell); + const line = document.createElementNS(SVG_NS, "polyline"); + svg.append(line); + root.append(name, value, range, svg); + $("tiles").append(root); + const t = { values: [], name, value, range, line }; + tiles.set(key, t); + return t; +} + +function drawTile(t, formula) { + const vs = t.values; + const last = vs[vs.length - 1]; + let lo = Infinity; + let hi = -Infinity; + for (const v of vs) { + lo = Math.min(lo, v); + hi = Math.max(hi, v); } - svg.hidden = series.length === 0; + t.value.textContent = String(last); + t.range.textContent = + "formula 0x" + formula.toString(16).toUpperCase().padStart(2, "0") + + " \u00b7 min " + lo + " \u00b7 max " + hi; + const span = hi - lo || 1; // a flat series sits in the middle, not at the floor + const pts = vs.map((v, i) => { + const x = vs.length === 1 ? 0 : (i / (MAX_POINTS - 1)) * 200; + const y = hi === lo ? 22 : 40 - ((v - lo) / span) * 36; + return x.toFixed(1) + "," + y.toFixed(1); + }); + t.line.setAttribute("points", pts.join(" ")); +} + +function setStatus(msg) { + $("live-status").textContent = msg; } async function pollLive() { + if (busy) return; // never queue requests behind a slow module + busy = true; try { const live = await api("/api/live?groups=" + encodeURIComponent($("groups").value)); showError(""); - const body = $("live").tBodies[0]; - body.replaceChildren(); + const ms = Date.now() - startedAt; for (const g of live.groups) { g.cells.forEach((c, n) => { const raw = c.a * 256 + c.b; - const key = g.group + "." + n; - const h = history.get(key) || []; - h.push(raw); - if (h.length > MAX_POINTS) h.shift(); - history.set(key, h); - const tr = document.createElement("tr"); - tr.append(el("td", String(g.group)), el("td", String(n + 1)), el("td", "0x" + c.formula.toString(16).toUpperCase().padStart(2, "0")), el("td", String(c.a)), el("td", String(c.b)), el("td", String(raw))); - body.append(tr); + const key = g.group + "." + (n + 1); + const t = tiles.get(key) || makeTile(key, g.group, n + 1); + t.values.push(raw); + if (t.values.length > MAX_POINTS) t.values.shift(); + drawTile(t, c.formula); + samples.push([ms, g.group, n + 1, c.formula, c.a, c.b]); }); } - $("live").hidden = false; - drawChart(); + $("live-csv").disabled = samples.length === 0; + setStatus(samples.length + " reading(s)"); } catch (e) { showError(e.message); stopLive(); + } finally { + busy = false; } } @@ -122,13 +160,43 @@ function stopLive() { $("live-toggle").textContent = "Start"; } -$("live-toggle").addEventListener("click", () => { - if (timer !== null) return stopLive(); - history.clear(); - $("live-toggle").textContent = "Stop"; +function startLive() { + if (samples.length === 0) startedAt = Date.now(); + $("live-toggle").textContent = "Pause"; pollLive(); - timer = setInterval(pollLive, 1000); + timer = setInterval(pollLive, Number($("interval").value)); +} + +function clearLive() { + stopLive(); + tiles.clear(); + samples.length = 0; + $("tiles").replaceChildren(); + $("live-csv").disabled = true; + setStatus(""); +} + +function downloadCsv() { + const rows = ["time_ms,group,cell,formula,a,b"].concat(samples.map((s) => s.join(","))); + const blob = new Blob([rows.join("\n") + "\n"], { type: "text/csv" }); + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = "opendiag-live.csv"; + a.click(); + URL.revokeObjectURL(a.href); +} + +$("live-toggle").addEventListener("click", () => (timer !== null ? stopLive() : startLive())); +$("live-clear").addEventListener("click", clearLive); +$("live-csv").addEventListener("click", downloadCsv); +$("interval").addEventListener("change", () => { + if (timer !== null) { + stopLive(); + startLive(); + } }); +// Different groups are different series: start fresh so tiles are not mixed up. +$("groups").addEventListener("change", clearLive); $("refresh-dtcs").addEventListener("click", () => loadDtcs().catch((e) => showError(e.message))); loadInfo().then(loadDtcs).catch((e) => showError(e.message)); diff --git a/crates/opendiag-web/src/index.html b/crates/opendiag-web/src/index.html index 63715d9..fe3b7d6 100644 --- a/crates/opendiag-web/src/index.html +++ b/crates/opendiag-web/src/index.html @@ -30,16 +30,26 @@

Fault codes

-
+

Live data

-

Raw measuring-block cells (formula, A, B). Values are not converted to units; the chart plots A×256+B.

- - - - - - - +

Raw measuring-block cells (formula, A, B), shown as A×256+B. Values are not converted to units.

+ +
+ + + + + + +
+

Read-only. Clearing codes and changing adaptation are only possible from the command line, with a backup first.

diff --git a/crates/opendiag-web/src/lib.rs b/crates/opendiag-web/src/lib.rs index 5a7b7ef..bd30ed2 100644 --- a/crates/opendiag-web/src/lib.rs +++ b/crates/opendiag-web/src/lib.rs @@ -106,6 +106,8 @@ pub struct Info { pub connection: String, /// True for the built-in virtual modules: the page shows a banner. pub simulated: bool, + /// True when answers come from a recorded session: the page shows a banner. + pub replay: bool, pub module: String, } @@ -144,6 +146,11 @@ impl App { /// Call periodically while idle. If the session cannot be kept alive, later API /// requests are refused instead of talking into a dead session. pub fn tick(&mut self) { + // A recording has no session to keep alive, and a keep-alive sent into it would + // only disturb where the replay is up to. + if self.info.replay { + return; + } if self.alive && self.module.keep_alive().is_err() { self.alive = false; } diff --git a/crates/opendiag-web/tests/handler.rs b/crates/opendiag-web/tests/handler.rs index c12d0ce..f5eb07d 100644 --- a/crates/opendiag-web/tests/handler.rs +++ b/crates/opendiag-web/tests/handler.rs @@ -14,6 +14,7 @@ fn info(simulated: bool) -> Info { version: "test".into(), connection: "test connection".into(), simulated, + replay: false, module: "test module".into(), } } @@ -369,3 +370,24 @@ fn random_requests_are_never_served_unless_every_rule_holds() { // The test must actually exercise the success path. assert!(served > 50, "only {served} requests were served"); } + +#[test] +fn info_tells_the_page_whether_it_is_a_replay() { + let mut app = kw_app(); + let v: serde_json::Value = + serde_json::from_str(&api(&mut app, "/api/info").body_text()).unwrap(); + assert_eq!(v["replay"], false); + let mut replay = App::new( + Box::new(virtual_kw1281_module().expect("virtual module")), + None, + Info { + replay: true, + ..info(false) + }, + TOKEN.into(), + PORT, + ); + let v: serde_json::Value = + serde_json::from_str(&api(&mut replay, "/api/info").body_text()).unwrap(); + assert_eq!(v["replay"], true); +} diff --git a/docs/replay.md b/docs/replay.md index ca1d62e..520b4ff 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -17,6 +17,19 @@ Say which protocol the recording used, as you would for a live connection: `--sl `--fast-init` for KWP2000, neither for UDS. `--replay` cannot be combined with `--simulate*`, `--port`, `--can`, `--elm327` or `--trace`. +## Replaying the web dashboard + +Record exactly what the page asks for by tracing `serve`, then use the page for a while (identification, +fault codes, start live data) and stop with Ctrl-C: + +```bash +opendiag serve --port /dev/ttyUSB0 --slow-init --trace page.trace +opendiag serve --replay page.trace --slow-init # later, no cable +``` + +The page shows a **REPLAY** banner, and a report made under `--replay` is labelled *REPLAYED DATA*. Each live +reading in the recording is played back in order, and the recording loops when it runs out. + ## How it answers Each thing the tool does (send a frame, set a baud rate, start an init) is looked up in the recording @@ -31,8 +44,11 @@ recording, as long as each was recorded at least once. This is different from `T ...`, naming the request. Nothing is guessed or made up. To replay `dtc read`, record `dtc read`. - **Replies are the recorded bytes.** A value that changes on a live car (an RPM, a counter) repeats its recorded value, so a replay shows a snapshot and not a running vehicle. -- **Matching is by content.** On K-line, identical one-byte acknowledgements are ambiguous. The forward-first - search handles a session replayed in recorded order; out of order it can pick the wrong one. +- **Matching is by content.** On K-line (KW1281) the recording is a stream of single bytes, so identical + acknowledgements are ambiguous. Replaying in recorded order works. Asking for something that was *not* + recorded does **not** reliably give the clean `not in recording` error there: it can surface as a protocol + error (for example "module acknowledged 0x03 with 0x09") or, in principle, as the wrong reply. Record + everything you intend to replay. CAN/UDS matches whole frames and gives the clean error. - **Timing is ignored.** - **Read-only, always.** `dtc clear` and `adaptation set` are refused under `--replay` before they plan anything or take a backup, so a recording can never be mistaken for a real change. diff --git a/docs/web.md b/docs/web.md index 4cff49e..79912fc 100644 --- a/docs/web.md +++ b/docs/web.md @@ -23,6 +23,13 @@ from it. Every request goes through one pure function (`opendiag-web`), which en Requests are handled one at a time, so the diagnostic session is never used concurrently. When idle, the server sends keep-alive messages; if one fails, the API answers 503 until you restart. +## Live data view + +Each measuring-block cell gets its own tile: the latest raw value (A×256+B), its min and max over the visible +window, and a sparkline on its own scale. Controls: start/pause, clear, sample interval (0.5 to 5 s), and a CSV +download of everything read this session (`time_ms,group,cell,formula,a,b`, the same columns as `opendiag log`). +Under `--replay` the page says so and plays the recording back ([replay.md](replay.md)). + ## Limits - Live data is KW1281 only, as raw cells (formula, A, B). Values are not converted to units, and the chart plots