Skip to content
Open
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 CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ It extracts the Windows build (ready to run, `.exe` already executable) into `<s

Before each phase, produce a short plan and acceptance tests, then implement.

Status: phases 0-2 are largely done (transports, ISO-TP, UDS, KWP2000, KW1281, serial and SocketCAN drivers). Phase 3 (read-only MVP) is in progress: the CLI works against a virtual ECU, and `probe` can talk to a real K-line module. BMW F-series (ENET/HSFZ, `opendiag-bmw`, see `docs/bmw.md`): step 1 read-only, simulator-tested only. Never bundle BMW proprietary data. Done and simulator-tested: TP2.0, KWP2000/KW1281 scan and DTCs, KW1281 live-data logging, `--replay` of recorded traces, the `serve` dashboard, the open data format v0, raw `log --ids` over KWP2000/UDS. Not done: decoded KWP2000 measuring blocks (no public source), BMW replay, GUI. Nothing has been verified against a real car yet.
Status: phases 0-2 are largely done (transports, ISO-TP, UDS, KWP2000, KW1281, serial and SocketCAN drivers). Phase 3 (read-only MVP) is in progress: the CLI works against a virtual ECU, and `probe` can talk to a real K-line module. BMW F-series (ENET/HSFZ, `opendiag-bmw`, see `docs/bmw.md`): step 1 read-only, simulator-tested only. Never bundle BMW proprietary data. Done and simulator-tested: TP2.0, KWP2000/KW1281 scan and DTCs, KW1281 live-data logging, `--replay` of recorded traces (K-line, CAN and BMW HSFZ), the `serve` dashboard, the open data format v0, raw `log --ids` over KWP2000/UDS. Not done: decoded KWP2000 measuring blocks (no public source), GUI. Nothing has been verified against a real car yet.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/opendiag-bmw/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repository.workspace = true
opendiag-core = { path = "../opendiag-core" }
opendiag-proto = { path = "../opendiag-proto" }
opendiag-services = { path = "../opendiag-services" }
opendiag-transport = { path = "../opendiag-transport" }

[lints]
workspace = true
2 changes: 2 additions & 0 deletions crates/opendiag-bmw/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub mod ident;
pub mod live;
pub mod mock;
pub mod scan;
pub mod trace;
pub mod vehicle;

pub use discovery::{broadcast_target, discover, Discovered};
Expand All @@ -26,4 +27,5 @@ pub use gateway::{ByteStream, HsfzGateway, HsfzLink, TcpByteStream};
pub use ident::{read_did, read_ident, BmwIdent};
pub use live::{log_dids_csv, DidLogConfig, DidLogSummary};
pub use scan::{scan, ScanEntry};
pub use trace::{RecordingStream, ReplayStream};
pub use vehicle::BmwVehicle;
135 changes: 135 additions & 0 deletions crates/opendiag-bmw/src/trace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
//! Record and replay of the HSFZ byte stream, so BMW commands can run with no car attached.
//!
//! [`RecordingStream`] wraps any [`ByteStream`] and writes everything that crosses it to a trace in
//! the same text format as the K-line and CAN traces (`TX raw ..` for bytes sent to the gateway,
//! `RX raw ..` for bytes read from it). It records raw HSFZ frames, uninterpreted.
//!
//! [`ReplayStream`] plays such a trace back as the gateway. Like `TraceEcu`, it is lenient: each
//! write is looked up in the recording by *content* (forward from the last match, then from the
//! start), and the recorded bytes that followed it are served to the next reads. A write that was
//! never recorded is an error naming it; nothing is invented. Replies are the recorded bytes, so
//! values that changed over time repeat. Timing is ignored.
//!
//! A replayed session can only ever do what was recorded, which is why `bmw` write commands refuse
//! to run against one (see the CLI).

use std::io::Write;
use std::time::{Duration, Instant};

use opendiag_core::{Error, Result};
use opendiag_transport::{format_frame, parse_trace, Frame, TraceEntry, TraceEvent, TRACE_HEADER};

use crate::gateway::ByteStream;

/// A boxed stream is a stream, so one gateway type serves live, recorded and replayed sessions.
impl ByteStream for Box<dyn ByteStream> {
fn write_all(&mut self, data: &[u8]) -> Result<()> {
(**self).write_all(data)
}
fn read_some(&mut self, timeout: Duration) -> Result<Vec<u8>> {
(**self).read_some(timeout)
}
fn reconnect(&mut self) -> Result<()> {
(**self).reconnect()
}
}

/// Records everything that crosses `inner` to `out`. Silent timeouts are not recorded.
pub struct RecordingStream<S: ByteStream, W: Write> {
inner: S,
out: W,
started: Instant,
}

impl<S: ByteStream, W: Write> RecordingStream<S, W> {
pub fn new(inner: S, mut out: W) -> Result<Self> {
writeln!(out, "{TRACE_HEADER}")
.and_then(|()| writeln!(out, "# hsfz byte stream: TX/RX are raw HSFZ frames"))
.and_then(|()| out.flush())
.map_err(|e| Error::Io(format!("cannot write the trace: {e}")))?;
Ok(Self {
inner,
out,
started: Instant::now(),
})
}

fn log(&mut self, event: &TraceEvent) -> Result<()> {
let t = self.started.elapsed();
writeln!(self.out, "{}.{:06} {event}", t.as_secs(), t.subsec_micros())
.and_then(|()| self.out.flush())
.map_err(|e| Error::Io(format!("cannot write the trace: {e}")))
}
}

impl<S: ByteStream, W: Write> ByteStream for RecordingStream<S, W> {
fn write_all(&mut self, data: &[u8]) -> Result<()> {
self.log(&TraceEvent::Tx(Frame::Raw(data.to_vec())))?;
self.inner.write_all(data)
}

fn read_some(&mut self, timeout: Duration) -> Result<Vec<u8>> {
let bytes = self.inner.read_some(timeout)?;
self.log(&TraceEvent::Rx(Frame::Raw(bytes.clone())))?;
Ok(bytes)
}

fn reconnect(&mut self) -> Result<()> {
self.inner.reconnect()
}
}

/// A recorded HSFZ session played back as the gateway.
#[derive(Debug)]
pub struct ReplayStream {
entries: Vec<TraceEntry>,
pos: usize,
}

impl ReplayStream {
pub fn from_text(text: &str) -> Result<Self> {
Ok(Self {
entries: parse_trace(text)?,
pos: 0,
})
}
}

impl ByteStream for ReplayStream {
fn write_all(&mut self, data: &[u8]) -> Result<()> {
let want = TraceEvent::Tx(Frame::Raw(data.to_vec()));
let hit = (self.pos..self.entries.len())
.chain(0..self.pos.min(self.entries.len()))
.find(|&i| self.entries[i].event == want);
match hit {
Some(i) => {
self.pos = i + 1;
Ok(())
}
None => Err(Error::Transport(format!(
"not in recording: the client sent `{}`, which was never recorded ({})",
format_frame(&Frame::Raw(data.to_vec())),
"replay answers only what was captured"
))),
}
}

fn read_some(&mut self, _timeout: Duration) -> Result<Vec<u8>> {
match self.entries.get(self.pos) {
Some(TraceEntry {
event: TraceEvent::Rx(Frame::Raw(b)),
..
}) => {
let b = b.clone();
self.pos += 1;
Ok(b)
}
// The gateway said nothing more after that request.
_ => Err(Error::Timeout),
}
}

fn reconnect(&mut self) -> Result<()> {
Ok(())
}
}
85 changes: 85 additions & 0 deletions crates/opendiag-bmw/tests/replay.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! Record a session against the mock gateway, then replay it with no network at all.

use std::cell::RefCell;
use std::io::Write;
use std::rc::Rc;

use opendiag_bmw::mock::{MockGateway, VirtualVehicle};
use opendiag_bmw::{
read_ident, ByteStream, HsfzGateway, RecordingStream, ReplayStream, TcpByteStream,
};
use opendiag_core::Error;
use opendiag_proto::clock::SystemClock;
use opendiag_proto::uds::{UdsClient, UdsConfig};

/// A `Write` the test can read back after the recorder owns it.
#[derive(Clone, Default)]
struct Shared(Rc<RefCell<Vec<u8>>>);

impl Write for Shared {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.0.borrow_mut().extend_from_slice(b);
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

fn record_ident() -> String {
let mock = MockGateway::start(VirtualVehicle::demo()).unwrap();
let tcp = TcpByteStream::connect(mock.tcp_addr()).unwrap();
let out = Shared::default();
let rec = RecordingStream::new(tcp, out.clone()).unwrap();
let gw = HsfzGateway::new(rec, SystemClock::new(), 0xF4);
let mut uds = UdsClient::new(gw.link(0x10), UdsConfig::default());
read_ident(&mut uds).unwrap();
let text = String::from_utf8(out.0.borrow().clone()).unwrap();
text
}

fn replay_gateway(text: &str) -> HsfzGateway<Box<dyn ByteStream>, SystemClock> {
let s: Box<dyn ByteStream> = Box::new(ReplayStream::from_text(text).unwrap());
HsfzGateway::new(s, SystemClock::new(), 0xF4)
}

#[test]
fn a_recorded_session_replays_without_a_network() {
let text = record_ident();
assert!(text.starts_with("# opendiag trace v1"));
assert!(
text.contains(" TX raw ") && text.contains(" RX raw "),
"{text}"
);
let gw = replay_gateway(&text);
let mut uds = UdsClient::new(gw.link(0x10), UdsConfig::default());
let id = read_ident(&mut uds).unwrap();
assert_eq!(id.vin.as_deref(), Some("WBASIMULATED00001"));
assert_eq!(id.i_level_text().as_deref(), Some("F020-00-00-000"));
// Asking again is fine: the recording is searched again from the start.
let again = read_ident(&mut uds).unwrap();
assert_eq!(again.vin, id.vin);
}

#[test]
fn a_request_that_was_never_recorded_is_named_not_invented() {
let text = record_ident();
let gw = replay_gateway(&text);
let mut uds = UdsClient::new(gw.link(0x10), UdsConfig::default());
let err = uds.read_data_by_identifier(0x1234).unwrap_err();
assert!(
matches!(&err, Error::Transport(m) if m.contains("not in recording")),
"{err:?}"
);
}

#[test]
fn an_empty_recording_answers_nothing() {
let gw = replay_gateway("# opendiag trace v1\n");
let mut uds = UdsClient::new(gw.link(0x10), UdsConfig::default());
let err = read_ident(&mut uds).unwrap_err();
assert!(
matches!(&err, Error::Transport(m) if m.contains("not in recording")),
"{err:?}"
);
}
Loading
Loading