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
62 changes: 58 additions & 4 deletions crates/opendiag-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use clap::{Args, Parser, Subcommand};
use opendiag_core::Error;
use opendiag_data::{json_schema_pretty, load_dir, DataSet};
use opendiag_proto::clock::SystemClock;
use opendiag_proto::clock::{FakeClock, SystemClock};
use opendiag_proto::isotp::{Config as IsoTpConfig, IsoTpLink};
use opendiag_proto::kw1281::{Kw1281Client, Kw1281Config};
use opendiag_proto::kwp::{KwpClient, KwpConfig, KwpService};
Expand All @@ -25,7 +25,7 @@ use opendiag_services::{
};
use opendiag_transport::{
list_serial_ports, open_can, Elm327, Elm327Emulator, Elm327Serial, KLineSerial, SerialIo,
TraceStatus, Tracing, Transport,
TraceEcu, TraceStatus, Tracing, Transport,
};

/// Which vehicle family a command talks to.
Expand Down Expand Up @@ -303,6 +303,14 @@ struct Target {
/// Record every byte sent and received to this file (see docs/capture.md).
#[arg(long)]
trace: Option<PathBuf>,
/// Run against a recorded trace instead of a vehicle (read-only, no hardware). Add
/// --slow-init for a KW1281 recording or --fast-init for KWP2000; otherwise it is UDS.
/// Only what was recorded can be answered; see docs/replay.md.
#[arg(
long,
conflicts_with_all = ["simulate", "simulate_kw1281", "simulate_kwp", "simulate_elm327", "port", "can", "elm327", "trace"]
)]
replay: Option<PathBuf>,
/// UDS over CAN through an ELM327-style adapter on this serial port, e.g. COM4.
/// Degraded: 11-bit ids only, slow, many clones are flaky. Read docs/elm327.md.
#[arg(long)]
Expand Down Expand Up @@ -804,6 +812,49 @@ fn elm327_session<P: SerialIo + 'static>(
})
}

/// A recorded session standing in for the vehicle. Always read-only: see `connect_for_write`.
fn connect_replay(path: &Path, target: &Target) -> Result<Connection, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let ecu = TraceEcu::from_text(&text).map_err(|e| e.to_string())?;
eprintln!(
"[replay] {} (recorded answers only; read-only, no hardware)",
path.display()
);
let transport: Box<dyn Transport> = Box::new(ecu);
let module: Box<dyn Module> = if target.slow_init {
let cfg = Kw1281Config {
echo: !target.no_echo,
..Kw1281Config::default()
};
let client = Kw1281Client::new(transport, FakeClock::new(), cfg);
Box::new(Kw1281Module::connect(client, target.address).map_err(|e| e.to_string())?)
} else if target.fast_init {
let mut kwp = KwpClient::new(transport, KwpConfig::new(target.address));
kwp.start_communication().map_err(|e| e.to_string())?;
Box::new(KwpModule::start(kwp, target.address, "kwp2000").map_err(|e| e.to_string())?)
} else {
uds_module(transport, target.tester_id, target.ecu_id)
};
Ok(Connection {
module,
_trace: None,
})
}

/// Like `connect`, for commands that change the vehicle. A replay is never writable: nothing
/// is sent anywhere, so a "successful" write would only look like one.
fn connect_for_write(target: &Target) -> Result<Connection, String> {
if target.replay.is_some() {
return Err(
"--replay is read-only: writes are refused so a recording can never be \
mistaken for a real change"
.into(),
);
}
connect(target)
}

