From de4929dd312084daa685ab629f46d1c52df2dab9 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:25:11 +0000 Subject: [PATCH 1/2] feat(transport,cli): --replay runs commands against a recorded trace TraceEcu answers requests from a recording by content, so scan, dtc read, log and serve run with no hardware. Unrecorded requests are an error naming them; replay is always read-only and refuses dtc clear and adaptation set before anything is planned. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Xe1HmJJjhbWaBGaF6FKosA --- crates/opendiag-cli/src/main.rs | 62 ++++++++- crates/opendiag-cli/tests/cli.rs | 135 +++++++++++++++++++ crates/opendiag-transport/src/lib.rs | 2 + crates/opendiag-transport/src/trace_ecu.rs | 135 +++++++++++++++++++ crates/opendiag-transport/tests/trace_ecu.rs | 89 ++++++++++++ docs/capture.md | 2 + docs/replay.md | 44 ++++++ 7 files changed, 465 insertions(+), 4 deletions(-) create mode 100644 crates/opendiag-transport/src/trace_ecu.rs create mode 100644 crates/opendiag-transport/tests/trace_ecu.rs create mode 100644 docs/replay.md diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index 61a3d0a..fad2e45 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -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}; @@ -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. @@ -303,6 +303,14 @@ struct Target { /// Record every byte sent and received to this file (see docs/capture.md). #[arg(long)] trace: Option, + /// 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, /// 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)] @@ -804,6 +812,49 @@ fn elm327_session( }) } +/// A recorded session standing in for the vehicle. Always read-only: see `connect_for_write`. +fn connect_replay(path: &Path, target: &Target) -> Result { + 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 = Box::new(ecu); + let module: Box = 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 { + 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 { let can = open_can(iface).map_err(|e| e.to_string())?; let (transport, report) = trace_transport(can, target.trace.as_deref())?; @@ -829,6 +880,9 @@ fn connect_tp20(iface: &str, target: &Target) -> Result { /// 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 { + 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}"); @@ -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 { @@ -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())?; diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index 0c2feb8..e01da3c 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1514,3 +1514,138 @@ 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}"); + assert_eq!(live, replayed); +} + +#[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}"); +} diff --git a/crates/opendiag-transport/src/lib.rs b/crates/opendiag-transport/src/lib.rs index c4dffe0..010e7f3 100644 --- a/crates/opendiag-transport/src/lib.rs +++ b/crates/opendiag-transport/src/lib.rs @@ -8,6 +8,7 @@ mod simulator; #[cfg(target_os = "linux")] mod socketcan_driver; mod trace; +mod trace_ecu; use std::time::Duration; @@ -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)] diff --git a/crates/opendiag-transport/src/trace_ecu.rs b/crates/opendiag-transport/src/trace_ecu.rs new file mode 100644 index 0000000..a1c9a3c --- /dev/null +++ b/crates/opendiag-transport/src/trace_ecu.rs @@ -0,0 +1,135 @@ +//! A recorded session played back as a stand-in for the vehicle. +//! +//! [`TraceReplay`](crate::TraceReplay) is strict: the client must repeat the recording exactly, which +//! makes it a regression test. `TraceEcu` is lenient: it behaves like the module that was recorded. +//! Each operation the client performs (`send`, `set_baud`, `slow_init`, `fast_init`) is looked up in +//! the recording by *content*, searching forward from the last match and then from the start, and +//! the recorded replies that followed it are served. That lets `scan`, `dtc read`, `log` and `serve` +//! run, repeatedly and in any order, against a capture with no hardware attached. +//! +//! Limits, stated plainly: +//! - Only what was recorded can be answered. An operation that is not in the recording is an error +//! naming it; nothing is guessed or invented. +//! - Replies are the recorded bytes. A reply that depends on state (a counter, a changing value) +//! repeats the recorded value, so this does not simulate a live vehicle. +//! - Matching is by content. On K-line, identical single-byte acknowledgements are ambiguous; the +//! forward-first search resolves them for sessions replayed in recorded order, but a session +//! replayed out of order can be matched to the wrong place. +//! - Timing is ignored. + +use std::time::Duration; + +use opendiag_core::{Error, Result}; + +use crate::trace::{parse_trace, TraceEntry, TraceEvent}; +use crate::{Capabilities, Frame, Transport}; + +#[derive(Debug)] +pub struct TraceEcu { + entries: Vec, + /// Next entry to hand out as a reply. + pos: usize, + rewinds: u32, +} + +impl TraceEcu { + pub fn from_text(text: &str) -> Result { + Ok(Self::from_entries(parse_trace(text)?)) + } + + pub fn from_entries(entries: Vec) -> Self { + Self { + entries, + pos: 0, + rewinds: 0, + } + } + + /// How many times an operation was only found by going back to the start of the recording. + pub fn rewinds(&self) -> u32 { + self.rewinds + } + + /// Find `op` by content, forward from the cursor first and then from the start. + fn find(&mut self, op: &TraceEvent) -> Result<()> { + let len = self.entries.len(); + let forward = (self.pos..len).find(|&i| &self.entries[i].event == op); + let found = match forward { + Some(i) => Some(i), + None => { + let back = (0..self.pos.min(len)).find(|&i| &self.entries[i].event == op); + if back.is_some() { + self.rewinds += 1; + } + back + } + }; + match found { + Some(i) => { + self.pos = i + 1; + Ok(()) + } + None => Err(Error::Transport(format!( + "not in recording: the client did `{op}`, which was never recorded" + ))), + } + } +} + +impl Transport for TraceEcu { + fn send(&mut self, frame: &Frame) -> Result<()> { + self.find(&TraceEvent::Tx(frame.clone())) + } + + fn recv(&mut self, _timeout: Duration) -> Result { + match self.entries.get(self.pos) { + Some(TraceEntry { + event: TraceEvent::Rx(f), + .. + }) => { + let f = f.clone(); + self.pos += 1; + Ok(f) + } + Some(TraceEntry { + event: TraceEvent::RecvTimeout(_), + .. + }) => { + self.pos += 1; + Err(Error::Timeout) + } + Some(TraceEntry { + event: TraceEvent::Error(m), + .. + }) => { + let e = Error::Transport(m.clone()); + self.pos += 1; + Err(e) + } + // The module said nothing more after that request. + _ => Err(Error::Timeout), + } + } + + fn set_baud(&mut self, baud: u32) -> Result<()> { + self.find(&TraceEvent::SetBaud(baud)) + } + + fn slow_init(&mut self, address: u8) -> Result<()> { + self.find(&TraceEvent::SlowInit(address)) + } + + fn fast_init(&mut self) -> Result<()> { + self.find(&TraceEvent::FastInit) + } + + fn capabilities(&self) -> Capabilities { + Capabilities { + can: true, + kline: true, + set_baud: true, + slow_init: true, + fast_init: true, + } + } +} diff --git a/crates/opendiag-transport/tests/trace_ecu.rs b/crates/opendiag-transport/tests/trace_ecu.rs new file mode 100644 index 0000000..30095a0 --- /dev/null +++ b/crates/opendiag-transport/tests/trace_ecu.rs @@ -0,0 +1,89 @@ +use std::time::Duration; + +use opendiag_transport::{Frame, TraceEcu, Transport}; + +const T: Duration = Duration::from_millis(10); + +fn can(id: u32, data: &[u8]) -> Frame { + Frame::Can { + id, + extended: false, + data: data.to_vec(), + } +} + +const TRACE: &str = "# opendiag trace v1 +0.000000 TX can 7E0#0210030000000000 +0.001000 RX can 7E8#065003003201F4 +0.100000 TX can 7E0#0322F19000000000 +0.101000 RX can 7E8#0762F19001020304 +0.200000 TX can 7E0#0319020000000000 +0.210000 EV recv_timeout 1000 +"; + +#[test] +fn answers_recorded_requests_by_content_in_any_order() { + let mut ecu = TraceEcu::from_text(TRACE).unwrap(); + // Ask for the second request first. + ecu.send(&can(0x7E0, &[0x03, 0x22, 0xF1, 0x90, 0, 0, 0, 0])) + .unwrap(); + assert_eq!( + ecu.recv(T).unwrap(), + can(0x7E8, &[0x07, 0x62, 0xF1, 0x90, 1, 2, 3, 4]) + ); +} + +#[test] +fn can_be_asked_again_after_the_end_of_the_recording() { + let mut ecu = TraceEcu::from_text(TRACE).unwrap(); + let req = can(0x7E0, &[0x02, 0x10, 0x03, 0, 0, 0, 0, 0]); + for _ in 0..3 { + ecu.send(&req).unwrap(); + assert_eq!( + ecu.recv(T).unwrap(), + can(0x7E8, &[0x06, 0x50, 0x03, 0x00, 0x32, 0x01, 0xF4]) + ); + } + assert!(ecu.rewinds() >= 1); +} + +#[test] +fn unrecorded_request_is_an_error_that_names_it() { + let mut ecu = TraceEcu::from_text(TRACE).unwrap(); + let err = ecu + .send(&can(0x7E0, &[0x04, 0x31, 0x01, 0xFF, 0x00, 0, 0, 0])) + .unwrap_err() + .to_string(); + assert!(err.contains("not in recording"), "{err}"); + assert!(err.contains("7E0#0431"), "{err}"); +} + +#[test] +fn recorded_silence_is_a_timeout_and_nothing_is_invented() { + let mut ecu = TraceEcu::from_text(TRACE).unwrap(); + ecu.send(&can(0x7E0, &[0x03, 0x19, 0x02, 0, 0, 0, 0, 0])) + .unwrap(); + assert!(matches!(ecu.recv(T), Err(opendiag_core::Error::Timeout))); + // And nothing more is ever delivered. + assert!(matches!(ecu.recv(T), Err(opendiag_core::Error::Timeout))); +} + +#[test] +fn k_line_acks_are_matched_forward_first() { + let text = "# opendiag trace v1 +0.000000 EV slow_init 01 +0.100000 RX raw 55 01 8A +0.200000 TX raw 75 +0.300000 RX raw 03 +0.400000 TX raw 75 +0.500000 RX raw 09 +"; + let mut ecu = TraceEcu::from_text(text).unwrap(); + ecu.slow_init(0x01).unwrap(); + assert_eq!(ecu.recv(T).unwrap(), Frame::Raw(vec![0x55, 0x01, 0x8A])); + ecu.send(&Frame::Raw(vec![0x75])).unwrap(); + assert_eq!(ecu.recv(T).unwrap(), Frame::Raw(vec![0x03])); + // The same ack again lands on the *next* recorded one, not the first. + ecu.send(&Frame::Raw(vec![0x75])).unwrap(); + assert_eq!(ecu.recv(T).unwrap(), Frame::Raw(vec![0x09])); +} diff --git a/docs/capture.md b/docs/capture.md index 21f6490..1338f65 100644 --- a/docs/capture.md +++ b/docs/capture.md @@ -62,3 +62,5 @@ That fixture is **synthetic**, recorded from the built-in virtual module. A trac vehicle drops into the same test: copy it to `tests/fixtures/`, add a test that runs the client against it, and the real behaviour becomes a permanent regression check. Contributed traces must follow the rules in [legal.md](legal.md): only your own vehicle, and nothing derived from proprietary tools. + +To run the CLI against a recording with no hardware, see [replay.md](replay.md). diff --git a/docs/replay.md b/docs/replay.md new file mode 100644 index 0000000..ca1d62e --- /dev/null +++ b/docs/replay.md @@ -0,0 +1,44 @@ +# Replaying a recorded session (`--replay`) + +`--replay FILE` runs any vehicle command against a recorded trace instead of a car, so you can develop +and demo with no hardware attached. + +```bash +# 1. Record once (against a simulator, or a real module with your own cable): +opendiag dtc read --port /dev/ttyUSB0 --slow-init --trace session.trace + +# 2. Replay as often as you like, with no cable: +opendiag dtc read --replay session.trace --slow-init +opendiag scan --replay session.trace --slow-init +opendiag serve --replay session.trace --slow-init +``` + +Say which protocol the recording used, as you would for a live connection: `--slow-init` for KW1281, +`--fast-init` for KWP2000, neither for UDS. `--replay` cannot be combined with `--simulate*`, `--port`, +`--can`, `--elm327` or `--trace`. + +## How it answers + +Each thing the tool does (send a frame, set a baud rate, start an init) is looked up in the recording +**by content**, searching forward from the last match and then from the start. The replies that followed +it in the recording are returned. So requests can be repeated, and made in a different order from the +recording, as long as each was recorded at least once. This is different from `TraceReplay` +([capture.md](capture.md)), which is strict and is used for regression tests. + +## Limits + +- **Only what was recorded can be answered.** Anything else fails with `not in recording: the client did + ...`, 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. +- **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. +- **BMW (ENET/HSFZ) is not covered yet.** It runs over TCP, not this transport. +- Like every test here, a replay of a *simulator* recording only proves the code agrees with itself. + Replaying a recording from a real module is what tests our understanding of the protocol. + +A trace holds whatever the vehicle reported (VIN, part numbers, fault history). Read the privacy note in +[capture.md](capture.md) before sharing one. From a3c176b01801d896dc869c5ebf2f9baad65b81bb Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:41:00 +0000 Subject: [PATCH 2/2] test(cli): compare replayed logs without the wall-clock time column Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Xe1HmJJjhbWaBGaF6FKosA --- crates/opendiag-cli/tests/cli.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index e01da3c..08f97ae 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1542,7 +1542,18 @@ fn assert_replay_matches(cmd: &[&str], sim_flag: &str, replay_flags: &[&str], na let _ = std::fs::remove_file(&trace); assert!(ok, "replay failed: {err}"); assert!(err.contains("[replay]"), "{err}"); - assert_eq!(live, replayed); + // 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::>() + .join("\n") } #[test]