Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/opendiag-cli/src/bmw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u16, String> {
Expand Down
17 changes: 16 additions & 1 deletion crates/opendiag-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -1125,14 +1131,21 @@ 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.
pub(crate) fn serve_module(
module: Box<dyn Module>,
connection: String,
simulated: bool,
replay: bool,
listen_port: u16,
) -> Result<(), String> {
let mut module = module;
Expand All @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
96 changes: 96 additions & 0 deletions crates/opendiag-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32> {
csv.lines()
.skip(1)
.filter_map(|l| {
let f: Vec<&str> = l.split(',').collect();
(f[2] == "1").then(|| f[4].parse::<u32>().unwrap() * 256 + f[5].parse::<u32>().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}");
}
8 changes: 8 additions & 0 deletions crates/opendiag-services/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub ident: Ident,
Expand Down Expand Up @@ -124,6 +126,12 @@ pub fn render_html(r: &Report) -> String {
);
}

if r.replay {
h.push_str(
"<p class=\"banner\" role=\"note\">REPLAYED DATA: this report comes from a recorded session, not from a vehicle right now.</p>\n",
);
}

h.push_str("<h2>Summary</h2>\n<dl>\n");
h.push_str(&row("Connection", &r.connection));
if let Some(m) = &r.module {
Expand Down
11 changes: 11 additions & 0 deletions crates/opendiag-services/tests/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down Expand Up @@ -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("<h2>Summary</h2>").unwrap());
assert!(!render_html(&base()).contains("REPLAYED DATA"));
}
12 changes: 10 additions & 2 deletions crates/opendiag-web/src/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -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; } }
Loading
Loading