fn connect_tp20(iface: &str, target: &Target) -> Result<Connection, String> {
let can = open_can(iface).map_err(|e| e.to_string())?;
let (transport, report) = trace_transport(can, target.trace.as_deref())?;
Expand All @@ -829,6 +880,9 @@ fn connect_tp20(iface: &str, target: &Target) -> Result<Connection, String> {
/// Open whichever module the flags select: a virtual module, KW1281 (`--slow-init`),
/// KWP2000 on K-line (`--fast-init`), or KWP2000 over TP2.0 on CAN (`--can`).
fn connect(target: &Target) -> Result<Connection, String> {
if let Some(path) = &target.replay {
return connect_replay(path, target);
}
let trace = target.trace.as_deref();
if target.simulate {
eprintln!("[simulated] virtual UDS ECU, tester id {TESTER_ID:#05X}");
Expand Down Expand Up @@ -973,7 +1027,7 @@ fn adaptation_set(
store: &StoreArg,
) -> Result<(), String> {
let store = backup_store(store);
let mut conn = connect(target)?;
let mut conn = connect_for_write(target)?;
let access = conn.module.adaptation().ok_or(NO_ADAPTATION)?;
let change = plan_change(access, channel, value).map_err(|e| e.to_string())?;
if change.old == change.new {
Expand Down Expand Up @@ -1418,7 +1472,7 @@ fn dtc_read(target: &Target) -> Result<(), String> {

fn dtc_clear(target: &Target, store: &StoreArg) -> Result<(), String> {
let store = backup_store(store);
let mut conn = connect(target)?;
let mut conn = connect_for_write(target)?;
let data = load_data();
let access = conn.module.faults();
let shown = plan_clear(access).map_err(|e| e.to_string())?;
Expand Down
146 changes: 146 additions & 0 deletions crates/opendiag-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1514,3 +1514,149 @@ fn bmw_coding_refuses_unknown_values_fields_and_blocks_without_writing() {
assert!(!ok && err.contains("no definition"), "{err}");
assert!(!backups.exists(), "nothing may be backed up or written");
}

// ---- replay: a recorded session standing in for the vehicle (no hardware) ----

fn trace_path(name: &str) -> String {
std::env::temp_dir()
.join(format!(
"opendiag-replay-{}-{name}.trace",
std::process::id()
))
.to_string_lossy()
.into_owned()
}

/// Record `cmd` against the simulator, then run it again from the recording; the output must match.
fn assert_replay_matches(cmd: &[&str], sim_flag: &str, replay_flags: &[&str], name: &str) {
let trace = trace_path(name);
let mut rec: Vec<&str> = cmd.to_vec();
rec.extend([sim_flag, "--trace", &trace]);
let (ok, live, err) = run(&rec, "");
assert!(ok, "record failed: {err}");

let mut rep: Vec<&str> = cmd.to_vec();
rep.extend(["--replay", &trace]);
rep.extend(replay_flags);
let (ok, replayed, err) = run(&rep, "");
let _ = std::fs::remove_file(&trace);
assert!(ok, "replay failed: {err}");
assert!(err.contains("[replay]"), "{err}");
// A log's time_ms column is the real clock, which differs run to run on a busy machine.
assert_eq!(without_time_column(&live), without_time_column(&replayed));
}

fn without_time_column(out: &str) -> String {
if !out.starts_with("time_ms,") {
return out.to_string();
}
out.lines()
.map(|l| l.split_once(',').map_or(l, |(_, rest)| rest))
.collect::<Vec<_>>()
.join("\n")
}

#[test]
fn replay_reproduces_scan_and_dtc_read_for_every_protocol() {
assert_replay_matches(&["scan"], "--simulate", &[], "uds-scan");
assert_replay_matches(&["dtc", "read"], "--simulate", &[], "uds-dtc");
assert_replay_matches(&["scan"], "--simulate-kw1281", &["--slow-init"], "kw-scan");
assert_replay_matches(
&["dtc", "read"],
"--simulate-kw1281",
&["--slow-init"],
"kw-dtc",
);
assert_replay_matches(&["scan"], "--simulate-kwp", &["--fast-init"], "kwp-scan");
assert_replay_matches(
&["dtc", "read"],
"--simulate-kwp",
&["--fast-init"],
"kwp-dtc",
);
}

#[test]
fn replay_reproduces_a_live_data_log() {
assert_replay_matches(
&[
"log",
"--groups",
"1",
"--samples",
"2",
"--interval-ms",
"10",
],
"--simulate-kw1281",
&["--slow-init"],
"kw-log",
);
}

#[test]
fn replay_can_be_asked_the_same_thing_twice() {
let trace = trace_path("twice");
let (ok, _, err) = run(&["dtc", "read", "--simulate-kw1281", "--trace", &trace], "");
assert!(ok, "{err}");
for _ in 0..2 {
let (ok, out, err) = run(&["dtc", "read", "--replay", &trace, "--slow-init"], "");
assert!(ok, "{err}");
assert!(out.contains("00525"), "{out}");
}
let _ = std::fs::remove_file(&trace);
}

#[test]
fn replay_names_a_request_that_was_never_recorded() {
let trace = trace_path("missing");
let (ok, _, err) = run(&["scan", "--simulate", "--trace", &trace], "");
assert!(ok, "{err}");
let (ok, _, err) = run(&["dtc", "read", "--replay", &trace], "");
let _ = std::fs::remove_file(&trace);
assert!(!ok);
assert!(err.contains("not in recording"), "{err}");
assert!(err.contains("TX can 7E0#"), "{err}");
}

#[test]
fn replay_refuses_every_write_before_anything_is_planned() {
let trace = trace_path("writes");
let (ok, _, err) = run(&["dtc", "read", "--simulate-kw1281", "--trace", &trace], "");
assert!(ok, "{err}");
let backup = trace_path("writes-backup");
let writes: [&[&str]; 2] = [
&["dtc", "clear", "--backup-file", &backup],
&[
"adaptation",
"set",
"--channel",
"4",
"--value",
"1",
"--workshop-code",
"1",
"--backup-file",
&backup,
],
];
for w in writes {
let mut args: Vec<&str> = w.to_vec();
args.extend(["--replay", &trace, "--slow-init"]);
let (ok, out, err) = run(&args, "y\ny\n");
assert!(!ok, "{args:?} must fail, got {out}");
assert!(err.contains("read-only"), "{args:?}: {err}");
}
assert!(
!std::path::Path::new(&backup).exists(),
"a refused write must not even take a backup"
);
let _ = std::fs::remove_file(&trace);
}

#[test]
fn replay_cannot_be_combined_with_a_live_connection() {
let (ok, _, err) = run(&["scan", "--replay", "x.trace", "--simulate"], "");
assert!(!ok);
assert!(err.contains("cannot be used with"), "{err}");
}
2 changes: 2 additions & 0 deletions crates/opendiag-transport/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod simulator;
#[cfg(target_os = "linux")]
mod socketcan_driver;
mod trace;
mod trace_ecu;

use std::time::Duration;

Expand All @@ -23,6 +24,7 @@ pub use trace::{
format_frame, parse_trace, TraceEntry, TraceEvent, TraceReplay, TraceStatus, Tracing,
TRACE_HEADER,
};
pub use trace_ecu::TraceEcu;

/// A unit of data on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down
Loading
Loading