From be86035b76a7761485914b74cd45aa8164f309d5 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:19:55 +0000 Subject: [PATCH 1/9] refactor(proto): run UDS over a MessageLink trait instead of IsoTpLink UdsClient is now generic over MessageLink (send, recv, describe). IsoTpLink implements it, so VAG behaviour is unchanged; this lets transports that carry whole UDS messages (BMW HSFZ) reuse the client. Co-Authored-By: Claude Sonnet 5.5 --- crates/opendiag-proto/src/isotp/link.rs | 15 ++++++++++++++ crates/opendiag-proto/src/lib.rs | 1 + crates/opendiag-proto/src/link.rs | 20 +++++++++++++++++++ crates/opendiag-proto/src/uds.rs | 14 ++++++------- crates/opendiag-proto/tests/uds_client.rs | 4 ++-- crates/opendiag-services/src/demo.rs | 4 ++-- crates/opendiag-services/src/lib.rs | 16 +++++++-------- crates/opendiag-services/tests/clear_guard.rs | 2 +- crates/opendiag-services/tests/services.rs | 2 +- 9 files changed, 56 insertions(+), 22 deletions(-) create mode 100644 crates/opendiag-proto/src/link.rs diff --git a/crates/opendiag-proto/src/isotp/link.rs b/crates/opendiag-proto/src/isotp/link.rs index 0b8bbc7..e840acf 100644 --- a/crates/opendiag-proto/src/isotp/link.rs +++ b/crates/opendiag-proto/src/isotp/link.rs @@ -7,6 +7,7 @@ use opendiag_transport::{Frame, Transport}; use super::{Config, Poll, Receiver, RxEvent, Sender}; use crate::clock::Clock; +use crate::link::MessageLink; /// A point-to-point ISO-TP channel using one CAN id each way (normal addressing). pub struct IsoTpLink { @@ -109,3 +110,17 @@ impl IsoTpLink { self.recv(timeout) } } + +impl MessageLink for IsoTpLink { + fn send(&mut self, payload: &[u8]) -> Result<()> { + IsoTpLink::send(self, payload) + } + + fn recv(&mut self, timeout: Duration) -> Result> { + IsoTpLink::recv(self, timeout) + } + + fn describe(&self) -> String { + format!("UDS ECU (request id {:#05X})", self.tx_id()) + } +} diff --git a/crates/opendiag-proto/src/lib.rs b/crates/opendiag-proto/src/lib.rs index e630bd9..5620810 100644 --- a/crates/opendiag-proto/src/lib.rs +++ b/crates/opendiag-proto/src/lib.rs @@ -4,5 +4,6 @@ pub mod clock; pub mod isotp; pub mod kw1281; pub mod kwp; +pub mod link; pub mod tp20; pub mod uds; diff --git a/crates/opendiag-proto/src/link.rs b/crates/opendiag-proto/src/link.rs new file mode 100644 index 0000000..ac071d1 --- /dev/null +++ b/crates/opendiag-proto/src/link.rs @@ -0,0 +1,20 @@ +//! A message-level channel to one ECU. +//! +//! UDS needs to send a request and receive a whole reply message. How that +//! message is carried is not UDS's business: ISO-TP segments it over CAN +//! frames, while BMW's HSFZ carries it whole inside a TCP packet. This trait +//! is the seam between the two. + +use std::time::Duration; + +use opendiag_core::Result; + +/// Sends and receives whole diagnostic messages to a single ECU. +pub trait MessageLink { + /// Send one message (starting with the service id). + fn send(&mut self, payload: &[u8]) -> Result<()>; + /// Receive one message, or `Error::Timeout` if none arrives in `timeout`. + fn recv(&mut self, timeout: Duration) -> Result>; + /// Short human-readable description of the peer, for backup records. + fn describe(&self) -> String; +} diff --git a/crates/opendiag-proto/src/uds.rs b/crates/opendiag-proto/src/uds.rs index dfdc7e3..34c8aa6 100644 --- a/crates/opendiag-proto/src/uds.rs +++ b/crates/opendiag-proto/src/uds.rs @@ -8,10 +8,8 @@ use std::time::Duration; use opendiag_core::{Error, Result, WriteMode}; -use opendiag_transport::Transport; -use crate::clock::Clock; -use crate::isotp::IsoTpLink; +use crate::link::MessageLink; // Service identifiers (ISO 14229-1). pub const SID_SESSION_CONTROL: u8 = 0x10; @@ -103,8 +101,8 @@ pub enum RoutineAction { RequestResults = 0x03, } -pub struct UdsClient { - link: IsoTpLink, +pub struct UdsClient { + link: L, cfg: UdsConfig, write_mode: WriteMode, } @@ -113,9 +111,9 @@ fn protocol(msg: impl Into) -> Error { Error::Protocol(format!("uds: {}", msg.into())) } -impl UdsClient { +impl UdsClient { /// New client, read-only by default. - pub fn new(link: IsoTpLink, cfg: UdsConfig) -> Self { + pub fn new(link: L, cfg: UdsConfig) -> Self { Self { link, cfg, @@ -131,7 +129,7 @@ impl UdsClient { self.write_mode = mode; } - pub fn link(&self) -> &IsoTpLink { + pub fn link(&self) -> &L { &self.link } diff --git a/crates/opendiag-proto/tests/uds_client.rs b/crates/opendiag-proto/tests/uds_client.rs index 1078a07..fe9cd5d 100644 --- a/crates/opendiag-proto/tests/uds_client.rs +++ b/crates/opendiag-proto/tests/uds_client.rs @@ -43,12 +43,12 @@ fn reply(payload: &[u8]) -> Vec { out } -fn client(sim: Simulator) -> UdsClient { +fn client(sim: Simulator) -> UdsClient> { let link = IsoTpLink::new(sim, FakeClock::new(), TESTER, ECU, Config::default()); UdsClient::new(link, UdsConfig::default()) } -fn unlocked(sim: Simulator) -> UdsClient { +fn unlocked(sim: Simulator) -> UdsClient> { let mut c = client(sim); c.set_write_mode(WriteMode::Unlocked); c diff --git a/crates/opendiag-services/src/demo.rs b/crates/opendiag-services/src/demo.rs index 454236a..e5d5b17 100644 --- a/crates/opendiag-services/src/demo.rs +++ b/crates/opendiag-services/src/demo.rs @@ -133,7 +133,7 @@ pub fn virtual_ecu_bus() -> Simulator { } /// UDS client type used with the virtual ECU. -pub type VirtualClient = UdsClient; +pub type VirtualClient = UdsClient>; /// A UDS client wired to the virtual ECU. Read-only until a service unlocks it. pub fn virtual_uds_client() -> VirtualClient { @@ -141,7 +141,7 @@ pub fn virtual_uds_client() -> VirtualClient { } /// The same client over any transport carrying the virtual ECU's traffic. -pub fn virtual_uds_client_over(transport: T) -> UdsClient { +pub fn virtual_uds_client_over(transport: T) -> UdsClient> { let link = IsoTpLink::new( transport, FakeClock::new(), diff --git a/crates/opendiag-services/src/lib.rs b/crates/opendiag-services/src/lib.rs index 4b88e1d..e6e3356 100644 --- a/crates/opendiag-services/src/lib.rs +++ b/crates/opendiag-services/src/lib.rs @@ -24,9 +24,9 @@ pub use live::{log_csv, Limit, LiveData, LogConfig, LogSummary, CSV_HEADER}; pub use report::{escape_html, format_unix_utc, render_html, Report, ReportFault}; use opendiag_core::{Error, Result, WriteMode}; +use opendiag_proto::link::MessageLink; +use opendiag_proto::uds::Dtc; use opendiag_proto::uds::UdsClient; -use opendiag_proto::{clock::Clock, uds::Dtc}; -use opendiag_transport::Transport; /// Standard UDS identification DIDs (ISO 14229 Annex C). const DID_PART_NUMBER: u16 = 0xF187; @@ -96,7 +96,7 @@ pub fn status_flags(status: u8) -> Vec<&'static str> { .collect() } -fn text_did(uds: &mut UdsClient, did: u16) -> Result> { +fn text_did(uds: &mut UdsClient, did: u16) -> Result> { match uds.read_data_by_identifier(did) { Ok(data) => { let s = String::from_utf8_lossy(&data); @@ -112,7 +112,7 @@ fn text_did(uds: &mut UdsClient, did: u16) -> Resu } /// Read the standard identification items from a module. -pub fn identify(uds: &mut UdsClient) -> Result { +pub fn identify(uds: &mut UdsClient) -> Result { Ok(Ident { part_number: text_did(uds, DID_PART_NUMBER)?, software_version: text_did(uds, DID_SOFTWARE_VERSION)?, @@ -146,7 +146,7 @@ pub trait Module { } } -impl Module for UdsClient { +impl Module for UdsClient { fn identify(&mut self) -> Result { identify(self) } @@ -164,7 +164,7 @@ impl Module for UdsClient { } } -impl FaultAccess for UdsClient { +impl FaultAccess for UdsClient { fn protocol(&self) -> &'static str { "uds" } @@ -174,7 +174,7 @@ impl FaultAccess for UdsClient { } fn describe(&self) -> String { - format!("UDS ECU (request id {:#05X})", self.link().tx_id()) + self.link().describe() } fn read(&mut self) -> Result> { @@ -191,7 +191,7 @@ impl FaultAccess for UdsClient { } /// Read every stored DTC (status mask 0xFF). -pub fn read_dtcs(uds: &mut UdsClient) -> Result> { +pub fn read_dtcs(uds: &mut UdsClient) -> Result> { Ok(uds .read_dtcs_by_status_mask(0xFF)? .into_iter() diff --git a/crates/opendiag-services/tests/clear_guard.rs b/crates/opendiag-services/tests/clear_guard.rs index 1293d8f..08c6e04 100644 --- a/crates/opendiag-services/tests/clear_guard.rs +++ b/crates/opendiag-services/tests/clear_guard.rs @@ -14,7 +14,7 @@ use opendiag_services::{ }; use opendiag_transport::{Frame, Simulator}; -type Uds = UdsClient; +type Uds = UdsClient>; fn uds(sim: Simulator) -> Uds { let link = IsoTpLink::new(sim, FakeClock::new(), TESTER_ID, ECU_ID, Config::default()); diff --git a/crates/opendiag-services/tests/services.rs b/crates/opendiag-services/tests/services.rs index 4ca31e6..9e61bd3 100644 --- a/crates/opendiag-services/tests/services.rs +++ b/crates/opendiag-services/tests/services.rs @@ -6,7 +6,7 @@ use opendiag_services::demo::{virtual_uds_client, ECU_ID, TESTER_ID}; use opendiag_services::{identify, read_dtcs}; use opendiag_transport::{Frame, Simulator}; -fn client(sim: Simulator) -> UdsClient { +fn client(sim: Simulator) -> UdsClient> { let link = IsoTpLink::new(sim, FakeClock::new(), TESTER_ID, ECU_ID, Config::default()); UdsClient::new(link, UdsConfig::default()) } From b2e8064a925f4d0a74a02bd00960a7aceed4f600 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:21:32 +0000 Subject: [PATCH 2/9] feat(bmw): add opendiag-bmw crate with HSFZ transport, discovery and read-only ident HSFZ framing, TCP gateway session with per-ECU MessageLinks, UDP discovery, VIN / I-level / FA reads, a mock gateway served over localhost sockets, and an `opendiag bmw` subcommand (discover, ident, did). Flash/programming services are refused at the link. Simulator-tested only; unverified protocol details are flagged in code and docs/bmw.md. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 2 +- Cargo.lock | 9 + Cargo.toml | 1 + PROJECT_PLAN.md | 4 + README.md | 1 + crates/opendiag-bmw/Cargo.toml | 15 ++ crates/opendiag-bmw/src/discovery.rs | 136 +++++++++++ crates/opendiag-bmw/src/gateway.rs | 324 +++++++++++++++++++++++++++ crates/opendiag-bmw/src/hsfz.rs | 175 +++++++++++++++ crates/opendiag-bmw/src/ident.rs | 62 +++++ crates/opendiag-bmw/src/lib.rs | 19 ++ crates/opendiag-bmw/src/mock.rs | 298 ++++++++++++++++++++++++ crates/opendiag-bmw/tests/e2e.rs | 154 +++++++++++++ crates/opendiag-cli/Cargo.toml | 1 + crates/opendiag-cli/src/bmw.rs | 217 ++++++++++++++++++ crates/opendiag-cli/src/main.rs | 8 + crates/opendiag-cli/tests/cli.rs | 30 +++ docs/bmw.md | 49 ++++ docs/legal.md | 2 + docs/sources.md | 5 + 20 files changed, 1511 insertions(+), 1 deletion(-) create mode 100644 crates/opendiag-bmw/Cargo.toml create mode 100644 crates/opendiag-bmw/src/discovery.rs create mode 100644 crates/opendiag-bmw/src/gateway.rs create mode 100644 crates/opendiag-bmw/src/hsfz.rs create mode 100644 crates/opendiag-bmw/src/ident.rs create mode 100644 crates/opendiag-bmw/src/lib.rs create mode 100644 crates/opendiag-bmw/src/mock.rs create mode 100644 crates/opendiag-bmw/tests/e2e.rs create mode 100644 crates/opendiag-cli/src/bmw.rs create mode 100644 docs/bmw.md diff --git a/CLAUDE.md b/CLAUDE.md index f0b3d3d..e64fc63 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,4 +42,4 @@ cargo run -p opendiag-cli -- --version 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. Not done: TP2.0, services/CLI wiring for KWP2000 and KW1281, live-data logging, the open data format. 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. Not done: TP2.0, services/CLI wiring for KWP2000 and KW1281, live-data logging, the open data format. Nothing has been verified against a real car yet. diff --git a/Cargo.lock b/Cargo.lock index a746c87..737e8fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -362,12 +362,21 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opendiag-bmw" +version = "0.1.0" +dependencies = [ + "opendiag-core", + "opendiag-proto", +] + [[package]] name = "opendiag-cli" version = "0.1.0" dependencies = [ "clap", "getrandom", + "opendiag-bmw", "opendiag-core", "opendiag-data", "opendiag-proto", diff --git a/Cargo.toml b/Cargo.toml index 1dd1cf4..81220a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "crates/opendiag-proto", "crates/opendiag-services", "crates/opendiag-data", + "crates/opendiag-bmw", "crates/opendiag-cli", "crates/opendiag-web", ] diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md index 94d6a4b..429a895 100644 --- a/PROJECT_PLAN.md +++ b/PROJECT_PLAN.md @@ -103,6 +103,10 @@ Key design points: - Packaging: Windows installer, AppImage/deb, Homebrew. Signed releases. - Optional: ESP32/STM32 firmware adapter, headless "diag server" on a Pi/homelab with web UI. +### Phase B - BMW F-series over ENET (branch `feat/bmw-backend`) + +Status: step 1 (read-only) done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Next: ECU scan, DTC read/clear (existing guarded flow), live data by DID, ECU address table; then backup + coding (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). + ## 5. Repo layout ``` diff --git a/README.md b/README.md index ecbcc55..05f4684 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ An open source, cross-platform diagnostic suite for VAG group vehicles (VW, Audi | Transports | Serial K-line (Windows/Linux/macOS), SocketCAN (Linux), ELM327-style adapters (degraded, UDS over 11-bit CAN), Simulator, Replay | | Modules | `scan` and `dtc read/clear` work on KW1281 (`--slow-init`), KWP2000 on K-line (`--fast-init`) and KWP2000 over TP2.0 on CAN (`--can`, Linux); live data and adaptation are KW1281 only | | CLI | `scan`, `dtc read/clear`, `report` (standalone HTML), `serve` (read-only local web page), `doctor` (support summary), `log` (live data to CSV), `adaptation read/set`, `backup list/restore`, `probe`, `ports`, `capture`, `--trace` on all hardware commands, `data validate/schema` | +| BMW (F-series, ENET) | **Experimental, simulator-tested only, never run on a real car.** `opendiag bmw discover/ident/did`: HSFZ over TCP, UDP discovery, VIN / I-level / FA reads, read-only. Unverified protocol details are listed in [docs/bmw.md](docs/bmw.md) | | Data | Open YAML format with validator and generated JSON Schema (CC0-1.0) | ## Install diff --git a/crates/opendiag-bmw/Cargo.toml b/crates/opendiag-bmw/Cargo.toml new file mode 100644 index 0000000..68e2a9f --- /dev/null +++ b/crates/opendiag-bmw/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "opendiag-bmw" +description = "BMW F-series diagnostics over ENET (HSFZ): transport, discovery, read-only services" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] +opendiag-core = { path = "../opendiag-core" } +opendiag-proto = { path = "../opendiag-proto" } + +[lints] +workspace = true diff --git a/crates/opendiag-bmw/src/discovery.rs b/crates/opendiag-bmw/src/discovery.rs new file mode 100644 index 0000000..ecc653e --- /dev/null +++ b/crates/opendiag-bmw/src/discovery.rs @@ -0,0 +1,136 @@ +//! Vehicle discovery over UDP port 6811. +//! +//! VERIFIED: discovery is a UDP broadcast to port 6811 and the gateway answers +//! with an HSFZ frame of control word `0x0011` ("vehicle ident data") that +//! carries VIN, diagnostic address, IP and MAC (Quantex HSFZ page, Scapy). +//! Scapy's dissector reads a `0x0011` frame with length 0 as the *request*. +//! +//! NOT VERIFIED (flagged): the exact ASCII layout of the identification +//! string. [`parse_ident_string`] expects the form +//! `DIAGADRBMWMAC<12 hex>BMWVIN<17 chars>` as remembered from BMW +//! captures, and degrades to "raw text only" when it does not match, so a +//! different layout shows up as an unparsed string rather than wrong data. + +use std::net::{IpAddr, SocketAddr, UdpSocket}; +use std::time::{Duration, Instant}; + +use opendiag_core::{Error, Result}; + +use crate::hsfz::{take_frame, HsfzFrame, CTRL_VEHICLE_IDENT, UDP_PORT}; + +/// A gateway that answered discovery. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Discovered { + pub ip: IpAddr, + /// The identification text exactly as received. + pub raw: String, + pub vin: Option, + pub diag_address: Option, + pub mac: Option, +} + +/// Fields found in an identification string. Best effort, see the module docs. +pub fn parse_ident_string(s: &str) -> (Option, Option, Option) { + let s = s.trim_matches(|c: char| c == '\0' || c.is_whitespace()); + let between = |from: &str, to: Option<&str>| -> Option { + let start = s.find(from)? + from.len(); + let rest = &s[start..]; + let end = match to { + Some(t) => rest.find(t)?, + None => rest.len(), + }; + Some(rest[..end].trim().to_string()).filter(|v| !v.is_empty()) + }; + let addr = between("DIAGADR", Some("BMWMAC")) + .and_then(|h| u8::from_str_radix(h.trim_start_matches("0x"), 16).ok()); + let mac = between("BMWMAC", Some("BMWVIN")).map(|m| m.replace([':', '-'], "")); + let vin = between("BMWVIN", None); + (addr, mac, vin) +} + +/// Broadcast target for real use: every host on the local network, port 6811. +pub fn broadcast_target() -> SocketAddr { + SocketAddr::from(([255, 255, 255, 255], UDP_PORT)) +} + +/// Send a discovery request to `target` and collect every answer for `wait`. +pub fn discover(target: SocketAddr, wait: Duration) -> Result> { + let sock = UdpSocket::bind("0.0.0.0:0") + .map_err(|e| Error::Transport(format!("binding a UDP socket: {e}")))?; + sock.set_broadcast(true) + .map_err(|e| Error::Transport(format!("enabling broadcast: {e}")))?; + let request = HsfzFrame::new(CTRL_VEHICLE_IDENT, Vec::new()).encode(); + sock.send_to(&request, target) + .map_err(|e| Error::Transport(format!("sending discovery to {target}: {e}")))?; + + let deadline = Instant::now() + wait; + let mut found: Vec = Vec::new(); + let mut buf = [0u8; 2048]; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + break; + } + sock.set_read_timeout(Some(left.max(Duration::from_millis(1)))) + .map_err(|e| Error::Transport(format!("set_read_timeout: {e}")))?; + let (n, from) = match sock.recv_from(&mut buf) { + Ok(v) => v, + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => + { + break + } + Err(e) => return Err(Error::Transport(format!("receiving discovery: {e}"))), + }; + let mut datagram = buf[..n].to_vec(); + let Ok(Some(frame)) = take_frame(&mut datagram) else { + continue; // not HSFZ + }; + if frame.control != CTRL_VEHICLE_IDENT || frame.payload.is_empty() { + continue; // our own request echoed back, or something else + } + let raw = String::from_utf8_lossy(&frame.payload).into_owned(); + let (diag_address, mac, vin) = parse_ident_string(&raw); + let d = Discovered { + ip: from.ip(), + raw, + vin, + diag_address, + mac, + }; + if !found.contains(&d) { + found.push(d); + } + } + Ok(found) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_the_expected_layout() { + let (a, m, v) = parse_ident_string("DIAGADR10BMWMAC001A37B44210BMWVINWBASIMULATED00001"); + assert_eq!(a, Some(0x10)); + assert_eq!(m.as_deref(), Some("001A37B44210")); + assert_eq!(v.as_deref(), Some("WBASIMULATED00001")); + } + + #[test] + fn an_unexpected_layout_yields_nothing_rather_than_guesses() { + assert_eq!(parse_ident_string("hello world"), (None, None, None)); + } + + #[test] + fn tolerates_padding_and_mac_separators() { + let (a, m, v) = + parse_ident_string("DIAGADR0x1ABMWMAC00:1A:37:B4:42:10BMWVIN WBASIMULATED00001\0\0"); + assert_eq!(a, Some(0x1A)); + assert_eq!(m.as_deref(), Some("001A37B44210")); + assert_eq!(v.as_deref(), Some("WBASIMULATED00001")); + } +} diff --git a/crates/opendiag-bmw/src/gateway.rs b/crates/opendiag-bmw/src/gateway.rs new file mode 100644 index 0000000..9615140 --- /dev/null +++ b/crates/opendiag-bmw/src/gateway.rs @@ -0,0 +1,324 @@ +//! A TCP session to a BMW gateway, and per-ECU message links on top of it. +//! +//! One TCP connection serves every ECU behind the gateway: requests carry the +//! target address. [`HsfzGateway`] owns the connection; [`HsfzLink`] is a view +//! of it addressed to one ECU, and implements [`MessageLink`] so the shared +//! UDS client runs over it unchanged (there is no ISO-TP here: the gateway +//! carries whole UDS messages). +//! +//! The session is single-threaded request/response, like the rest of the +//! workspace. Keep-alive is therefore driven by the caller between requests +//! (`UdsClient::tester_present`, as `serve` does), not by a background thread: +//! a second thread could read another request's reply off the shared stream. + +use std::cell::RefCell; +use std::io::{ErrorKind, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::rc::Rc; +use std::time::Duration; + +use opendiag_core::{Error, Result, WriteMode}; +use opendiag_proto::clock::Clock; +use opendiag_proto::link::MessageLink; + +use crate::hsfz::{self, take_frame, HsfzFrame}; + +/// A byte stream with timed reads. `TcpByteStream` for real, scripted fakes in tests. +pub trait ByteStream { + fn write_all(&mut self, data: &[u8]) -> Result<()>; + /// Whatever bytes arrive within `timeout`; `Error::Timeout` if none. + fn read_some(&mut self, timeout: Duration) -> Result>; + /// Open the connection again after it dropped. Unsupported by default. + fn reconnect(&mut self) -> Result<()> { + Err(Error::Transport("this stream cannot reconnect".into())) + } +} + +/// [`ByteStream`] over TCP. +pub struct TcpByteStream { + addr: SocketAddr, + stream: TcpStream, +} + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); + +fn io_err(what: &str, e: std::io::Error) -> Error { + Error::Transport(format!("{what}: {e}")) +} + +impl TcpByteStream { + pub fn connect(addr: SocketAddr) -> Result { + Ok(Self { + addr, + stream: Self::open(addr)?, + }) + } + + fn open(addr: SocketAddr) -> Result { + let s = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) + .map_err(|e| io_err(&format!("connecting to {addr}"), e))?; + s.set_nodelay(true).map_err(|e| io_err("set_nodelay", e))?; + Ok(s) + } +} + +impl ByteStream for TcpByteStream { + fn write_all(&mut self, data: &[u8]) -> Result<()> { + self.stream + .write_all(data) + .map_err(|e| io_err("writing to the gateway", e)) + } + + fn read_some(&mut self, timeout: Duration) -> Result> { + // A zero timeout means "block forever" to the OS; never pass one. + let t = timeout.max(Duration::from_millis(1)); + self.stream + .set_read_timeout(Some(t)) + .map_err(|e| io_err("set_read_timeout", e))?; + let mut buf = [0u8; 4096]; + match self.stream.read(&mut buf) { + Ok(0) => Err(Error::Transport("the gateway closed the connection".into())), + Ok(n) => Ok(buf[..n].to_vec()), + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { + Err(Error::Timeout) + } + Err(e) => Err(io_err("reading from the gateway", e)), + } + } + + fn reconnect(&mut self) -> Result<()> { + self.stream = Self::open(self.addr)?; + Ok(()) + } +} + +struct Inner { + stream: S, + clock: C, + buf: Vec, + tester: u8, +} + +impl Inner { + /// Next complete frame within `timeout`. + fn next_frame(&mut self, timeout: Duration) -> Result { + let deadline = self.clock.now() + timeout; + loop { + if let Some(f) = take_frame(&mut self.buf)? { + return Ok(f); + } + let now = self.clock.now(); + if now >= deadline { + return Err(Error::Timeout); + } + let more = self.stream.read_some(deadline - now)?; + self.buf.extend_from_slice(&more); + } + } +} + +/// The connection to a gateway. Clone-free: make links with [`HsfzGateway::link`]. +pub struct HsfzGateway { + inner: Rc>>, +} + +impl HsfzGateway { + pub fn new(stream: S, clock: C, tester: u8) -> Self { + Self { + inner: Rc::new(RefCell::new(Inner { + stream, + clock, + buf: Vec::new(), + tester, + })), + } + } + + /// A message link to the ECU with diagnostic address `target`. + pub fn link(&self, target: u8) -> HsfzLink { + HsfzLink { + inner: Rc::clone(&self.inner), + target, + } + } + + /// Drop buffered bytes and reopen the connection. Any diagnostic session + /// state in the ECUs is the caller's to re-establish. + pub fn reconnect(&self) -> Result<()> { + let mut i = self.inner.borrow_mut(); + i.buf.clear(); + i.stream.reconnect() + } +} + +/// Services that start flashing or reprogramming. They are never sent, by +/// anything, at any write mode (CLAUDE.md ground rule 3). +fn forbidden(req: &[u8]) -> Option<&'static str> { + match req { + [0x10, sub, ..] if sub & 0x7F == 0x02 => Some("programming session (0x10 02)"), + [0x34..=0x38, ..] => Some("download/upload/transfer (flash) service"), + _ => None, + } +} + +/// Message link to one ECU behind the gateway. +pub struct HsfzLink { + inner: Rc>>, + target: u8, +} + +impl HsfzLink { + pub fn target(&self) -> u8 { + self.target + } +} + +impl MessageLink for HsfzLink { + fn send(&mut self, payload: &[u8]) -> Result<()> { + if let Some(what) = forbidden(payload) { + return Err(Error::WritesLocked(format!( + "{what} is never sent: OpenDiag does not flash or reprogram ECUs" + ))); + } + let mut i = self.inner.borrow_mut(); + let frame = HsfzFrame::diagnostic(i.tester, self.target, payload); + i.stream.write_all(&frame.encode()) + } + + fn recv(&mut self, timeout: Duration) -> Result> { + let mut i = self.inner.borrow_mut(); + let deadline = i.clock.now() + timeout; + loop { + let left = deadline.saturating_sub(i.clock.now()); + let frame = i.next_frame(left)?; + if let Some((src, dst, data)) = frame.as_diagnostic() { + if src == self.target && dst == i.tester { + return Ok(data.to_vec()); + } + continue; // another ECU's traffic + } + if let Some(name) = hsfz::error_name(frame.control) { + return Err(Error::Protocol(format!( + "hsfz: gateway reported `{name}` (control {:#06X}, payload {:02X?})", + frame.control, frame.payload + ))); + } + // Acknowledge, alive check, terminal 15, status, ident: not a reply to us. + } + } + + fn describe(&self) -> String { + format!("BMW ECU {:#04X} via HSFZ", self.target) + } +} + +/// Convenience: a read-only default, spelled out so callers need not import `WriteMode`. +pub const DEFAULT_WRITE_MODE: WriteMode = WriteMode::ReadOnly; + +#[cfg(test)] +mod tests { + use super::*; + use opendiag_proto::clock::FakeClock; + use std::collections::VecDeque; + + /// Feeds scripted chunks and records what was written. + struct Scripted { + incoming: VecDeque>, + written: Vec, + } + + impl Scripted { + fn new(chunks: Vec>) -> Self { + Self { + incoming: chunks.into(), + written: Vec::new(), + } + } + } + + impl ByteStream for Scripted { + fn write_all(&mut self, data: &[u8]) -> Result<()> { + self.written.extend_from_slice(data); + Ok(()) + } + fn read_some(&mut self, _t: Duration) -> Result> { + self.incoming.pop_front().ok_or(Error::Timeout) + } + } + + fn gw(chunks: Vec>) -> HsfzGateway { + HsfzGateway::new(Scripted::new(chunks), FakeClock::new(), 0xF4) + } + + #[test] + fn skips_acks_and_other_ecus_and_returns_the_reply() { + let ack = HsfzFrame::new(hsfz::CTRL_ACK, vec![0x12, 0xF4]).encode(); + let other = HsfzFrame::diagnostic(0x40, 0xF4, &[0x62, 1, 1, 1]).encode(); + let mine = HsfzFrame::diagnostic(0x12, 0xF4, &[0x62, 0xF1, 0x90, b'X']).encode(); + let g = gw(vec![[ack, other, mine].concat()]); + let mut link = g.link(0x12); + link.send(&[0x22, 0xF1, 0x90]).unwrap(); + assert_eq!( + link.recv(Duration::from_secs(1)).unwrap(), + [0x62, 0xF1, 0x90, b'X'] + ); + } + + #[test] + fn the_request_is_addressed_from_the_tester_to_the_ecu() { + let g = gw(vec![]); + let mut link = g.link(0x12); + link.send(&[0x3E, 0x00]).unwrap(); + let i = g.inner.borrow(); + assert_eq!(i.stream.written, [0, 0, 0, 4, 0, 1, 0xF4, 0x12, 0x3E, 0x00]); + } + + #[test] + fn silence_is_a_timeout() { + let g = gw(vec![]); + let mut link = g.link(0x10); + assert!(matches!( + link.recv(Duration::from_millis(100)), + Err(Error::Timeout) + )); + } + + #[test] + fn a_gateway_error_word_becomes_a_protocol_error() { + let e = HsfzFrame::new(0x43, vec![0x99]).encode(); + let g = gw(vec![e]); + let mut link = g.link(0x99); + let err = link.recv(Duration::from_secs(1)).unwrap_err().to_string(); + assert!(err.contains("incorrect destination address"), "{err}"); + } + + #[test] + fn flash_and_programming_requests_are_never_written() { + let g = gw(vec![]); + let mut link = g.link(0x12); + for req in [ + &[0x10u8, 0x02][..], + &[0x10, 0x82], + &[0x34, 0, 0], + &[0x36, 1], + &[0x37], + ] { + assert!( + matches!(link.send(req), Err(Error::WritesLocked(_))), + "{req:02X?}" + ); + } + assert!(g.inner.borrow().stream.written.is_empty()); + // The extended session is fine. + link.send(&[0x10, 0x03]).unwrap(); + } + + #[test] + fn a_frame_split_across_reads_is_reassembled() { + let f = HsfzFrame::diagnostic(0x12, 0xF4, &[0x62, 0xF1, 0x90, b'A', b'B']).encode(); + let (a, b) = f.split_at(4); + let g = gw(vec![a.to_vec(), b.to_vec()]); + let mut link = g.link(0x12); + assert_eq!(link.recv(Duration::from_secs(1)).unwrap().len(), 5); + } +} diff --git a/crates/opendiag-bmw/src/hsfz.rs b/crates/opendiag-bmw/src/hsfz.rs new file mode 100644 index 0000000..5e71dcd --- /dev/null +++ b/crates/opendiag-bmw/src/hsfz.rs @@ -0,0 +1,175 @@ +//! HSFZ ("High-Speed-Fahrzeug-Zugang") framing, BMW's diagnostic-over-IP protocol. +//! +//! Wire format (VERIFIED against the public Scapy `bmw/hsfz.py` dissector and +//! the Quantex HSFZ description, see `docs/sources.md`): +//! +//! ```text +//! +----------------+------------------+---------------------------+ +//! | length: u32 BE | control: u16 BE | payload (length bytes) | +//! +----------------+------------------+---------------------------+ +//! ``` +//! +//! `length` counts the payload only (not the 6-byte header). For a diagnostic +//! message (`0x0001`) the payload is `source, target, UDS data...`, so +//! `length = 2 + data.len()`. Addresses are one byte. +//! +//! NOT VERIFIED (flagged, see README): the exact layout of the acknowledge +//! (`0x0002`) payload beyond its two address bytes, and the reply an alive +//! check (`0x0012`) expects. This client therefore ignores both. + +use opendiag_core::{Error, Result}; + +/// TCP port of the gateway's diagnostic service. +pub const TCP_PORT: u16 = 6801; +/// UDP port used for vehicle discovery. +pub const UDP_PORT: u16 = 6811; +/// Usual tester address. +pub const DEFAULT_TESTER: u8 = 0xF4; +/// Usual gateway (ZGW) diagnostic address. Reported by discovery; this is only a fallback. +pub const DEFAULT_GATEWAY: u8 = 0x10; + +pub const HEADER_LEN: usize = 6; +/// Our own sanity limit, not a protocol value: a longer length field means the +/// stream is out of step (or not HSFZ), so we refuse rather than buffer it. +pub const MAX_PAYLOAD: usize = 0x1_0000; + +pub const CTRL_DIAGNOSTIC: u16 = 0x0001; +pub const CTRL_ACK: u16 = 0x0002; +pub const CTRL_TERMINAL15: u16 = 0x0010; +pub const CTRL_VEHICLE_IDENT: u16 = 0x0011; +pub const CTRL_ALIVE_CHECK: u16 = 0x0012; +pub const CTRL_STATUS_INQUIRY: u16 = 0x0013; + +/// Name of an error control word (`0x40..=0x45`, `0xFF`), or `None` for other words. +pub fn error_name(control: u16) -> Option<&'static str> { + Some(match control { + 0x0040 => "incorrect tester address", + 0x0041 => "incorrect control word", + 0x0042 => "incorrect format", + 0x0043 => "incorrect destination address", + 0x0044 => "message too large", + 0x0045 => "diagnostic application not ready", + 0x00FF => "out of memory", + _ => return None, + }) +} + +/// One HSFZ packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HsfzFrame { + pub control: u16, + pub payload: Vec, +} + +impl HsfzFrame { + pub fn new(control: u16, payload: Vec) -> Self { + Self { control, payload } + } + + /// A diagnostic message carrying one UDS request or response. + pub fn diagnostic(source: u8, target: u8, data: &[u8]) -> Self { + let mut payload = Vec::with_capacity(2 + data.len()); + payload.extend_from_slice(&[source, target]); + payload.extend_from_slice(data); + Self::new(CTRL_DIAGNOSTIC, payload) + } + + /// Encode header and payload. + pub fn encode(&self) -> Vec { + let mut out = Vec::with_capacity(HEADER_LEN + self.payload.len()); + out.extend_from_slice(&(self.payload.len() as u32).to_be_bytes()); + out.extend_from_slice(&self.control.to_be_bytes()); + out.extend_from_slice(&self.payload); + out + } + + /// `(source, target, data)` if this is a well-formed diagnostic message. + pub fn as_diagnostic(&self) -> Option<(u8, u8, &[u8])> { + match (self.control, self.payload.as_slice()) { + (CTRL_DIAGNOSTIC, [s, t, data @ ..]) => Some((*s, *t, data)), + _ => None, + } + } +} + +/// Take one complete frame off the front of `buf`, if there is one. +/// +/// Returns `Ok(None)` when more bytes are needed. A length beyond +/// [`MAX_PAYLOAD`] is an error: the stream cannot be trusted any more. +pub fn take_frame(buf: &mut Vec) -> Result> { + if buf.len() < HEADER_LEN { + return Ok(None); + } + let len = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; + if len > MAX_PAYLOAD { + return Err(Error::Protocol(format!( + "hsfz: implausible frame length {len}; the stream is out of step" + ))); + } + if buf.len() < HEADER_LEN + len { + return Ok(None); + } + let control = u16::from_be_bytes([buf[4], buf[5]]); + let payload = buf[HEADER_LEN..HEADER_LEN + len].to_vec(); + buf.drain(..HEADER_LEN + len); + Ok(Some(HsfzFrame { control, payload })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encodes_a_diagnostic_message() { + let f = HsfzFrame::diagnostic(0xF4, 0x10, &[0x22, 0xF1, 0x90]); + assert_eq!( + f.encode(), + [0, 0, 0, 5, 0, 1, 0xF4, 0x10, 0x22, 0xF1, 0x90], + "length counts source+target+data, not the header" + ); + } + + #[test] + fn decodes_across_split_reads_and_back_to_back_frames() { + let a = HsfzFrame::diagnostic(0x10, 0xF4, &[0x62, 0xF1, 0x90, b'W']).encode(); + let b = HsfzFrame::new(CTRL_ACK, vec![0x10, 0xF4]).encode(); + let mut all = a.clone(); + all.extend_from_slice(&b); + let mut buf = Vec::new(); + for chunk in all.chunks(3) { + buf.extend_from_slice(chunk); + } + let first = take_frame(&mut buf).unwrap().unwrap(); + assert_eq!(first.as_diagnostic().unwrap().2, [0x62, 0xF1, 0x90, b'W']); + let second = take_frame(&mut buf).unwrap().unwrap(); + assert_eq!(second.control, CTRL_ACK); + assert!(take_frame(&mut buf).unwrap().is_none()); + assert!(buf.is_empty()); + } + + #[test] + fn a_partial_frame_waits_for_more_bytes() { + let mut buf = HsfzFrame::diagnostic(1, 2, &[3, 4, 5]).encode(); + buf.truncate(buf.len() - 1); + assert!(take_frame(&mut buf).unwrap().is_none()); + assert_eq!(buf.len(), HEADER_LEN + 4, "nothing consumed"); + } + + #[test] + fn an_absurd_length_is_an_error_not_a_huge_buffer() { + let mut buf = vec![0xFF, 0xFF, 0xFF, 0xFF, 0, 1]; + assert!(take_frame(&mut buf).is_err()); + } + + #[test] + fn a_diagnostic_frame_too_short_for_addresses_is_not_diagnostic() { + let f = HsfzFrame::new(CTRL_DIAGNOSTIC, vec![0xF4]); + assert!(f.as_diagnostic().is_none()); + } + + #[test] + fn error_words_have_names() { + assert_eq!(error_name(0x43), Some("incorrect destination address")); + assert_eq!(error_name(CTRL_DIAGNOSTIC), None); + } +} diff --git a/crates/opendiag-bmw/src/ident.rs b/crates/opendiag-bmw/src/ident.rs new file mode 100644 index 0000000..b8598c1 --- /dev/null +++ b/crates/opendiag-bmw/src/ident.rs @@ -0,0 +1,62 @@ +//! Read-only vehicle identification: VIN, vehicle order (FA) and I-level. +//! +//! - VIN: DID `0xF190`, the standard ISO 14229 identifier. VERIFIED. +//! - I-level and FA: BMW-specific DIDs [`DID_I_LEVEL`] and [`DID_FA`]. +//! **NOT VERIFIED.** They are recalled from community tooling and could not +//! be confirmed from a public source. A wrong DID is harmless here (the ECU +//! answers "request out of range" and the item is reported as unavailable), +//! and `opendiag bmw did` lets you try others. Their contents are returned +//! as raw bytes; no decoding is attempted until a real capture exists. + +use opendiag_core::{Error, Result}; +use opendiag_proto::link::MessageLink; +use opendiag_proto::uds::UdsClient; + +pub const DID_VIN: u16 = 0xF190; +/// UNVERIFIED, see module docs. +pub const DID_I_LEVEL: u16 = 0x100B; +/// UNVERIFIED, see module docs. +pub const DID_FA: u16 = 0x3F06; + +/// What the gateway reported about the vehicle. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BmwIdent { + pub vin: Option, + /// Raw bytes of the I-level DID, if the ECU has it. + pub i_level_raw: Option>, + /// Raw bytes of the FA (vehicle order) DID, if the ECU has it. + pub fa_raw: Option>, +} + +impl BmwIdent { + /// I-level as text when the bytes are printable ASCII, else `None`. + pub fn i_level_text(&self) -> Option { + let raw = self.i_level_raw.as_ref()?; + let t: Vec = raw.iter().copied().filter(|b| *b != 0).collect(); + (!t.is_empty() && t.iter().all(|b| (0x20..0x7F).contains(b))) + .then(|| String::from_utf8_lossy(&t).into_owned()) + } +} + +/// Read one DID; `None` if the ECU says the identifier does not exist. +pub fn read_did(uds: &mut UdsClient, did: u16) -> Result>> { + match uds.read_data_by_identifier(did) { + Ok(d) => Ok(Some(d)), + Err(Error::NegativeResponse { nrc: 0x31, .. }) => Ok(None), + Err(e) => Err(e), + } +} + +/// Read VIN, I-level and FA. Reads only. +pub fn read_ident(uds: &mut UdsClient) -> Result { + let vin = read_did(uds, DID_VIN)?.map(|d| { + String::from_utf8_lossy(&d) + .trim_matches(|c: char| c == '\0' || c.is_whitespace()) + .to_string() + }); + Ok(BmwIdent { + vin, + i_level_raw: read_did(uds, DID_I_LEVEL)?, + fa_raw: read_did(uds, DID_FA)?, + }) +} diff --git a/crates/opendiag-bmw/src/lib.rs b/crates/opendiag-bmw/src/lib.rs new file mode 100644 index 0000000..0c4fa6f --- /dev/null +++ b/crates/opendiag-bmw/src/lib.rs @@ -0,0 +1,19 @@ +//! BMW F-series diagnostics over ENET (HSFZ). +//! +//! **Simulator-tested only.** Nothing here has run against a real car or +//! gateway. Items marked NOT VERIFIED in the module docs and the README are +//! recalled or inferred, not confirmed from a public source. +//! +//! Layers: [`hsfz`] (framing), [`gateway`] (TCP session and per-ECU links that +//! implement the shared `MessageLink`, so the VAG-proven UDS client is reused), +//! [`discovery`] (UDP), [`ident`] (read-only services), [`mock`] (virtual car). + +pub mod discovery; +pub mod gateway; +pub mod hsfz; +pub mod ident; +pub mod mock; + +pub use discovery::{broadcast_target, discover, Discovered}; +pub use gateway::{ByteStream, HsfzGateway, HsfzLink, TcpByteStream}; +pub use ident::{read_did, read_ident, BmwIdent}; diff --git a/crates/opendiag-bmw/src/mock.rs b/crates/opendiag-bmw/src/mock.rs new file mode 100644 index 0000000..acab294 --- /dev/null +++ b/crates/opendiag-bmw/src/mock.rs @@ -0,0 +1,298 @@ +//! A virtual BMW vehicle and an HSFZ gateway server for it, for tests and +//! `--simulate`. No car needed. +//! +//! [`VirtualVehicle`] answers UDS requests per ECU (pure, unit-testable); +//! [`MockGateway`] serves it over real localhost TCP (diagnostics) and UDP +//! (discovery) on background threads, so the real socket code is exercised. +//! +//! This encodes our reading of the protocol (see `hsfz.rs`), so a shared +//! misunderstanding would not be caught. It is not evidence about a real car. + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{ErrorKind, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; + +use crate::hsfz::{take_frame, HsfzFrame, CTRL_ACK, CTRL_VEHICLE_IDENT}; + +/// A request seen by the gateway: target address and UDS bytes. +pub type Request = (u8, Vec); +type RequestLog = Arc>>; + +/// One simulated ECU. +#[derive(Debug, Clone, Default)] +pub struct VirtualEcu { + pub address: u8, + pub dids: BTreeMap>, + /// Stored DTCs: 3-byte code and status byte. + pub dtcs: Vec<(u32, u8)>, + /// DIDs that first answer "response pending" (0x78) once. + pub slow_dids: BTreeSet, +} + +/// A simulated car: a gateway plus ECUs, all addressed through the gateway. +#[derive(Debug, Clone)] +pub struct VirtualVehicle { + pub vin: String, + pub mac: String, + pub gateway: u8, + pub ecus: Vec, +} + +impl VirtualVehicle { + /// A synthetic F-series-like car. Every value is invented for testing. + pub fn demo() -> Self { + let vin = "WBASIMULATED00001".to_string(); + let mut gw = VirtualEcu { + address: 0x10, + ..Default::default() + }; + gw.dids.insert(0xF190, vin.clone().into_bytes()); + gw.dids.insert(0x100B, b"F020-00-00-000".to_vec()); + gw.dids.insert(0x3F06, vec![0x01, 0x02, 0x03, 0x04]); + let mut dme = VirtualEcu { + address: 0x12, + dtcs: vec![(0x480A12, 0x09), (0x480B01, 0x24)], + ..Default::default() + }; + dme.dids.insert(0xF190, vin.clone().into_bytes()); + dme.slow_dids.insert(0x4001); + dme.dids.insert(0x4001, vec![0x12, 0x34]); + Self { + vin, + mac: "001A37B44210".into(), + gateway: 0x10, + ecus: vec![gw, dme], + } + } + + /// The identification string a gateway announces (layout unverified, see `discovery.rs`). + pub fn ident_string(&self) -> String { + format!( + "DIAGADR{:X}BMWMAC{}BMWVIN{}", + self.gateway, self.mac, self.vin + ) + } + + /// UDS replies to one request for `target`, in order; `None` if no such ECU. + pub fn respond(&mut self, target: u8, req: &[u8]) -> Option>> { + let ecu = self.ecus.iter_mut().find(|e| e.address == target)?; + let Some(&sid) = req.first() else { + return Some(vec![]); + }; + let nrc = |n: u8| vec![0x7F, sid, n]; + Some(match (sid, req) { + (0x10, [_, sub, ..]) => vec![vec![0x50, *sub, 0x00, 0x32, 0x01, 0xF4]], + (0x3E, [_, sub, ..]) => vec![vec![0x7E, *sub]], + (0x22, [_, hi, lo]) => { + let did = u16::from_be_bytes([*hi, *lo]); + match ecu.dids.get(&did) { + None => vec![nrc(0x31)], + Some(data) => { + let mut ok = vec![0x62, *hi, *lo]; + ok.extend_from_slice(data); + if ecu.slow_dids.remove(&did) { + vec![nrc(0x78), ok] + } else { + vec![ok] + } + } + } + } + (0x19, [_, 0x02, mask]) => { + let mut r = vec![0x59, 0x02, 0xFF]; + for (code, status) in ecu.dtcs.iter().filter(|(_, s)| s & mask != 0) { + let c = code.to_be_bytes(); + r.extend_from_slice(&[c[1], c[2], c[3], *status]); + } + vec![r] + } + (0x14, [_, a, b, c]) => { + if [*a, *b, *c] == [0xFF, 0xFF, 0xFF] { + ecu.dtcs.clear(); + vec![vec![0x54]] + } else { + vec![nrc(0x31)] + } + } + (0x19 | 0x22 | 0x14, _) => vec![nrc(0x13)], + _ => vec![nrc(0x11)], + }) + } +} + +/// A running mock gateway. Threads stop when this is dropped. +pub struct MockGateway { + tcp: SocketAddr, + udp: SocketAddr, + stop: Arc, + threads: Vec>, + /// Every UDS request received, as `(target, bytes)`, for assertions. + requests: RequestLog, +} + +const TICK: Duration = Duration::from_millis(20); + +impl MockGateway { + /// Serve `vehicle` on 127.0.0.1 with OS-chosen ports. + pub fn start(vehicle: VirtualVehicle) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0")?; + listener.set_nonblocking(true)?; + let tcp = listener.local_addr()?; + let udp_sock = UdpSocket::bind("127.0.0.1:0")?; + udp_sock.set_read_timeout(Some(TICK))?; + let udp = udp_sock.local_addr()?; + + let stop = Arc::new(AtomicBool::new(false)); + let requests = Arc::new(Mutex::new(Vec::new())); + let vehicle = Arc::new(Mutex::new(vehicle)); + let mut threads = Vec::new(); + + // Discovery responder. + { + let (stop, vehicle) = (stop.clone(), vehicle.clone()); + threads.push(thread::spawn(move || { + let mut buf = [0u8; 512]; + while !stop.load(Ordering::Relaxed) { + let Ok((n, from)) = udp_sock.recv_from(&mut buf) else { + continue; + }; + let mut d = buf[..n].to_vec(); + if let Ok(Some(f)) = take_frame(&mut d) { + if f.control == CTRL_VEHICLE_IDENT && f.payload.is_empty() { + let ident = vehicle.lock().unwrap().ident_string(); + let reply = + HsfzFrame::new(CTRL_VEHICLE_IDENT, ident.into_bytes()).encode(); + let _ = udp_sock.send_to(&reply, from); + } + } + } + })); + } + + // Diagnostic server: one thread accepts, one per connection serves. + { + let (stop, requests) = (stop.clone(), requests.clone()); + threads.push(thread::spawn(move || { + let mut conns: Vec> = Vec::new(); + while !stop.load(Ordering::Relaxed) { + match listener.accept() { + Ok((sock, _)) => { + let (stop, vehicle, requests) = + (stop.clone(), vehicle.clone(), requests.clone()); + conns.push(thread::spawn(move || { + serve(sock, &stop, &vehicle, &requests) + })); + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(TICK), + Err(_) => break, + } + } + for c in conns { + let _ = c.join(); + } + })); + } + + Ok(Self { + tcp, + udp, + stop, + threads, + requests, + }) + } + + /// Address of the diagnostic (TCP) service. + pub fn tcp_addr(&self) -> SocketAddr { + self.tcp + } + + /// Address of the discovery (UDP) responder. + pub fn udp_addr(&self) -> SocketAddr { + self.udp + } + + pub fn requests(&self) -> Vec<(u8, Vec)> { + self.requests.lock().unwrap().clone() + } +} + +impl Drop for MockGateway { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + for t in self.threads.drain(..) { + let _ = t.join(); + } + } +} + +fn serve( + mut sock: TcpStream, + stop: &AtomicBool, + vehicle: &Mutex, + requests: &Mutex>, +) { + let _ = sock.set_nonblocking(false); + let _ = sock.set_read_timeout(Some(TICK)); + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + while !stop.load(Ordering::Relaxed) { + match sock.read(&mut chunk) { + Ok(0) => return, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + Err(_) => return, + } + loop { + let frame = match take_frame(&mut buf) { + Ok(Some(f)) => f, + Ok(None) => break, + Err(_) => return, + }; + let Some((src, dst, data)) = frame.as_diagnostic() else { + let _ = sock.write_all(&HsfzFrame::new(0x41, vec![]).encode()); + continue; + }; + requests.lock().unwrap().push((dst, data.to_vec())); + let replies = vehicle.lock().unwrap().respond(dst, data); + let out = match replies { + None => HsfzFrame::new(0x43, vec![dst]).encode(), + Some(list) => { + let mut o = HsfzFrame::new(CTRL_ACK, vec![src, dst]).encode(); + for r in list { + o.extend(HsfzFrame::diagnostic(dst, src, &r).encode()); + } + o + } + }; + if sock.write_all(&out).is_err() { + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn answers_a_did_and_rejects_an_unknown_one() { + let mut v = VirtualVehicle::demo(); + let r = v.respond(0x10, &[0x22, 0xF1, 0x90]).unwrap(); + assert_eq!(&r[0][..3], [0x62, 0xF1, 0x90]); + assert_eq!( + v.respond(0x10, &[0x22, 0xAB, 0xCD]).unwrap()[0], + [0x7F, 0x22, 0x31] + ); + } + + #[test] + fn an_unknown_ecu_gets_no_replies() { + assert!(VirtualVehicle::demo().respond(0x99, &[0x3E, 0]).is_none()); + } +} diff --git a/crates/opendiag-bmw/tests/e2e.rs b/crates/opendiag-bmw/tests/e2e.rs new file mode 100644 index 0000000..5fb249f --- /dev/null +++ b/crates/opendiag-bmw/tests/e2e.rs @@ -0,0 +1,154 @@ +//! End-to-end over real localhost sockets against the mock gateway. +//! No car and no network beyond loopback. + +use std::time::Duration; + +use opendiag_bmw::mock::{MockGateway, VirtualVehicle}; +use opendiag_bmw::{discover, read_did, read_ident, HsfzGateway, HsfzLink, TcpByteStream}; +use opendiag_core::{Error, WriteMode}; +use opendiag_proto::clock::SystemClock; +use opendiag_proto::uds::{UdsClient, UdsConfig}; + +type Link = HsfzLink; + +fn setup() -> (MockGateway, HsfzGateway) { + let mock = MockGateway::start(VirtualVehicle::demo()).unwrap(); + let stream = TcpByteStream::connect(mock.tcp_addr()).unwrap(); + let gw = HsfzGateway::new(stream, SystemClock::new(), 0xF4); + (mock, gw) +} + +fn uds(gw: &HsfzGateway, ecu: u8) -> UdsClient { + UdsClient::new(gw.link(ecu), UdsConfig::default()) +} + +#[test] +fn discovery_finds_the_vehicle_and_parses_it() { + let mock = MockGateway::start(VirtualVehicle::demo()).unwrap(); + let found = discover(mock.udp_addr(), Duration::from_millis(400)).unwrap(); + assert_eq!(found.len(), 1); + let d = &found[0]; + assert_eq!(d.vin.as_deref(), Some("WBASIMULATED00001")); + assert_eq!(d.diag_address, Some(0x10)); + assert_eq!(d.mac.as_deref(), Some("001A37B44210")); + assert!(d.ip.is_loopback()); +} + +#[test] +fn discovery_with_no_answer_returns_nothing() { + // A bound-but-silent UDP socket stands in for an empty network. + let silent = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let found = discover(silent.local_addr().unwrap(), Duration::from_millis(150)).unwrap(); + assert!(found.is_empty()); +} + +#[test] +fn reads_vin_i_level_and_fa_from_the_gateway() { + let (_mock, gw) = setup(); + let id = read_ident(&mut uds(&gw, 0x10)).unwrap(); + assert_eq!(id.vin.as_deref(), Some("WBASIMULATED00001")); + assert_eq!(id.i_level_text().as_deref(), Some("F020-00-00-000")); + assert_eq!(id.fa_raw, Some(vec![1, 2, 3, 4])); +} + +#[test] +fn a_missing_did_is_reported_as_absent_not_an_error() { + let (_mock, gw) = setup(); + // ECU 0x12 has a VIN but no I-level / FA DIDs. + let id = read_ident(&mut uds(&gw, 0x12)).unwrap(); + assert!(id.vin.is_some()); + assert_eq!(id.i_level_raw, None); + assert_eq!(id.fa_raw, None); +} + +#[test] +fn response_pending_is_waited_out() { + let (mock, gw) = setup(); + let mut u = uds(&gw, 0x12); + assert_eq!(read_did(&mut u, 0x4001).unwrap(), Some(vec![0x12, 0x34])); + assert_eq!(mock.requests().len(), 1, "one request, two replies"); +} + +#[test] +fn two_ecus_share_one_connection() { + let (_mock, gw) = setup(); + let mut a = uds(&gw, 0x10); + let mut b = uds(&gw, 0x12); + assert!(read_did(&mut a, 0xF190).unwrap().is_some()); + assert!(read_did(&mut b, 0xF190).unwrap().is_some()); + assert!(read_did(&mut a, 0x100B).unwrap().is_some()); +} + +#[test] +fn reads_dtcs_with_status() { + let (_mock, gw) = setup(); + let dtcs = uds(&gw, 0x12).read_dtcs_by_status_mask(0xFF).unwrap(); + assert_eq!(dtcs.len(), 2); + assert_eq!(dtcs[0].code, 0x480A12); + assert_eq!(dtcs[0].status, 0x09); +} + +#[test] +fn an_unknown_ecu_is_a_clear_gateway_error() { + let (_mock, gw) = setup(); + let err = read_did(&mut uds(&gw, 0x99), 0xF190).unwrap_err(); + assert!( + err.to_string().contains("incorrect destination address"), + "{err}" + ); +} + +#[test] +fn a_negative_response_is_decoded() { + let (_mock, gw) = setup(); + let mut u = uds(&gw, 0x12); + let err = u.request(&[0x27, 0x01]).unwrap_err(); + assert!(matches!( + err, + Error::NegativeResponse { + service: 0x27, + nrc: 0x11 + } + )); +} + +#[test] +fn read_only_clients_cannot_clear_and_nothing_reaches_the_gateway() { + let (mock, gw) = setup(); + let mut u = uds(&gw, 0x12); + assert_eq!(u.write_mode(), WriteMode::ReadOnly); + assert!(matches!( + u.clear_dtcs(0xFF_FFFF), + Err(Error::WritesLocked(_)) + )); + assert!(mock.requests().is_empty()); +} + +#[test] +fn programming_session_is_refused_even_when_writes_are_unlocked() { + let (mock, gw) = setup(); + let mut u = uds(&gw, 0x12); + u.set_write_mode(WriteMode::Unlocked); + assert!(matches!( + u.session_control(0x02), + Err(Error::WritesLocked(_)) + )); + assert!(mock.requests().is_empty()); + // The extended session is allowed and answered. + u.session_control(0x03).unwrap(); +} + +#[test] +fn reconnecting_gives_a_working_session_again() { + let (_mock, gw) = setup(); + let mut u = uds(&gw, 0x10); + assert!(read_did(&mut u, 0xF190).unwrap().is_some()); + gw.reconnect().unwrap(); + assert!(read_did(&mut u, 0xF190).unwrap().is_some()); +} + +#[test] +fn tester_present_keeps_the_session_alive() { + let (_mock, gw) = setup(); + uds(&gw, 0x12).tester_present().unwrap(); +} diff --git a/crates/opendiag-cli/Cargo.toml b/crates/opendiag-cli/Cargo.toml index ab7ac29..c78cd76 100644 --- a/crates/opendiag-cli/Cargo.toml +++ b/crates/opendiag-cli/Cargo.toml @@ -12,6 +12,7 @@ name = "opendiag" path = "src/main.rs" [dependencies] +opendiag-bmw = { path = "../opendiag-bmw" } opendiag-core = { path = "../opendiag-core" } opendiag-data = { path = "../opendiag-data" } opendiag-proto = { path = "../opendiag-proto" } diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs new file mode 100644 index 0000000..7604045 --- /dev/null +++ b/crates/opendiag-cli/src/bmw.rs @@ -0,0 +1,217 @@ +//! `opendiag bmw ...`: BMW F-series over an ENET cable (HSFZ). Read-only. + +use std::net::{IpAddr, SocketAddr}; +use std::time::Duration; + +use clap::{Args, Subcommand}; +use opendiag_bmw::hsfz::{DEFAULT_GATEWAY, TCP_PORT}; +use opendiag_bmw::mock::{MockGateway, VirtualVehicle}; +use opendiag_bmw::{ + broadcast_target, discover, read_did, read_ident, Discovered, HsfzGateway, TcpByteStream, +}; +use opendiag_proto::clock::SystemClock; +use opendiag_proto::uds::{UdsClient, UdsConfig}; + +#[derive(Subcommand)] +pub enum BmwCmd { + /// Find BMW gateways on the network (UDP broadcast, port 6811). + Discover { + /// Send the request here instead of the broadcast address. + #[arg(long)] + to: Option, + /// How long to listen for answers, in milliseconds. + #[arg(long, default_value_t = 2000)] + wait_ms: u64, + /// Use the built-in virtual BMW (no car needed). + #[arg(long)] + simulate: bool, + }, + /// Read VIN, I-level and vehicle order (FA, raw) from the gateway. + Ident(Conn), + /// Read one data identifier from an ECU and print it as hex and text. + Did { + #[command(flatten)] + conn: Conn, + /// Data identifier in hex, e.g. 0xF190. + #[arg(value_parser = parse_hex_u16)] + did: u16, + }, +} + +#[derive(Args)] +pub struct Conn { + /// Gateway IP address (TCP 6801). Omit to discover it on the network. + #[arg(long)] + ip: Option, + /// Gateway TCP port. + #[arg(long, default_value_t = TCP_PORT)] + port: u16, + /// Use the built-in virtual BMW (no car needed). + #[arg(long)] + simulate: bool, + /// Diagnostic address of the ECU to talk to, in hex (default: the gateway). + #[arg(long, value_parser = crate::parse_hex_u8)] + target: Option, + /// Tester address, in hex. + #[arg(long, default_value = "0xF4", value_parser = crate::parse_hex_u8)] + tester: u8, +} + +fn parse_hex_u16(s: &str) -> Result { + u16::from_str_radix(s.trim_start_matches("0x").trim_start_matches("0X"), 16) + .map_err(|e| e.to_string()) +} + +const NOTICE: &str = + "BMW support is simulator-tested only: it has not been run against a real car. \ +It only reads. Keep the ignition on and a battery charger connected."; + +pub fn run(cmd: BmwCmd) -> Result<(), String> { + match cmd { + BmwCmd::Discover { + to, + wait_ms, + simulate, + } => discover_cmd(to, wait_ms, simulate), + BmwCmd::Ident(c) => ident_cmd(&c), + BmwCmd::Did { conn, did } => did_cmd(&conn, did), + } +} + +fn print_found(found: &[Discovered]) { + for d in found { + println!("gateway {}", d.ip); + println!( + " VIN: {}", + d.vin.as_deref().unwrap_or("(not parsed)") + ); + match d.diag_address { + Some(a) => println!(" diag addr: {a:#04X}"), + None => println!(" diag addr: (not parsed)"), + } + println!( + " MAC: {}", + d.mac.as_deref().unwrap_or("(not parsed)") + ); + if d.vin.is_none() && d.diag_address.is_none() && d.mac.is_none() { + println!(" raw reply: {:?}", d.raw); + } + } +} + +fn discover_cmd(to: Option, wait_ms: u64, simulate: bool) -> Result<(), String> { + let _mock; + let target = if simulate { + eprintln!("[simulated] virtual BMW gateway"); + let m = MockGateway::start(VirtualVehicle::demo()).map_err(|e| e.to_string())?; + let t = m.udp_addr(); + _mock = Some(m); + t + } else { + _mock = None; + to.unwrap_or_else(broadcast_target) + }; + let found = discover(target, Duration::from_millis(wait_ms)).map_err(|e| e.to_string())?; + if found.is_empty() { + println!("No gateway answered. Check the ENET cable, that the ignition is on, and that"); + println!("your network adapter is on the same link-local network (169.254.x.x)."); + } else { + print_found(&found); + } + Ok(()) +} + +struct Session { + gateway: HsfzGateway, + target: u8, + _mock: Option, +} + +fn connect(c: &Conn) -> Result { + let mut discovered_addr = None; + let (addr, mock) = if c.simulate { + eprintln!("[simulated] virtual BMW gateway"); + let m = MockGateway::start(VirtualVehicle::demo()).map_err(|e| e.to_string())?; + (m.tcp_addr(), Some(m)) + } else { + eprintln!("{NOTICE}"); + let ip = match c.ip { + Some(ip) => ip, + None => { + eprintln!("Looking for a gateway on the network..."); + let found = discover(broadcast_target(), Duration::from_secs(2)) + .map_err(|e| e.to_string())?; + match found.as_slice() { + [] => return Err("no gateway answered; pass --ip if you know it".into()), + [one] => { + discovered_addr = one.diag_address; + one.ip + } + many => { + print_found(many); + return Err("several gateways answered; pick one with --ip".into()); + } + } + } + }; + (SocketAddr::new(ip, c.port), None) + }; + let stream = TcpByteStream::connect(addr).map_err(|e| e.to_string())?; + Ok(Session { + gateway: HsfzGateway::new(stream, SystemClock::new(), c.tester), + target: c.target.or(discovered_addr).unwrap_or(DEFAULT_GATEWAY), + _mock: mock, + }) +} + +fn hex(b: &[u8]) -> String { + b.iter() + .map(|x| format!("{x:02X}")) + .collect::>() + .join(" ") +} + +fn ident_cmd(c: &Conn) -> Result<(), String> { + let s = connect(c)?; + let mut uds = UdsClient::new(s.gateway.link(s.target), UdsConfig::default()); + let id = read_ident(&mut uds).map_err(|e| e.to_string())?; + println!("ECU {:#04X}", s.target); + println!( + " VIN: {}", + id.vin.as_deref().unwrap_or("(not available)") + ); + match (&id.i_level_raw, id.i_level_text()) { + (_, Some(t)) => println!(" I-level: {t}"), + (Some(raw), None) => println!(" I-level: raw {}", hex(raw)), + (None, _) => println!(" I-level: (not available)"), + } + match &id.fa_raw { + Some(raw) => println!(" FA (raw): {} (not decoded)", hex(raw)), + None => println!(" FA: (not available)"), + } + println!("The I-level and FA data identifiers are unverified guesses (docs/bmw.md)."); + Ok(()) +} + +fn did_cmd(c: &Conn, did: u16) -> Result<(), String> { + let s = connect(c)?; + let mut uds = UdsClient::new(s.gateway.link(s.target), UdsConfig::default()); + match read_did(&mut uds, did).map_err(|e| e.to_string())? { + None => println!("ECU {:#04X} does not have DID {did:#06X}", s.target), + Some(d) => { + println!("ECU {:#04X} DID {did:#06X}: {}", s.target, hex(&d)); + let text: String = d + .iter() + .map(|b| { + if (0x20..0x7F).contains(b) { + *b as char + } else { + '.' + } + }) + .collect(); + println!("text: {text}"); + } + } + Ok(()) +} diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index e1f7afb..3747b9e 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -1,3 +1,5 @@ +mod bmw; + use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; @@ -36,6 +38,11 @@ struct Cli { #[derive(Subcommand)] enum Cmd { + /// BMW F-series over an ENET cable (HSFZ). Read-only; simulator-tested only. + Bmw { + #[command(subcommand)] + action: bmw::BmwCmd, + }, /// Identify the module (part number, software version, VIN). Scan(Target), /// Read or clear diagnostic trouble codes. @@ -310,6 +317,7 @@ fn main() -> ExitCode { ); Ok(()) } + Some(Cmd::Bmw { action }) => bmw::run(action), Some(Cmd::Scan(t)) => scan(&t), Some(Cmd::Dtc { action: DtcCmd::Read(t), diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index c3bc919..765a41c 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1160,3 +1160,33 @@ fn doctor_prints_a_summary_and_writes_it_to_a_file_without_a_vin() { // The summary is for sharing: it must not contain identification from modules. assert!(!stdout.contains("DEMO-KW-0001") && !stdout.contains("VIRTUAL ENGINE ECU")); } + +#[test] +fn bmw_simulated_discovery_lists_the_virtual_car() { + let (ok, out, err) = run(&["bmw", "discover", "--simulate", "--wait-ms", "400"], ""); + assert!(ok, "{err}"); + assert!(out.contains("WBASIMULATED00001"), "{out}"); + assert!(out.contains("0x10"), "{out}"); +} + +#[test] +fn bmw_simulated_ident_reads_vin_and_flags_unverified_items() { + let (ok, out, err) = run(&["bmw", "ident", "--simulate"], ""); + assert!(ok, "{err}"); + assert!(out.contains("WBASIMULATED00001"), "{out}"); + assert!(out.contains("F020-00-00-000"), "{out}"); + assert!(out.contains("unverified"), "{out}"); +} + +#[test] +fn bmw_simulated_did_read_and_missing_did() { + let (ok, out, _) = run( + &["bmw", "did", "--simulate", "--target", "0x12", "0xF190"], + "", + ); + assert!(ok); + assert!(out.contains("57 42 41"), "{out}"); + let (ok, out, _) = run(&["bmw", "did", "--simulate", "0xABCD"], ""); + assert!(ok); + assert!(out.contains("does not have DID"), "{out}"); +} diff --git a/docs/bmw.md b/docs/bmw.md new file mode 100644 index 0000000..499929f --- /dev/null +++ b/docs/bmw.md @@ -0,0 +1,49 @@ +# BMW F-series (ENET / HSFZ) + +**Status: simulator-tested only.** None of this has run against a real car, gateway or ENET cable. Read-only. + +```bash +opendiag bmw discover # find gateways (UDP broadcast, port 6811) +opendiag bmw ident [--ip 169.254.x.x] # VIN, I-level, FA (raw) from the gateway +opendiag bmw did --target 0x12 0xF190 # read one data identifier from one ECU +opendiag bmw ident --simulate # no car: built-in virtual BMW +``` + +Before connecting to a real car: ignition on, a battery charger connected. The ENET cable needs the car's +activation line (OBD pin 8) wired; a plain Ethernet cable will not wake the gateway. + +## How it is built + +`opendiag-bmw` speaks HSFZ over TCP and plugs into the shared UDS client through the `MessageLink` trait +(`opendiag-proto`). There is no ISO-TP: the gateway carries whole UDS messages. One TCP connection serves every +ECU behind the gateway; each ECU gets an `HsfzLink` addressed by its diagnostic address. + +Keep-alive is driven by the caller between requests (`tester_present`), not by a background thread, because a +second thread could read another request's reply off the shared stream. If the gateway drops the connection, +`HsfzGateway::reconnect` reopens it; ECU session state must then be re-established by the caller. + +Safety: the link refuses programming sessions (`0x10 02`) and download/transfer services (`0x34`-`0x38`) at any +write mode. Clearing DTCs and writes are not wired to the CLI yet. + +## Verified vs unverified + +Verified against public sources (see [sources.md](sources.md)): + +- TCP port 6801 for diagnostics, UDP port 6811 for discovery. +- Frame: 4-byte big-endian length (payload only), 2-byte control word, payload. A diagnostic message (`0x0001`) + payload is `source, target, UDS data`, one byte each address. No routing activation (unlike DoIP). +- Control words: `0x01` diagnostic, `0x02` acknowledge, `0x10` terminal 15, `0x11` vehicle ident, + `0x12` alive check, `0x13` status inquiry, `0x40`-`0x45` and `0xFF` errors. +- Default tester address `0xF4`. +- VIN is UDS DID `0xF190` (ISO 14229). + +**NOT verified.** These are flagged in the code and must be checked on a real car: + +- The exact ASCII layout of the discovery reply (`DIAGADR..BMWMAC..BMWVIN..`). Unparseable replies are shown raw. +- That the discovery *request* is a `0x0011` frame with an empty payload (inferred from the Scapy dissector). +- The acknowledge (`0x0002`) payload beyond its two address bytes, and what an alive check (`0x0012`) expects as + a reply. This client ignores both and relies on UDS TesterPresent. +- The I-level DID (`0x100B`) and FA DID (`0x3F06`), and how to decode them. Output is raw bytes. A wrong DID + just yields "not available". +- Whether an F30 needs ReadDTCInformation sub-functions other than `0x02`. +- The gateway's diagnostic address (`0x10` is the usual one and is taken from discovery when available). diff --git a/docs/legal.md b/docs/legal.md index 5482e09..2e2a198 100644 --- a/docs/legal.md +++ b/docs/legal.md @@ -12,4 +12,6 @@ Contributors may: - contribute data they captured themselves from their own vehicles, with a `captured_on` provenance field; - write original descriptions of modules, DTCs and measuring blocks. +BMW: OpenDiag will never bundle, commit or redistribute BMW proprietary data (PSdZData, CAFD files, SGBD/PRG files, ISTA content). Any future decoding of such files reads them from a path the user supplies on their own machine, and stays out of `data/` and the CC0 data set. + If you have seen proprietary label data and are unsure whether your contribution is affected, say so in the PR and a maintainer will advise. diff --git a/docs/sources.md b/docs/sources.md index 3b5b0e9..f4b77ab 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -15,3 +15,8 @@ Every piece of protocol knowledge must be traceable to a public source listed he | ELM327 AT commands | ELM327 data sheet (ELM Electronics), from general knowledge of the command set; **not re-read against the data sheet when written** | Commands used: ATZ, ATE0, ATL0, ATS0, ATH1, ATCAF0, ATSP6, ATST, ATCRA, ATSH; the `>` prompt, `NO DATA` and the error lines. The software emulator in `opendiag-transport` encodes this same reading, so it cannot catch a shared mistake. | Do not cite or derive from Ross-Tech label files, VCDS or ODIS. + +## BMW HSFZ (ENET) + +- Scapy `scapy/contrib/automotive/bmw/hsfz.py` (GPL-2.0-only): frame layout, control words, ports. Read for protocol facts only; no code copied. +- Quantex "ELM327 BMW HSFZ" page (quantexlab.com/en/develop/elm327_hsfz.html): ports, 1-byte addressing, default tester `F4`, discovery by UDP broadcast, no routing activation. From b8d342780f22ffdb3e0a657522f1342455ad7fce Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:46:23 +0000 Subject: [PATCH 3/9] feat(bmw): ECU scan, DTC read and guarded clear, raw DID live logging - scan: probe addresses with TesterPresent, count fault codes (read-only) - BmwEcu implements FaultAccess/Module: raw hex DTCs, clear through the existing plan_clear/apply_clear flow (snapshot, typed YES, re-read) - clear over HSFZ added to write_safety.rs under corrupted bytes - live: log DIDs as raw hex CSV on a fixed grid - small unverified ECU address table (labels only) - mock: more ECUs, in-memory LoopbackStream - CLI: opendiag bmw scan | dtc read|clear | live Simulator-tested only; never run against a real car. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 2 + PROJECT_PLAN.md | 2 +- README.md | 2 +- crates/opendiag-bmw/Cargo.toml | 1 + crates/opendiag-bmw/src/ecu.rs | 115 ++++++++++ crates/opendiag-bmw/src/ecus.rs | 57 +++++ crates/opendiag-bmw/src/lib.rs | 10 +- crates/opendiag-bmw/src/live.rs | 77 +++++++ crates/opendiag-bmw/src/mock.rs | 119 ++++++++-- crates/opendiag-bmw/src/scan.rs | 66 ++++++ crates/opendiag-bmw/tests/e2e.rs | 151 +++++++++++- crates/opendiag-cli/src/bmw.rs | 216 +++++++++++++++++- crates/opendiag-cli/tests/cli.rs | 98 ++++++++ crates/opendiag-services/Cargo.toml | 4 + .../opendiag-services/tests/write_safety.rs | 57 ++++- docs/bmw.md | 32 ++- 16 files changed, 981 insertions(+), 28 deletions(-) create mode 100644 crates/opendiag-bmw/src/ecu.rs create mode 100644 crates/opendiag-bmw/src/ecus.rs create mode 100644 crates/opendiag-bmw/src/live.rs create mode 100644 crates/opendiag-bmw/src/scan.rs diff --git a/Cargo.lock b/Cargo.lock index 737e8fe..c68cb1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,6 +368,7 @@ version = "0.1.0" dependencies = [ "opendiag-core", "opendiag-proto", + "opendiag-services", ] [[package]] @@ -413,6 +414,7 @@ dependencies = [ name = "opendiag-services" version = "0.1.0" dependencies = [ + "opendiag-bmw", "opendiag-core", "opendiag-proto", "opendiag-transport", diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md index 429a895..e09385d 100644 --- a/PROJECT_PLAN.md +++ b/PROJECT_PLAN.md @@ -105,7 +105,7 @@ Key design points: ### Phase B - BMW F-series over ENET (branch `feat/bmw-backend`) -Status: step 1 (read-only) done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Next: ECU scan, DTC read/clear (existing guarded flow), live data by DID, ECU address table; then backup + coding (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). +Status: steps 1 and 2 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Next: backup + coding (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). ## 5. Repo layout diff --git a/README.md b/README.md index 05f4684..aa05485 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ An open source, cross-platform diagnostic suite for VAG group vehicles (VW, Audi | Transports | Serial K-line (Windows/Linux/macOS), SocketCAN (Linux), ELM327-style adapters (degraded, UDS over 11-bit CAN), Simulator, Replay | | Modules | `scan` and `dtc read/clear` work on KW1281 (`--slow-init`), KWP2000 on K-line (`--fast-init`) and KWP2000 over TP2.0 on CAN (`--can`, Linux); live data and adaptation are KW1281 only | | CLI | `scan`, `dtc read/clear`, `report` (standalone HTML), `serve` (read-only local web page), `doctor` (support summary), `log` (live data to CSV), `adaptation read/set`, `backup list/restore`, `probe`, `ports`, `capture`, `--trace` on all hardware commands, `data validate/schema` | -| BMW (F-series, ENET) | **Experimental, simulator-tested only, never run on a real car.** `opendiag bmw discover/ident/did`: HSFZ over TCP, UDP discovery, VIN / I-level / FA reads, read-only. Unverified protocol details are listed in [docs/bmw.md](docs/bmw.md) | +| BMW (F-series, ENET) | **Experimental, simulator-tested only, never run on a real car.** `opendiag bmw discover/ident/did/scan/dtc/live`: HSFZ over TCP, UDP discovery, VIN / I-level / FA reads, ECU scan, fault codes (read, and guarded clear), raw DID logging. Unverified protocol details are listed in [docs/bmw.md](docs/bmw.md) | | Data | Open YAML format with validator and generated JSON Schema (CC0-1.0) | ## Install diff --git a/crates/opendiag-bmw/Cargo.toml b/crates/opendiag-bmw/Cargo.toml index 68e2a9f..57a1823 100644 --- a/crates/opendiag-bmw/Cargo.toml +++ b/crates/opendiag-bmw/Cargo.toml @@ -10,6 +10,7 @@ repository.workspace = true [dependencies] opendiag-core = { path = "../opendiag-core" } opendiag-proto = { path = "../opendiag-proto" } +opendiag-services = { path = "../opendiag-services" } [lints] workspace = true diff --git a/crates/opendiag-bmw/src/ecu.rs b/crates/opendiag-bmw/src/ecu.rs new file mode 100644 index 0000000..2d2b6c2 --- /dev/null +++ b/crates/opendiag-bmw/src/ecu.rs @@ -0,0 +1,115 @@ +//! One BMW ECU as a [`Module`] / [`FaultAccess`], so the existing guarded +//! clear flow (`plan_clear` / `apply_clear`: confirmation bound to the codes, +//! re-read, flushed snapshot, clear, re-read) works for BMW unchanged. +//! +//! DTCs are shown as the raw 3-byte hex code (e.g. `480A12`), not as SAE +//! letters: BMW codes are not SAE J2012 codes, so inventing `P`/`B`/`C`/`U` +//! text would be wrong. +//! +//! Reading uses ReadDTCInformation 0x19 02 with mask 0xFF and clearing uses +//! ClearDiagnosticInformation 0x14 FFFFFF, both generic ISO 14229. Whether an +//! F-series ECU wants a different session first is NOT VERIFIED. + +use opendiag_core::{Result, WriteMode}; +use opendiag_proto::link::MessageLink; +use opendiag_proto::uds::{UdsClient, UdsConfig}; +use opendiag_services::{ + identify, status_flags, DtcReport, FaultAccess, Ident, Module, WriteToken, +}; + +/// Raw hex form of a BMW DTC. +pub fn format_bmw_dtc(code: u32) -> String { + format!("{:06X}", code & 0xFF_FFFF) +} + +pub struct BmwEcu { + uds: UdsClient, + address: u8, +} + +impl BmwEcu { + pub fn new(link: L, address: u8, cfg: UdsConfig) -> Self { + Self { + uds: UdsClient::new(link, cfg), + address, + } + } + + pub fn address(&self) -> u8 { + self.address + } + + /// The underlying UDS client, for DID reads and other read-only requests. + pub fn uds(&mut self) -> &mut UdsClient { + &mut self.uds + } +} + +impl FaultAccess for BmwEcu { + fn protocol(&self) -> &'static str { + "hsfz-uds" + } + + fn module_address(&self) -> u8 { + self.address + } + + fn describe(&self) -> String { + match crate::ecus::name(self.address) { + Some(n) => format!("BMW ECU {:#04X} ({n}) via HSFZ", self.address), + None => format!("BMW ECU {:#04X} via HSFZ", self.address), + } + } + + fn read(&mut self) -> Result> { + Ok(self + .uds + .read_dtcs_by_status_mask(0xFF)? + .into_iter() + .map(|d| DtcReport { + code: d.code, + text: format_bmw_dtc(d.code), + status: d.status, + flags: status_flags(d.status), + }) + .collect()) + } + + fn clear(&mut self, _token: &WriteToken) -> Result<()> { + // Unlock only for this one request, and put the mode back whatever happens. + let previous = self.uds.write_mode(); + self.uds.set_write_mode(WriteMode::Unlocked); + let result = self.uds.clear_dtcs(0xFF_FFFF); + self.uds.set_write_mode(previous); + result + } +} + +impl Module for BmwEcu { + fn identify(&mut self) -> Result { + identify(&mut self.uds) + } + + fn read_dtcs(&mut self) -> Result> { + self.read() + } + + fn faults(&mut self) -> &mut dyn FaultAccess { + self + } + + fn keep_alive(&mut self) -> Result<()> { + self.uds.tester_present() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dtcs_are_six_hex_digits() { + assert_eq!(format_bmw_dtc(0x480A12), "480A12"); + assert_eq!(format_bmw_dtc(0x000012), "000012"); + } +} diff --git a/crates/opendiag-bmw/src/ecus.rs b/crates/opendiag-bmw/src/ecus.rs new file mode 100644 index 0000000..c2732d1 --- /dev/null +++ b/crates/opendiag-bmw/src/ecus.rs @@ -0,0 +1,57 @@ +//! BMW diagnostic addresses and names. +//! +//! **NOT VERIFIED.** This is our own short list, written from general +//! community knowledge of F-series layouts, with no public specification +//! behind it. Names are labels for display only: the scan finds ECUs by +//! asking, not by trusting this table, and a wrong or missing name never +//! changes what is sent. Extend it from your own car's scan results. +//! +//! The table is deliberately small and is not derived from any BMW data +//! file (see `docs/legal.md`). + +/// `(diagnostic address, short name, description)`. +pub const KNOWN_ECUS: &[(u8, &str, &str)] = &[ + (0x10, "ZGW", "central gateway"), + (0x12, "DME", "engine control"), + (0x18, "EGS", "transmission control"), + (0x29, "DSC", "stability control / ABS"), + (0x40, "CAS", "access / start system"), + (0x60, "KOMBI", "instrument cluster"), +]; + +/// Short name for an address, if it is in the table. +pub fn name(address: u8) -> Option<&'static str> { + KNOWN_ECUS + .iter() + .find(|(a, _, _)| *a == address) + .map(|(_, n, _)| *n) +} + +/// Description for an address, if it is in the table. +pub fn description(address: u8) -> Option<&'static str> { + KNOWN_ECUS + .iter() + .find(|(a, _, _)| *a == address) + .map(|(_, _, d)| *d) +} + +/// The addresses a default scan probes. +pub fn known_addresses() -> Vec { + KNOWN_ECUS.iter().map(|(a, _, _)| *a).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn addresses_are_unique_and_lookup_works() { + let mut a = known_addresses(); + a.sort_unstable(); + a.dedup(); + assert_eq!(a.len(), KNOWN_ECUS.len()); + assert_eq!(name(0x12), Some("DME")); + assert_eq!(name(0xEE), None); + assert_eq!(description(0x10), Some("central gateway")); + } +} diff --git a/crates/opendiag-bmw/src/lib.rs b/crates/opendiag-bmw/src/lib.rs index 0c4fa6f..120b756 100644 --- a/crates/opendiag-bmw/src/lib.rs +++ b/crates/opendiag-bmw/src/lib.rs @@ -6,14 +6,22 @@ //! //! Layers: [`hsfz`] (framing), [`gateway`] (TCP session and per-ECU links that //! implement the shared `MessageLink`, so the VAG-proven UDS client is reused), -//! [`discovery`] (UDP), [`ident`] (read-only services), [`mock`] (virtual car). +//! [`discovery`] (UDP), [`ident`], [`scan`], [`live`] (read-only services), [`ecu`] (DTC read and the +//! guarded clear, via `opendiag-services`), [`mock`] (virtual car). pub mod discovery; +pub mod ecu; +pub mod ecus; pub mod gateway; pub mod hsfz; pub mod ident; +pub mod live; pub mod mock; +pub mod scan; pub use discovery::{broadcast_target, discover, Discovered}; +pub use ecu::{format_bmw_dtc, BmwEcu}; 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}; diff --git a/crates/opendiag-bmw/src/live.rs b/crates/opendiag-bmw/src/live.rs new file mode 100644 index 0000000..2a0cf82 --- /dev/null +++ b/crates/opendiag-bmw/src/live.rs @@ -0,0 +1,77 @@ +//! Live data by data identifier: read a list of DIDs at a steady rate and log +//! them as CSV. Values are logged raw (hex). Turning them into engineering +//! units needs per-DID definitions we do not have verified, so none are guessed. +//! +//! Read-only: only ReadDataByIdentifier is sent. + +use std::io::Write; +use std::time::Duration; + +use opendiag_core::{Error, Result}; +use opendiag_proto::clock::Clock; +use opendiag_proto::link::MessageLink; +use opendiag_proto::uds::UdsClient; + +pub const CSV_HEADER: &str = "time_ms,did,status,hex"; + +#[derive(Debug, Clone)] +pub struct DidLogConfig { + pub dids: Vec, + /// Time between the start of one round and the next. + pub interval: Duration, + pub samples: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DidLogSummary { + pub samples: u32, + pub rows: u64, +} + +fn io_err(e: std::io::Error) -> Error { + Error::Io(e.to_string()) +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02X}")).collect() +} + +/// Log `cfg.dids` to `out`. Rounds start on a fixed grid so timestamps do not +/// drift; output is flushed after every round, so a failure part-way through +/// keeps the earlier rows. An ECU that says a DID does not exist, or refuses +/// it, gets a row saying so; a lost connection or timeout stops the log. +pub fn log_dids_csv( + uds: &mut UdsClient, + clock: &C, + cfg: &DidLogConfig, + out: &mut W, +) -> Result { + writeln!(out, "{CSV_HEADER}").map_err(io_err)?; + let start = clock.now(); + let mut rows = 0u64; + let mut samples = 0u32; + for round in 0..cfg.samples { + clock.wait_until(start + cfg.interval * round); + let ms = clock.now().saturating_sub(start).as_millis(); + for &did in &cfg.dids { + match uds.read_data_by_identifier(did) { + Ok(d) => writeln!(out, "{ms},{did:#06X},ok,{}", hex(&d)), + Err(Error::NegativeResponse { nrc: 0x31, .. }) => { + writeln!(out, "{ms},{did:#06X},absent,") + } + Err(Error::NegativeResponse { nrc, .. }) => { + writeln!(out, "{ms},{did:#06X},nrc_{nrc:#04X},") + } + Err(e) => { + let _ = out.flush(); + return Err(e); + } + } + .map_err(io_err)?; + rows += 1; + } + out.flush().map_err(io_err)?; + samples += 1; + } + Ok(DidLogSummary { samples, rows }) +} diff --git a/crates/opendiag-bmw/src/mock.rs b/crates/opendiag-bmw/src/mock.rs index acab294..759d385 100644 --- a/crates/opendiag-bmw/src/mock.rs +++ b/crates/opendiag-bmw/src/mock.rs @@ -8,7 +8,7 @@ //! This encodes our reading of the protocol (see `hsfz.rs`), so a shared //! misunderstanding would not be caught. It is not evidence about a real car. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::{ErrorKind, Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -16,10 +16,14 @@ use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; +use opendiag_core::{Error, Result}; + +use crate::gateway::ByteStream; use crate::hsfz::{take_frame, HsfzFrame, CTRL_ACK, CTRL_VEHICLE_IDENT}; /// A request seen by the gateway: target address and UDS bytes. pub type Request = (u8, Vec); +type WriteHook = Box; type RequestLog = Arc>>; /// One simulated ECU. @@ -61,11 +65,23 @@ impl VirtualVehicle { dme.dids.insert(0xF190, vin.clone().into_bytes()); dme.slow_dids.insert(0x4001); dme.dids.insert(0x4001, vec![0x12, 0x34]); + dme.dids.insert(0x4002, vec![0x0B, 0xB8]); + let mut egs = VirtualEcu { + address: 0x18, + ..Default::default() + }; + egs.dids.insert(0xF190, vin.clone().into_bytes()); + let mut kombi = VirtualEcu { + address: 0x60, + dtcs: vec![(0x930001, 0x2F)], + ..Default::default() + }; + kombi.dids.insert(0xF190, vin.clone().into_bytes()); Self { vin, mac: "001A37B44210".into(), gateway: 0x10, - ecus: vec![gw, dme], + ecus: vec![gw, dme, egs, kombi], } } @@ -253,22 +269,10 @@ fn serve( Ok(None) => break, Err(_) => return, }; - let Some((src, dst, data)) = frame.as_diagnostic() else { - let _ = sock.write_all(&HsfzFrame::new(0x41, vec![]).encode()); - continue; - }; - requests.lock().unwrap().push((dst, data.to_vec())); - let replies = vehicle.lock().unwrap().respond(dst, data); - let out = match replies { - None => HsfzFrame::new(0x43, vec![dst]).encode(), - Some(list) => { - let mut o = HsfzFrame::new(CTRL_ACK, vec![src, dst]).encode(); - for r in list { - o.extend(HsfzFrame::diagnostic(dst, src, &r).encode()); - } - o - } - }; + let (request, out) = handle_frame(&mut vehicle.lock().unwrap(), &frame, None); + if let Some(r) = request { + requests.lock().unwrap().push(r); + } if sock.write_all(&out).is_err() { return; } @@ -276,6 +280,85 @@ fn serve( } } +/// Answer one HSFZ frame: the request it carried (if a diagnostic message) and +/// the bytes to send back. `on_write` is called for requests that modify an ECU, +/// *before* the vehicle sees them (the write-safety tests use it). +fn handle_frame( + vehicle: &mut VirtualVehicle, + frame: &HsfzFrame, + on_write: Option<&mut WriteHook>, +) -> (Option, Vec) { + let Some((src, dst, data)) = frame.as_diagnostic() else { + return (None, HsfzFrame::new(0x41, vec![]).encode()); + }; + if let (Some(hook), Some(0x14 | 0x2E | 0x2F | 0x31)) = (on_write, data.first()) { + hook("write"); + } + let request = (dst, data.to_vec()); + let out = match vehicle.respond(dst, data) { + None => HsfzFrame::new(0x43, vec![dst]).encode(), + Some(list) => { + let mut o = HsfzFrame::new(CTRL_ACK, vec![src, dst]).encode(); + for r in list { + o.extend(HsfzFrame::diagnostic(dst, src, &r).encode()); + } + o + } + }; + (Some(request), out) +} + +/// A [`ByteStream`] wired straight to a [`VirtualVehicle`] in memory: no sockets, +/// no threads, fully deterministic. For tests that need many fast runs, or that +/// want to damage the bytes in between. +pub struct LoopbackStream { + vehicle: VirtualVehicle, + inbuf: Vec, + out: VecDeque, + hook: Option, +} + +impl LoopbackStream { + pub fn new(vehicle: VirtualVehicle) -> Self { + Self { + vehicle, + inbuf: Vec::new(), + out: VecDeque::new(), + hook: None, + } + } + + /// Call `hook` the moment a modifying request (0x14, 0x2E, 0x2F, 0x31) arrives. + pub fn on_write(mut self, hook: impl FnMut(&str) + 'static) -> Self { + self.hook = Some(Box::new(hook)); + self + } +} + +impl ByteStream for LoopbackStream { + fn write_all(&mut self, data: &[u8]) -> Result<()> { + self.inbuf.extend_from_slice(data); + while let Some(frame) = take_frame(&mut self.inbuf)? { + let (_, reply) = handle_frame(&mut self.vehicle, &frame, self.hook.as_mut()); + self.out.extend(reply); + } + Ok(()) + } + + fn read_some(&mut self, _timeout: Duration) -> Result> { + if self.out.is_empty() { + return Err(Error::Timeout); + } + Ok(self.out.drain(..).collect()) + } + + fn reconnect(&mut self) -> Result<()> { + self.inbuf.clear(); + self.out.clear(); + Ok(()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/opendiag-bmw/src/scan.rs b/crates/opendiag-bmw/src/scan.rs new file mode 100644 index 0000000..0f522fe --- /dev/null +++ b/crates/opendiag-bmw/src/scan.rs @@ -0,0 +1,66 @@ +//! ECU scan through the gateway: ask each candidate address whether an ECU +//! answers, and count its stored fault codes. Read-only (TesterPresent and +//! ReadDTCInformation only). +//! +//! How a missing ECU shows up is partly NOT VERIFIED: we treat both silence +//! and an HSFZ error frame from the gateway (our mock sends one) as "absent". +//! A real gateway may behave differently; the first scan of a real car will tell. + +use std::time::Duration; + +use opendiag_core::{Error, Result}; +use opendiag_proto::clock::Clock; +use opendiag_proto::uds::{UdsClient, UdsConfig}; + +use crate::gateway::{ByteStream, HsfzGateway}; + +/// What a scan found at one address. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScanEntry { + pub address: u8, + pub present: bool, + /// Why it counts as present or absent, for display. + pub detail: String, + /// Stored fault codes, when the ECU answered the read. + pub dtc_count: Option, +} + +/// Probe each address. Fatal errors (the connection itself failing) abort the scan. +pub fn scan( + gateway: &HsfzGateway, + addresses: &[u8], + probe_timeout: Duration, +) -> Result> { + let cfg = UdsConfig { + p2: probe_timeout, + ..UdsConfig::default() + }; + let mut out = Vec::with_capacity(addresses.len()); + for &address in addresses { + let mut uds = UdsClient::new(gateway.link(address), cfg.clone()); + let (present, detail) = match uds.tester_present() { + Ok(()) => (true, "answered".to_string()), + // A negative response is still an answer: the ECU is there. + Err(Error::NegativeResponse { nrc, .. }) => { + (true, format!("answered (negative response {nrc:#04X})")) + } + Err(Error::Timeout) => (false, "no answer".to_string()), + Err(Error::Protocol(m)) if m.starts_with("hsfz: gateway reported") => { + (false, m.trim_start_matches("hsfz: ").to_string()) + } + Err(e) => return Err(e), + }; + let dtc_count = if present { + uds.read_dtcs_by_status_mask(0xFF).ok().map(|v| v.len()) + } else { + None + }; + out.push(ScanEntry { + address, + present, + detail, + dtc_count, + }); + } + Ok(out) +} diff --git a/crates/opendiag-bmw/tests/e2e.rs b/crates/opendiag-bmw/tests/e2e.rs index 5fb249f..e571df2 100644 --- a/crates/opendiag-bmw/tests/e2e.rs +++ b/crates/opendiag-bmw/tests/e2e.rs @@ -3,11 +3,16 @@ use std::time::Duration; +use opendiag_bmw::ecus::known_addresses; use opendiag_bmw::mock::{MockGateway, VirtualVehicle}; -use opendiag_bmw::{discover, read_did, read_ident, HsfzGateway, HsfzLink, TcpByteStream}; +use opendiag_bmw::{ + discover, log_dids_csv, read_did, read_ident, scan, BmwEcu, DidLogConfig, HsfzGateway, + HsfzLink, TcpByteStream, +}; use opendiag_core::{Error, WriteMode}; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; +use opendiag_services::{apply_clear, plan_clear, BackupStore, ClearConfirmation, Module}; type Link = HsfzLink; @@ -152,3 +157,147 @@ fn tester_present_keeps_the_session_alive() { let (_mock, gw) = setup(); uds(&gw, 0x12).tester_present().unwrap(); } + +fn ecu(gw: &HsfzGateway, address: u8) -> BmwEcu { + BmwEcu::new(gw.link(address), address, UdsConfig::default()) +} + +fn temp_store(name: &str) -> BackupStore { + let path = + std::env::temp_dir().join(format!("opendiag-bmw-{}-{name}.jsonl", std::process::id())); + let _ = std::fs::remove_file(&path); + BackupStore::new(path) +} + +#[test] +fn scan_of_the_known_addresses_finds_the_ecus_and_counts_their_codes() { + let (_mock, gw) = setup(); + let found = scan(&gw, &known_addresses(), Duration::from_millis(300)).unwrap(); + let get = |a: u8| found.iter().find(|e| e.address == a).unwrap(); + assert!(get(0x10).present); + assert_eq!(get(0x10).dtc_count, Some(0)); + assert_eq!(get(0x12).dtc_count, Some(2)); + assert_eq!(get(0x60).dtc_count, Some(1)); + // In the table but not in this car: the gateway answers with an error frame. + assert!(!get(0x29).present); + assert_eq!(get(0x29).dtc_count, None); + assert!(!get(0x40).present); +} + +#[test] +fn a_full_address_sweep_finds_exactly_the_cars_ecus() { + let (_mock, gw) = setup(); + let all: Vec = (0..=0xFFu8).collect(); + let found = scan(&gw, &all, Duration::from_millis(300)).unwrap(); + let present: Vec = found + .iter() + .filter(|e| e.present) + .map(|e| e.address) + .collect(); + assert_eq!(present, vec![0x10, 0x12, 0x18, 0x60]); +} + +#[test] +fn scanning_never_sends_anything_but_tester_present_and_dtc_reads() { + let (mock, gw) = setup(); + scan(&gw, &known_addresses(), Duration::from_millis(300)).unwrap(); + for (_, req) in mock.requests() { + assert!( + matches!(req[0], 0x3E | 0x19), + "unexpected request {req:02X?}" + ); + } +} + +#[test] +fn bmw_dtcs_are_shown_as_raw_hex_with_status_flags() { + let (_mock, gw) = setup(); + let dtcs = ecu(&gw, 0x12).read_dtcs().unwrap(); + assert_eq!(dtcs[0].text, "480A12"); + assert_eq!(dtcs[0].flags, vec!["testFailed", "confirmed"]); +} + +#[test] +fn clearing_goes_through_the_guarded_flow_with_a_snapshot() { + let (mock, gw) = setup(); + let store = temp_store("clear"); + let mut e = ecu(&gw, 0x12); + let shown = plan_clear(e.faults()).unwrap(); + assert_eq!(shown.len(), 2); + assert!( + !mock.requests().iter().any(|(_, r)| r[0] == 0x14), + "planning must not clear anything" + ); + let out = apply_clear( + e.faults(), + &store, + &shown, + &ClearConfirmation::for_codes(&shown), + ) + .unwrap(); + assert_eq!(out.cleared.len(), 2); + assert!(out.remaining.is_empty()); + let text = std::fs::read_to_string(store.path()).unwrap(); + assert!(text.contains("\"kind\":\"dtc_clear\""), "{text}"); + assert!(text.contains("hsfz-uds"), "{text}"); + assert!( + text.contains("480A12"), + "snapshot must hold the codes: {text}" + ); + assert!(text.contains("\"status\":\"verified\""), "{text}"); + assert!(plan_clear(e.faults()).unwrap().is_empty()); + let _ = std::fs::remove_file(store.path()); +} + +#[test] +fn a_confirmation_for_other_codes_clears_nothing() { + let (mock, gw) = setup(); + let store = temp_store("mismatch"); + let mut e = ecu(&gw, 0x12); + let shown = plan_clear(e.faults()).unwrap(); + let other = ClearConfirmation::for_codes(&shown[..1]); + assert!(apply_clear(e.faults(), &store, &shown, &other).is_err()); + assert!(!mock.requests().iter().any(|(_, r)| r[0] == 0x14)); + assert!(!store.path().exists()); +} + +#[test] +fn clearing_is_impossible_if_the_snapshot_cannot_be_written() { + let (mock, gw) = setup(); + let store = BackupStore::new("no-such-directory-xyz/backups.jsonl"); + let mut e = ecu(&gw, 0x12); + let shown = plan_clear(e.faults()).unwrap(); + assert!(apply_clear( + e.faults(), + &store, + &shown, + &ClearConfirmation::for_codes(&shown) + ) + .is_err()); + assert!(!mock.requests().iter().any(|(_, r)| r[0] == 0x14)); + assert_eq!( + plan_clear(e.faults()).unwrap().len(), + 2, + "codes must still be there" + ); +} + +#[test] +fn live_data_logs_raw_values_on_a_steady_grid() { + let (_mock, gw) = setup(); + let mut u = uds(&gw, 0x12); + let cfg = DidLogConfig { + dids: vec![0x4002, 0xF190, 0xBEEF], + interval: Duration::from_millis(10), + samples: 3, + }; + let mut out = Vec::new(); + let sum = log_dids_csv(&mut u, &SystemClock::new(), &cfg, &mut out).unwrap(); + assert_eq!((sum.samples, sum.rows), (3, 9)); + let text = String::from_utf8(out).unwrap(); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines[0], "time_ms,did,status,hex"); + assert_eq!(lines.len(), 10); + assert!(lines[1].ends_with("0x4002,ok,0BB8"), "{}", lines[1]); + assert!(lines[3].ends_with("0xBEEF,absent,"), "{}", lines[3]); +} diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs index 7604045..9dc4511 100644 --- a/crates/opendiag-cli/src/bmw.rs +++ b/crates/opendiag-cli/src/bmw.rs @@ -1,16 +1,22 @@ -//! `opendiag bmw ...`: BMW F-series over an ENET cable (HSFZ). Read-only. +//! `opendiag bmw ...`: BMW F-series over an ENET cable (HSFZ). Read-only, +//! except `dtc clear`, which goes through the guarded clear flow. use std::net::{IpAddr, SocketAddr}; use std::time::Duration; use clap::{Args, Subcommand}; +use opendiag_bmw::ecus; use opendiag_bmw::hsfz::{DEFAULT_GATEWAY, TCP_PORT}; use opendiag_bmw::mock::{MockGateway, VirtualVehicle}; use opendiag_bmw::{ - broadcast_target, discover, read_did, read_ident, Discovered, HsfzGateway, TcpByteStream, + broadcast_target, discover, log_dids_csv, read_did, read_ident, scan, BmwEcu, DidLogConfig, + Discovered, HsfzGateway, HsfzLink, TcpByteStream, }; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; +use opendiag_services::{apply_clear, plan_clear, ClearConfirmation, DtcReport, Module}; + +use crate::{backup_store, confirm, StoreArg}; #[derive(Subcommand)] pub enum BmwCmd { @@ -36,6 +42,53 @@ pub enum BmwCmd { #[arg(value_parser = parse_hex_u16)] did: u16, }, + /// Find which ECUs answer behind the gateway, and how many fault codes each holds. + Scan { + #[command(flatten)] + conn: Conn, + /// Probe every address 0x00-0xFF instead of just the known ones (slower). + #[arg(long)] + all: bool, + /// How long to wait for each address, in milliseconds. + #[arg(long, default_value_t = 300)] + probe_ms: u64, + }, + /// Read or clear fault codes of one ECU (default: the gateway; pick with --target). + Dtc { + #[command(subcommand)] + action: BmwDtc, + }, + /// Log data identifiers from one ECU as raw CSV at a steady rate. + Live { + #[command(flatten)] + conn: Conn, + /// Data identifiers in hex, comma separated, e.g. 0x4002,0xF190. + #[arg(long, value_delimiter = ',', required = true, value_parser = parse_hex_u16)] + did: Vec, + /// Time between rounds, in milliseconds. + #[arg(long, default_value_t = 500)] + interval_ms: u64, + /// Number of rounds. + #[arg(long, default_value_t = 10)] + samples: u32, + /// Write the CSV here instead of standard output. + #[arg(long)] + out: Option, + }, +} + +#[derive(Subcommand)] +pub enum BmwDtc { + /// List the stored fault codes (read-only). + Read(Conn), + /// Clear all stored fault codes. Saves a snapshot of them first, asks you to + /// confirm exactly what was shown, then checks what the ECU reports. There is no --yes. + Clear { + #[command(flatten)] + conn: Conn, + #[command(flatten)] + store: StoreArg, + }, } #[derive(Args)] @@ -75,6 +128,24 @@ pub fn run(cmd: BmwCmd) -> Result<(), String> { } => discover_cmd(to, wait_ms, simulate), BmwCmd::Ident(c) => ident_cmd(&c), BmwCmd::Did { conn, did } => did_cmd(&conn, did), + BmwCmd::Scan { + conn, + all, + probe_ms, + } => scan_cmd(&conn, all, probe_ms), + BmwCmd::Dtc { + action: BmwDtc::Read(conn), + } => dtc_read_cmd(&conn), + BmwCmd::Dtc { + action: BmwDtc::Clear { conn, store }, + } => dtc_clear_cmd(&conn, &store), + BmwCmd::Live { + conn, + did, + interval_ms, + samples, + out, + } => live_cmd(&conn, did, interval_ms, samples, out), } } @@ -215,3 +286,144 @@ fn did_cmd(c: &Conn, did: u16) -> Result<(), String> { } Ok(()) } + +fn scan_cmd(c: &Conn, all: bool, probe_ms: u64) -> Result<(), String> { + let s = connect(c)?; + let addresses: Vec = if all { + (0..=0xFFu8).filter(|a| *a != c.tester).collect() + } else { + ecus::known_addresses() + }; + let found = + scan(&s.gateway, &addresses, Duration::from_millis(probe_ms)).map_err(|e| e.to_string())?; + let present: Vec<_> = found.iter().filter(|e| e.present).collect(); + if present.is_empty() { + println!("No ECU answered. Check the ENET cable and that the ignition is on."); + return Ok(()); + } + println!("{} ECU(s) answered:", present.len()); + for e in present { + let name = ecus::name(e.address).unwrap_or("?"); + let desc = ecus::description(e.address).unwrap_or("not in the address table"); + let codes = match e.dtc_count { + Some(0) => "no fault codes".to_string(), + Some(n) => format!("{n} fault code(s)"), + None => "fault codes unreadable".to_string(), + }; + println!(" {:#04X} {name:<6} {desc}: {codes}", e.address); + } + println!("Names come from a short unverified table (docs/bmw.md); they are labels only."); + Ok(()) +} + +type CliEcu = BmwEcu>; + +fn ecu_of(s: &Session) -> CliEcu { + BmwEcu::new(s.gateway.link(s.target), s.target, UdsConfig::default()) +} + +fn print_bmw_dtcs(dtcs: &[DtcReport]) { + if dtcs.is_empty() { + println!("No fault codes stored."); + return; + } + for d in dtcs { + println!( + " {} status {:#04X} {}", + d.text, + d.status, + d.flags.join(", ") + ); + } +} + +fn dtc_read_cmd(c: &Conn) -> Result<(), String> { + let s = connect(c)?; + let mut ecu = ecu_of(&s); + println!("ECU {:#04X}", s.target); + let dtcs = ecu.read_dtcs().map_err(|e| e.to_string())?; + print_bmw_dtcs(&dtcs); + println!("Codes are shown as raw hex; no descriptions are bundled (docs/bmw.md)."); + Ok(()) +} + +fn dtc_clear_cmd(c: &Conn, store: &StoreArg) -> Result<(), String> { + let store = backup_store(store); + let s = connect(c)?; + let mut ecu = ecu_of(&s); + let shown = plan_clear(ecu.faults()).map_err(|e| e.to_string())?; + if shown.is_empty() { + println!( + "ECU {:#04X} has no fault codes stored; nothing to clear.", + s.target + ); + return Ok(()); + } + println!( + "About to clear {} fault code(s) in ECU {:#04X}:", + shown.len(), + s.target + ); + print_bmw_dtcs(&shown); + println!( + "Clearing erases these codes and their status for good and cannot be undone. A snapshot of them is saved to {} first.", + store.path().display() + ); + if !c.simulate { + println!("Keep the ignition on and a battery charger connected until this finishes."); + } + if !confirm()? { + println!("Cancelled; nothing was changed."); + return Ok(()); + } + let confirmation = ClearConfirmation::for_codes(&shown); + let outcome = + apply_clear(ecu.faults(), &store, &shown, &confirmation).map_err(|e| e.to_string())?; + println!( + "Cleared {} fault code(s). Snapshot {} is in {}.", + outcome.cleared.len(), + outcome.backup_id, + store.path().display() + ); + if outcome.remaining.is_empty() { + println!("The ECU now reports no fault codes."); + } else { + println!( + "Note: {} code(s) are still reported (active faults come straight back):", + outcome.remaining.len() + ); + print_bmw_dtcs(&outcome.remaining); + } + Ok(()) +} + +fn live_cmd( + c: &Conn, + dids: Vec, + interval_ms: u64, + samples: u32, + out: Option, +) -> Result<(), String> { + let s = connect(c)?; + let mut uds = UdsClient::new(s.gateway.link(s.target), UdsConfig::default()); + let cfg = DidLogConfig { + dids, + interval: Duration::from_millis(interval_ms), + samples, + }; + let clock = SystemClock::new(); + let summary = match out { + Some(path) => { + let mut f = std::fs::File::create(&path) + .map_err(|e| format!("cannot create {}: {e}", path.display()))?; + log_dids_csv(&mut uds, &clock, &cfg, &mut f) + } + None => log_dids_csv(&mut uds, &clock, &cfg, &mut std::io::stdout().lock()), + } + .map_err(|e| e.to_string())?; + eprintln!( + "Logged {} round(s), {} row(s). Values are raw hex, not converted to units.", + summary.samples, summary.rows + ); + Ok(()) +} diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index 765a41c..eb0cea3 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1190,3 +1190,101 @@ fn bmw_simulated_did_read_and_missing_did() { assert!(ok); assert!(out.contains("does not have DID"), "{out}"); } + +#[test] +fn bmw_simulated_scan_lists_the_ecus_with_code_counts() { + let (ok, out, err) = run(&["bmw", "scan", "--simulate"], ""); + assert!(ok, "{err}"); + assert!(out.contains("4 ECU(s) answered"), "{out}"); + assert!( + out.contains("0x12") && out.contains("2 fault code(s)"), + "{out}" + ); + assert!( + out.contains("0x60") && out.contains("1 fault code(s)"), + "{out}" + ); + assert!( + !out.contains("0x29"), + "an ECU the car lacks must not be listed: {out}" + ); + let (ok, out, err) = run(&["bmw", "scan", "--simulate", "--all"], ""); + assert!(ok, "{err}"); + assert!(out.contains("4 ECU(s) answered"), "{out}"); +} + +#[test] +fn bmw_simulated_dtc_read_shows_raw_hex_codes() { + let (ok, out, err) = run( + &["bmw", "dtc", "read", "--simulate", "--target", "0x12"], + "", + ); + assert!(ok, "{err}"); + assert!(out.contains("480A12") && out.contains("480B01"), "{out}"); + assert!(out.contains("confirmed"), "{out}"); +} + +#[test] +fn bmw_simulated_clear_needs_yes_snapshots_and_verifies() { + let backups = temp_file("bmw-clear.jsonl"); + let _ = std::fs::remove_file(&backups); + let b = backups.to_str().unwrap(); + let args = [ + "bmw", + "dtc", + "clear", + "--simulate", + "--target", + "0x12", + "--backup-file", + b, + ]; + // Anything but YES: nothing changes and no snapshot is written. + let (ok, out, _) = run(&args, "no\n"); + assert!(ok); + assert!(out.contains("Cancelled"), "{out}"); + assert!(!backups.exists()); + // YES: snapshot first, then the clear, then the re-read. + let (ok, out, err) = run(&args, "YES\n"); + assert!(ok, "{err}"); + assert!(out.contains("Cleared 2 fault code(s)"), "{out}"); + assert!(out.contains("now reports no fault codes"), "{out}"); + let text = std::fs::read_to_string(&backups).unwrap(); + assert!( + text.contains("480A12") && text.contains("\"status\":\"verified\""), + "{text}" + ); + let _ = std::fs::remove_file(&backups); +} + +#[test] +fn bmw_clear_has_no_yes_flag() { + let (ok, _, err) = run(&["bmw", "dtc", "clear", "--simulate", "--yes"], ""); + assert!(!ok); + assert!(err.contains("--yes"), "{err}"); +} + +#[test] +fn bmw_simulated_live_logs_raw_csv() { + let (ok, out, err) = run( + &[ + "bmw", + "live", + "--simulate", + "--target", + "0x12", + "--did", + "0x4002,0xBEEF", + "--interval-ms", + "10", + "--samples", + "2", + ], + "", + ); + assert!(ok, "{err}"); + assert!(out.starts_with("time_ms,did,status,hex"), "{out}"); + assert!(out.contains("0x4002,ok,0BB8"), "{out}"); + assert!(out.contains("0xBEEF,absent,"), "{out}"); + assert_eq!(out.lines().count(), 5, "{out}"); +} diff --git a/crates/opendiag-services/Cargo.toml b/crates/opendiag-services/Cargo.toml index e82c4a9..4e62abd 100644 --- a/crates/opendiag-services/Cargo.toml +++ b/crates/opendiag-services/Cargo.toml @@ -14,5 +14,9 @@ opendiag-transport = { path = "../opendiag-transport" } serde = { version = "1", features = ["derive"] } serde_json = "1" +[dev-dependencies] +# Test-only cycle (bmw depends on services): lets write_safety.rs cover the BMW clear flow. +opendiag-bmw = { path = "../opendiag-bmw" } + [lints] workspace = true diff --git a/crates/opendiag-services/tests/write_safety.rs b/crates/opendiag-services/tests/write_safety.rs index d396f56..969e32c 100644 --- a/crates/opendiag-services/tests/write_safety.rs +++ b/crates/opendiag-services/tests/write_safety.rs @@ -14,6 +14,8 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use std::time::Duration; +use opendiag_bmw::mock::{LoopbackStream, VirtualVehicle}; +use opendiag_bmw::{BmwEcu, ByteStream, HsfzGateway}; use opendiag_core::Result; use opendiag_proto::clock::FakeClock; use opendiag_proto::isotp::{Config, IsoTpLink}; @@ -356,14 +358,67 @@ fn run_tp20_clear(store: &BackupStore, seed: u64, watch: &Watch) { ); } +/// Damages the bytes a gateway connection delivers: flips, truncates, duplicates +/// and invents data, so the HSFZ framing and the UDS client above it see confused +/// and partial sessions. +struct MutBytes { + inner: S, + rng: Rng, + rate: u64, +} + +impl ByteStream for MutBytes { + fn write_all(&mut self, data: &[u8]) -> Result<()> { + self.inner.write_all(data) + } + + fn read_some(&mut self, timeout: Duration) -> Result> { + let mut b = self.inner.read_some(timeout)?; + if self.rng.below(100) < self.rate { + match self.rng.below(4) { + 0 => { + let i = self.rng.below(b.len() as u64) as usize; + b[i] ^= 1 << self.rng.below(8); + } + 1 => b.truncate(1 + self.rng.below(b.len() as u64) as usize / 2), + 2 => b.extend(b.clone()), + _ => b = (0..8).map(|_| self.rng.below(256) as u8).collect(), + } + } + Ok(b) + } +} + +fn run_bmw_clear(store: &BackupStore, seed: u64, watch: &Watch) { + let stream = LoopbackStream::new(VirtualVehicle::demo()) + .on_write(watch.hook(store.path(), "\"kind\":\"dtc_clear\"")); + let stream = MutBytes { + inner: stream, + rng: Rng(seed ^ 0xB3), + rate: rate(seed), + }; + let gw = HsfzGateway::new(stream, FakeClock::new(), 0xF4); + let mut ecu = BmwEcu::new(gw.link(0x12), 0x12, UdsConfig::default()); + let Ok(shown) = plan_clear(ecu.faults()) else { + return; + }; + let _ = apply_clear( + ecu.faults(), + store, + &shown, + &ClearConfirmation::for_codes(&shown), + ); +} + type Run = fn(&BackupStore, u64, &Watch); -const FLOWS: [(&str, Run); 5] = [ +const FLOWS: [(&str, Run); 6] = [ ("clear over KW1281", run_kw1281_clear), ("clear over KWP2000 (K-line)", run_kwp_clear), ("adaptation over KW1281", run_kw1281_adaptation), ("clear over UDS (ISO-TP)", run_uds_clear), ("clear over KWP2000 over TP2.0", run_tp20_clear), + ("clear over BMW HSFZ (UDS)", run_bmw_clear), ]; #[test] diff --git a/docs/bmw.md b/docs/bmw.md index 499929f..431f3a9 100644 --- a/docs/bmw.md +++ b/docs/bmw.md @@ -1,12 +1,16 @@ # BMW F-series (ENET / HSFZ) -**Status: simulator-tested only.** None of this has run against a real car, gateway or ENET cable. Read-only. +**Status: simulator-tested only.** None of this has run against a real car, gateway or ENET cable. Read-only, except `dtc clear`, which uses the guarded flow below. ```bash opendiag bmw discover # find gateways (UDP broadcast, port 6811) opendiag bmw ident [--ip 169.254.x.x] # VIN, I-level, FA (raw) from the gateway opendiag bmw did --target 0x12 0xF190 # read one data identifier from one ECU -opendiag bmw ident --simulate # no car: built-in virtual BMW +opendiag bmw scan [--all] # which ECUs answer, and how many fault codes each holds +opendiag bmw dtc read --target 0x12 # stored fault codes (raw hex + status flags) +opendiag bmw dtc clear --target 0x12 # guarded: snapshot, typed YES, clear, re-read +opendiag bmw live --target 0x12 --did 0x4002,0xF190 --samples 20 # raw CSV log +opendiag bmw ident --simulate # no car: built-in virtual BMW (works for every command) ``` Before connecting to a real car: ignition on, a battery charger connected. The ENET cable needs the car's @@ -23,7 +27,24 @@ second thread could read another request's reply off the shared stream. If the g `HsfzGateway::reconnect` reopens it; ECU session state must then be re-established by the caller. Safety: the link refuses programming sessions (`0x10 02`) and download/transfer services (`0x34`-`0x38`) at any -write mode. Clearing DTCs and writes are not wired to the CLI yet. +write mode. + +### Step 2: scan, fault codes, live data + +- **Scan** probes each candidate address with TesterPresent and, for ECUs that answer, reads the fault-code + count. Default candidates are the short address table (`ecus.rs`); `--all` sweeps `0x00`-`0xFF`. + Only TesterPresent and ReadDTCInformation are sent (tested). +- **DTCs** are shown as raw 3-byte hex (e.g. `480A12`) with decoded status bits. BMW codes are not SAE J2012 + codes, so no `P`/`B`/`C`/`U` text is invented, and no descriptions are bundled. +- **Clear** reuses the same guarded flow as the VAG modules (`plan_clear` / `apply_clear`): a confirmation bound + to the exact codes shown, a re-read, a flushed snapshot in the backup file before anything is sent, the clear, + and a re-read afterwards. There is no `--yes`. This path is part of + `crates/opendiag-services/tests/write_safety.rs` (no clear reaches the ECU without a durable snapshot, under + corrupted bytes, and none if the snapshot cannot be written). +- **Live data** logs raw DID values as hex at a fixed rate. Nothing is converted to units: we have no verified + DID definitions. Which DIDs a given ECU offers is for you to find (`opendiag bmw did`). +- **ECU address table** (`crates/opendiag-bmw/src/ecus.rs`): six names, **NOT VERIFIED**, labels only. It does + not affect what is sent. ## Verified vs unverified @@ -47,3 +68,8 @@ Verified against public sources (see [sources.md](sources.md)): just yields "not available". - Whether an F30 needs ReadDTCInformation sub-functions other than `0x02`. - The gateway's diagnostic address (`0x10` is the usual one and is taken from discovery when available). +- Whether an F-series ECU needs an extended diagnostic session (`0x10 03`) before ReadDTCInformation or + ClearDiagnosticInformation. Currently neither is sent in a special session. +- How a real gateway reports an address with no ECU (silence or an error frame). The scan treats both as absent. +- The names in the ECU address table. +- Whether `0x14 FFFFFF` clears every ECU's codes on a real F30, or only some groups. From 31100e0d366ce2cc737375cefe120e7448ea7438 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:57:43 +0000 Subject: [PATCH 4/9] feat(bmw): guarded raw block write and restore - services::block: BlockAccess, plan/apply_block_change, plan_block_restore. Confirmation bound to the change, re-read, flushed full-block backup, write, read-back verify; length changes, no-ops and 0xF1xx refused - BackupRecord gains block/old_hex/new_hex (older records still load) - BmwEcu implements BlockAccess; opt-in extended session, never programming - CLI: opendiag bmw block read|write|restore; backup list shows blocks - block write added to write_safety.rs under corrupted bytes - mock: writable blocks, one that acknowledges but does not keep a write DID is supplied by the user; no coding DID is assumed. Simulator-tested only. Co-Authored-By: Claude Sonnet 5.5 --- PROJECT_PLAN.md | 2 +- README.md | 2 +- crates/opendiag-bmw/src/ecu.rs | 62 ++++- crates/opendiag-bmw/src/mock.rs | 21 +- crates/opendiag-bmw/tests/e2e.rs | 174 +++++++++++- crates/opendiag-cli/src/bmw.rs | 158 ++++++++++- crates/opendiag-cli/src/main.rs | 12 + crates/opendiag-cli/tests/cli.rs | 84 ++++++ crates/opendiag-services/src/backup.rs | 52 ++++ crates/opendiag-services/src/block.rs | 252 ++++++++++++++++++ crates/opendiag-services/src/lib.rs | 5 + .../opendiag-services/tests/write_safety.rs | 34 ++- docs/bmw.md | 33 ++- 13 files changed, 881 insertions(+), 10 deletions(-) create mode 100644 crates/opendiag-services/src/block.rs diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md index e09385d..683848e 100644 --- a/PROJECT_PLAN.md +++ b/PROJECT_PLAN.md @@ -105,7 +105,7 @@ Key design points: ### Phase B - BMW F-series over ENET (branch `feat/bmw-backend`) -Status: steps 1 and 2 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Next: backup + coding (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). +Status: steps 1-3 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Step 3 added: guarded raw block write/restore (`opendiag-services::block`, backup-first, read-back verify, in `write_safety.rs`; DID supplied by the user). Next: FDL decode (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). ## 5. Repo layout diff --git a/README.md b/README.md index aa05485..35b1992 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ An open source, cross-platform diagnostic suite for VAG group vehicles (VW, Audi | Transports | Serial K-line (Windows/Linux/macOS), SocketCAN (Linux), ELM327-style adapters (degraded, UDS over 11-bit CAN), Simulator, Replay | | Modules | `scan` and `dtc read/clear` work on KW1281 (`--slow-init`), KWP2000 on K-line (`--fast-init`) and KWP2000 over TP2.0 on CAN (`--can`, Linux); live data and adaptation are KW1281 only | | CLI | `scan`, `dtc read/clear`, `report` (standalone HTML), `serve` (read-only local web page), `doctor` (support summary), `log` (live data to CSV), `adaptation read/set`, `backup list/restore`, `probe`, `ports`, `capture`, `--trace` on all hardware commands, `data validate/schema` | -| BMW (F-series, ENET) | **Experimental, simulator-tested only, never run on a real car.** `opendiag bmw discover/ident/did/scan/dtc/live`: HSFZ over TCP, UDP discovery, VIN / I-level / FA reads, ECU scan, fault codes (read, and guarded clear), raw DID logging. Unverified protocol details are listed in [docs/bmw.md](docs/bmw.md) | +| BMW (F-series, ENET) | **Experimental, simulator-tested only, never run on a real car.** `opendiag bmw discover/ident/did/scan/dtc/live`: HSFZ over TCP, UDP discovery, VIN / I-level / FA reads, ECU scan, fault codes (read, and guarded clear), raw DID logging, guarded raw block write/restore. Unverified protocol details are listed in [docs/bmw.md](docs/bmw.md) | | Data | Open YAML format with validator and generated JSON Schema (CC0-1.0) | ## Install diff --git a/crates/opendiag-bmw/src/ecu.rs b/crates/opendiag-bmw/src/ecu.rs index 2d2b6c2..d4dcf11 100644 --- a/crates/opendiag-bmw/src/ecu.rs +++ b/crates/opendiag-bmw/src/ecu.rs @@ -14,7 +14,7 @@ use opendiag_core::{Result, WriteMode}; use opendiag_proto::link::MessageLink; use opendiag_proto::uds::{UdsClient, UdsConfig}; use opendiag_services::{ - identify, status_flags, DtcReport, FaultAccess, Ident, Module, WriteToken, + identify, status_flags, BlockAccess, DtcReport, FaultAccess, Ident, Module, WriteToken, }; /// Raw hex form of a BMW DTC. @@ -25,6 +25,9 @@ pub fn format_bmw_dtc(code: u32) -> String { pub struct BmwEcu { uds: UdsClient, address: u8, + /// Open the extended diagnostic session (0x10 03) before the first block access. + extended_session: bool, + session_open: bool, } impl BmwEcu { @@ -32,9 +35,27 @@ impl BmwEcu { Self { uds: UdsClient::new(link, cfg), address, + extended_session: false, + session_open: false, } } + /// Open the extended diagnostic session (0x10 03) before reading or writing + /// blocks. Whether an F-series ECU needs this is NOT VERIFIED, so it is opt-in. + /// Never the programming session: that is refused at the link. + pub fn with_extended_session(mut self) -> Self { + self.extended_session = true; + self + } + + fn ensure_session(&mut self) -> Result<()> { + if self.extended_session && !self.session_open { + self.uds.session_control(0x03)?; + self.session_open = true; + } + Ok(()) + } + pub fn address(&self) -> u8 { self.address } @@ -85,6 +106,45 @@ impl FaultAccess for BmwEcu { } } +impl BlockAccess for BmwEcu { + fn protocol(&self) -> &'static str { + "hsfz-uds" + } + + fn module_address(&self) -> u8 { + self.address + } + + fn describe(&self) -> String { + FaultAccess::describe(self) + } + + fn read_block(&mut self, id: u16) -> Result> { + self.ensure_session()?; + self.uds.read_data_by_identifier(id) + } + + fn writable(&self, id: u16) -> std::result::Result<(), String> { + // 0xF100-0xF1FF are the ISO 14229 identification identifiers (VIN, part + // numbers, ...). Identity data is never written. + if (0xF100..=0xF1FF).contains(&id) { + return Err(format!( + "{id:#06X} is an identification identifier (VIN, part numbers, ...); OpenDiag never writes those" + )); + } + Ok(()) + } + + fn write_block(&mut self, _token: &WriteToken, id: u16, data: &[u8]) -> Result<()> { + self.ensure_session()?; + let previous = self.uds.write_mode(); + self.uds.set_write_mode(WriteMode::Unlocked); + let result = self.uds.write_data_by_identifier(id, data); + self.uds.set_write_mode(previous); + result + } +} + impl Module for BmwEcu { fn identify(&mut self) -> Result { identify(&mut self.uds) diff --git a/crates/opendiag-bmw/src/mock.rs b/crates/opendiag-bmw/src/mock.rs index 759d385..303dbc4 100644 --- a/crates/opendiag-bmw/src/mock.rs +++ b/crates/opendiag-bmw/src/mock.rs @@ -35,6 +35,8 @@ pub struct VirtualEcu { pub dtcs: Vec<(u32, u8)>, /// DIDs that first answer "response pending" (0x78) once. pub slow_dids: BTreeSet, + /// DIDs that acknowledge a write but do not store it (to test read-back checks). + pub ignore_writes: BTreeSet, } /// A simulated car: a gateway plus ECUs, all addressed through the gateway. @@ -66,6 +68,10 @@ impl VirtualVehicle { dme.slow_dids.insert(0x4001); dme.dids.insert(0x4001, vec![0x12, 0x34]); dme.dids.insert(0x4002, vec![0x0B, 0xB8]); + // Two invented 8-byte blocks standing in for coding data. The second never keeps a write. + dme.dids.insert(0x2000, vec![1, 2, 3, 4, 5, 6, 7, 8]); + dme.dids.insert(0x2001, vec![0; 8]); + dme.ignore_writes.insert(0x2001); let mut egs = VirtualEcu { address: 0x18, ..Default::default() @@ -134,7 +140,20 @@ impl VirtualVehicle { vec![nrc(0x31)] } } - (0x19 | 0x22 | 0x14, _) => vec![nrc(0x13)], + (0x2E, [_, hi, lo, data @ ..]) => { + let did = u16::from_be_bytes([*hi, *lo]); + match ecu.dids.get(&did) { + None => vec![nrc(0x31)], + Some(cur) if cur.len() != data.len() => vec![nrc(0x13)], + Some(_) => { + if !ecu.ignore_writes.contains(&did) { + ecu.dids.insert(did, data.to_vec()); + } + vec![vec![0x6E, *hi, *lo]] + } + } + } + (0x19 | 0x22 | 0x14 | 0x2E, _) => vec![nrc(0x13)], _ => vec![nrc(0x11)], }) } diff --git a/crates/opendiag-bmw/tests/e2e.rs b/crates/opendiag-bmw/tests/e2e.rs index e571df2..dde173c 100644 --- a/crates/opendiag-bmw/tests/e2e.rs +++ b/crates/opendiag-bmw/tests/e2e.rs @@ -12,7 +12,10 @@ use opendiag_bmw::{ use opendiag_core::{Error, WriteMode}; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; -use opendiag_services::{apply_clear, plan_clear, BackupStore, ClearConfirmation, Module}; +use opendiag_services::{ + apply_block_change, apply_clear, plan_block_change, plan_block_restore, plan_clear, + BackupStatus, BackupStore, BlockAccess, BlockConfirmation, ClearConfirmation, Module, +}; type Link = HsfzLink; @@ -301,3 +304,172 @@ fn live_data_logs_raw_values_on_a_steady_grid() { assert!(lines[1].ends_with("0x4002,ok,0BB8"), "{}", lines[1]); assert!(lines[3].ends_with("0xBEEF,absent,"), "{}", lines[3]); } + +fn writes_seen(mock: &MockGateway) -> usize { + mock.requests().iter().filter(|(_, r)| r[0] == 0x2E).count() +} + +fn changed(block: &[u8], at: usize, to: u8) -> Vec { + let mut v = block.to_vec(); + v[at] = to; + v +} + +#[test] +fn a_block_write_is_backed_up_written_and_read_back() { + let (mock, gw) = setup(); + let store = temp_store("block-ok"); + let mut e = ecu(&gw, 0x12); + let old = e.read_block(0x2000).unwrap(); + let change = plan_block_change(&mut e, 0x2000, changed(&old, 3, 0xAA)).unwrap(); + assert_eq!(change.differing_offsets(), vec![3]); + assert_eq!(writes_seen(&mock), 0, "planning must not write"); + let done = apply_block_change( + &mut e, + &store, + &change, + &BlockConfirmation::for_change(&change), + ) + .unwrap(); + assert_eq!(e.read_block(0x2000).unwrap(), changed(&old, 3, 0xAA)); + let rec = store.get(&done.backup_id).unwrap().unwrap(); + assert_eq!(rec.kind, "block_write"); + assert_eq!(rec.old_hex.as_deref(), Some("0102030405060708")); + assert_eq!(rec.new_hex.as_deref(), Some("010203AA05060708")); + assert_eq!(rec.status, BackupStatus::Verified); + let _ = std::fs::remove_file(store.path()); +} + +#[test] +fn a_block_write_can_be_restored_byte_for_byte() { + let (_mock, gw) = setup(); + let store = temp_store("block-restore"); + let mut e = ecu(&gw, 0x12); + let old = e.read_block(0x2000).unwrap(); + let change = plan_block_change(&mut e, 0x2000, changed(&old, 0, 0xFF)).unwrap(); + let done = apply_block_change( + &mut e, + &store, + &change, + &BlockConfirmation::for_change(&change), + ) + .unwrap(); + let back = plan_block_restore(&mut e, &store, &done.backup_id).unwrap(); + assert_eq!(back.new, old); + let again = + apply_block_change(&mut e, &store, &back, &BlockConfirmation::for_change(&back)).unwrap(); + assert_eq!(e.read_block(0x2000).unwrap(), old); + assert_eq!( + store.get(&done.backup_id).unwrap().unwrap().status, + BackupStatus::Restored + ); + assert_eq!( + store + .get(&again.backup_id) + .unwrap() + .unwrap() + .restores + .as_deref(), + Some(done.backup_id.as_str()) + ); + let _ = std::fs::remove_file(store.path()); +} + +#[test] +fn a_write_the_ecu_does_not_keep_is_reported_and_recorded() { + let (_mock, gw) = setup(); + let store = temp_store("block-lie"); + let mut e = ecu(&gw, 0x12); + let change = plan_block_change(&mut e, 0x2001, vec![9; 8]).unwrap(); + let err = apply_block_change( + &mut e, + &store, + &change, + &BlockConfirmation::for_change(&change), + ) + .unwrap_err(); + assert!(err.to_string().contains("reads back differently"), "{err}"); + let rec = store.records().unwrap().pop().unwrap(); + assert_eq!(rec.status, BackupStatus::VerificationFailed); + assert_eq!(rec.old_hex.as_deref(), Some("0000000000000000")); + let _ = std::fs::remove_file(store.path()); +} + +#[test] +fn refused_block_writes_send_nothing() { + let (mock, gw) = setup(); + let store = temp_store("block-refused"); + let mut e = ecu(&gw, 0x12); + let old = e.read_block(0x2000).unwrap(); + let change = plan_block_change(&mut e, 0x2000, changed(&old, 1, 0x77)).unwrap(); + + // Confirmation for a different change. + let other = plan_block_change(&mut e, 0x2000, changed(&old, 2, 0x77)).unwrap(); + assert!(apply_block_change( + &mut e, + &store, + &change, + &BlockConfirmation::for_change(&other) + ) + .is_err()); + // Not a change. + let same = plan_block_change(&mut e, 0x2000, old.clone()).unwrap(); + assert!( + apply_block_change(&mut e, &store, &same, &BlockConfirmation::for_change(&same)).is_err() + ); + // Length change. + let short = plan_block_change(&mut e, 0x2000, old[..4].to_vec()).unwrap(); + assert!(apply_block_change( + &mut e, + &store, + &short, + &BlockConfirmation::for_change(&short) + ) + .is_err()); + // Identity data (the VIN) is never writable. + assert!(plan_block_change(&mut e, 0xF190, vec![0; 17]).is_err()); + // Snapshot cannot be written. + let bad = BackupStore::new("no-such-directory-xyz/backups.jsonl"); + assert!(apply_block_change( + &mut e, + &bad, + &change, + &BlockConfirmation::for_change(&change) + ) + .is_err()); + + assert_eq!(writes_seen(&mock), 0, "no write may reach the ECU"); + assert!(!store.path().exists()); + assert_eq!(e.read_block(0x2000).unwrap(), old); +} + +#[test] +fn restoring_from_another_modules_backup_is_refused() { + let (_mock, gw) = setup(); + let store = temp_store("block-other"); + let mut a = ecu(&gw, 0x12); + let old = a.read_block(0x2000).unwrap(); + let change = plan_block_change(&mut a, 0x2000, changed(&old, 0, 0x42)).unwrap(); + let done = apply_block_change( + &mut a, + &store, + &change, + &BlockConfirmation::for_change(&change), + ) + .unwrap(); + let mut other = ecu(&gw, 0x60); + assert!(plan_block_restore(&mut other, &store, &done.backup_id).is_err()); + let _ = std::fs::remove_file(store.path()); +} + +#[test] +fn the_extended_session_is_opt_in_and_the_programming_session_is_still_refused() { + let (mock, gw) = setup(); + let mut plain = ecu(&gw, 0x12); + plain.read_block(0x2000).unwrap(); + assert!(!mock.requests().iter().any(|(_, r)| r[0] == 0x10)); + let mut ext = BmwEcu::new(gw.link(0x12), 0x12, UdsConfig::default()).with_extended_session(); + ext.read_block(0x2000).unwrap(); + assert!(mock.requests().iter().any(|(_, r)| r == &[0x10, 0x03])); + assert!(!mock.requests().iter().any(|(_, r)| r[..2] == [0x10, 0x02])); +} diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs index 9dc4511..4ea7c5a 100644 --- a/crates/opendiag-cli/src/bmw.rs +++ b/crates/opendiag-cli/src/bmw.rs @@ -14,7 +14,10 @@ use opendiag_bmw::{ }; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; -use opendiag_services::{apply_clear, plan_clear, ClearConfirmation, DtcReport, Module}; +use opendiag_services::{ + apply_block_change, apply_clear, plan_block_change, plan_block_restore, plan_clear, unhex, + BlockAccess, BlockChange, BlockConfirmation, ClearConfirmation, DtcReport, Module, +}; use crate::{backup_store, confirm, StoreArg}; @@ -58,6 +61,12 @@ pub enum BmwCmd { #[command(subcommand)] action: BmwDtc, }, + /// Read, write or restore a raw data block (coding data) of one ECU. Writes are + /// guarded: backup first, typed confirmation, read-back check. No --yes. + Block { + #[command(subcommand)] + action: BmwBlock, + }, /// Log data identifiers from one ECU as raw CSV at a steady rate. Live { #[command(flatten)] @@ -77,6 +86,49 @@ pub enum BmwCmd { }, } +#[derive(Args)] +pub struct BlockConn { + #[command(flatten)] + conn: Conn, + /// Open the extended diagnostic session (0x10 03) first. Whether an F-series + /// ECU needs it is unverified, so it is off by default. + #[arg(long)] + extended_session: bool, +} + +#[derive(Subcommand)] +pub enum BmwBlock { + /// Print one block as hex (read-only). + Read { + #[command(flatten)] + bc: BlockConn, + /// Data identifier of the block, in hex. + #[arg(long, value_parser = parse_hex_u16)] + did: u16, + }, + /// Replace one block with new hex bytes of the same length. + Write { + #[command(flatten)] + bc: BlockConn, + #[arg(long, value_parser = parse_hex_u16)] + did: u16, + /// The complete new block as hex, e.g. 010203AA05060708. + #[arg(long)] + hex: String, + #[command(flatten)] + store: StoreArg, + }, + /// Put a block back from a backup id (see `opendiag backup list`). + Restore { + #[command(flatten)] + bc: BlockConn, + /// Backup id, e.g. b0003. + id: String, + #[command(flatten)] + store: StoreArg, + }, +} + #[derive(Subcommand)] pub enum BmwDtc { /// List the stored fault codes (read-only). @@ -139,6 +191,7 @@ pub fn run(cmd: BmwCmd) -> Result<(), String> { BmwCmd::Dtc { action: BmwDtc::Clear { conn, store }, } => dtc_clear_cmd(&conn, &store), + BmwCmd::Block { action } => block_cmd(action), BmwCmd::Live { conn, did, @@ -427,3 +480,106 @@ fn live_cmd( ); Ok(()) } + +fn block_ecu(bc: &BlockConn) -> Result<(CliEcu, Session), String> { + let s = connect(&bc.conn)?; + let mut ecu = ecu_of(&s); + if bc.extended_session { + ecu = ecu.with_extended_session(); + } + Ok((ecu, s)) +} + +fn hex_str(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02X}")).collect() +} + +fn block_cmd(action: BmwBlock) -> Result<(), String> { + match action { + BmwBlock::Read { bc, did } => { + let (mut ecu, s) = block_ecu(&bc)?; + let b = ecu.read_block(did).map_err(|e| e.to_string())?; + println!( + "ECU {:#04X} block {did:#06X} ({} bytes): {}", + s.target, + b.len(), + hex_str(&b) + ); + Ok(()) + } + BmwBlock::Write { + bc, + did, + hex, + store, + } => { + let new = unhex(hex.trim()).ok_or("--hex must be an even number of hex digits")?; + let (mut ecu, s) = block_ecu(&bc)?; + let change = plan_block_change(&mut ecu, did, new).map_err(|e| e.to_string())?; + block_apply( + &mut ecu, + &s, + &backup_store(&store), + &change, + bc.conn.simulate, + ) + } + BmwBlock::Restore { bc, id, store } => { + let store = backup_store(&store); + let (mut ecu, s) = block_ecu(&bc)?; + let change = plan_block_restore(&mut ecu, &store, &id).map_err(|e| e.to_string())?; + block_apply(&mut ecu, &s, &store, &change, bc.conn.simulate) + } + } +} + +fn block_apply( + ecu: &mut CliEcu, + s: &Session, + store: &opendiag_services::BackupStore, + change: &BlockChange, + simulate: bool, +) -> Result<(), String> { + println!( + "ECU {:#04X} block {:#06X} ({} bytes)", + s.target, + change.id, + change.old.len() + ); + println!(" now: {}", hex_str(&change.old)); + println!(" new: {}", hex_str(&change.new)); + let diff = change.differing_offsets(); + if change.old.len() == change.new.len() { + println!(" {} byte(s) differ, at offset(s) {:?}", diff.len(), diff); + } + if change.old == change.new { + println!("The new block equals the current one; nothing to do."); + return Ok(()); + } + println!( + "The whole current block is saved to {} first, and the ECU is read back afterwards.", + store.path().display() + ); + println!( + "Coding errors can make an ECU misbehave. This has only been tested against a simulator." + ); + if !simulate { + println!("Keep the ignition on and a battery charger connected until this finishes."); + } + if !confirm()? { + println!("Cancelled; nothing was changed."); + return Ok(()); + } + let done = apply_block_change(ecu, store, change, &BlockConfirmation::for_change(change)) + .map_err(|e| e.to_string())?; + println!( + "Written and verified by reading it back. Backup {} is in {}.", + done.backup_id, + store.path().display() + ); + println!( + "To undo: opendiag bmw block restore {} (same connection options).", + done.backup_id + ); + Ok(()) +} diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index 3747b9e..a4411f9 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -1113,6 +1113,18 @@ fn backup_list(store: &StoreArg) -> Result<(), String> { for c in &r.codes { println!(" was: {c}"); } + } else if r.kind == "block_write" { + println!( + "{} {} UTC {} block {:#06X} written [{:?}]{restore}", + r.id, + format_unix_utc(r.created_unix), + r.module.as_deref().unwrap_or(&r.protocol), + r.block.unwrap_or(0), + r.status + ); + println!(" was: {}", r.old_hex.as_deref().unwrap_or("?")); + println!(" now: {}", r.new_hex.as_deref().unwrap_or("?")); + println!(" undo: opendiag bmw block restore {}", r.id); } else { println!( "{} {} UTC {} module {:#04X} {} channel {}: {} -> {} [{:?}]{restore}", diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index eb0cea3..32ce002 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1288,3 +1288,87 @@ fn bmw_simulated_live_logs_raw_csv() { assert!(out.contains("0xBEEF,absent,"), "{out}"); assert_eq!(out.lines().count(), 5, "{out}"); } + +fn bmw_block_args<'a>(sub: &'a [&'a str], backups: &'a str) -> Vec<&'a str> { + let mut v = vec!["bmw", "block"]; + v.extend_from_slice(sub); + v.extend_from_slice(&["--simulate", "--target", "0x12", "--backup-file", backups]); + v +} + +#[test] +fn bmw_block_read_and_guarded_write_in_the_simulator() { + let backups = temp_file("bmw-block.jsonl"); + let _ = std::fs::remove_file(&backups); + let b = backups.to_str().unwrap(); + let (ok, out, err) = run( + &[ + "bmw", + "block", + "read", + "--simulate", + "--target", + "0x12", + "--did", + "0x2000", + ], + "", + ); + assert!(ok, "{err}"); + assert!(out.contains("0102030405060708"), "{out}"); + + let args = bmw_block_args( + &["write", "--did", "0x2000", "--hex", "010203AA05060708"], + b, + ); + // Not YES: nothing written, no backup. + let (ok, out, _) = run(&args, "no\n"); + assert!(ok); + assert!(out.contains("Cancelled"), "{out}"); + assert!(out.contains("offset(s) [3]"), "{out}"); + assert!(!backups.exists()); + // YES: backed up, written, verified. + let (ok, out, err) = run(&args, "YES\n"); + assert!(ok, "{err}"); + assert!(out.contains("verified by reading it back"), "{out}"); + let text = std::fs::read_to_string(&backups).unwrap(); + assert!(text.contains("\"old_hex\":\"0102030405060708\""), "{text}"); + // The backup list shows it with the undo hint. + let (ok, out, _) = run(&["backup", "list", "--backup-file", b], ""); + assert!(ok); + assert!( + out.contains("0x2000") && out.contains("bmw block restore"), + "{out}" + ); + let _ = std::fs::remove_file(&backups); +} + +#[test] +fn bmw_block_write_refuses_identity_data_wrong_length_and_has_no_yes_flag() { + let backups = temp_file("bmw-block-refused.jsonl"); + let _ = std::fs::remove_file(&backups); + let b = backups.to_str().unwrap(); + let (ok, _, err) = run( + &bmw_block_args(&["write", "--did", "0xF190", "--hex", "00"], b), + "YES\n", + ); + assert!(!ok); + assert!(err.contains("identification"), "{err}"); + let (ok, _, err) = run( + &bmw_block_args(&["write", "--did", "0x2000", "--hex", "0102"], b), + "YES\n", + ); + assert!(!ok); + assert!(err.contains("length must not change"), "{err}"); + let (ok, _, err) = run( + &bmw_block_args(&["write", "--did", "0x2000", "--hex", "zz"], b), + "YES\n", + ); + assert!(!ok && err.contains("hex"), "{err}"); + let (ok, _, err) = run( + &bmw_block_args(&["write", "--did", "0x2000", "--hex", "00", "--yes"], b), + "", + ); + assert!(!ok && err.contains("--yes"), "{err}"); + assert!(!backups.exists()); +} diff --git a/crates/opendiag-services/src/backup.rs b/crates/opendiag-services/src/backup.rs index 65c99d6..65d1ba7 100644 --- a/crates/opendiag-services/src/backup.rs +++ b/crates/opendiag-services/src/backup.rs @@ -56,6 +56,16 @@ pub struct BackupRecord { /// `note`, which a later status change replaces. Absent in older records. #[serde(default)] pub module: Option, + /// For `block_write` records: the data identifier of the block that was written. + #[serde(default)] + pub block: Option, + /// For `block_write` records: the whole block before the change, as hex. + /// This is what a restore puts back. + #[serde(default)] + pub old_hex: Option, + /// For `block_write` records: the whole block as written, as hex. + #[serde(default)] + pub new_hex: Option, } /// Add to `msg` that the backup record could not be updated, if updating it failed. @@ -182,6 +192,9 @@ impl BackupStore { restores: new.restores, codes: Vec::new(), module: None, + block: None, + old_hex: None, + new_hex: None, }; self.append(&rec)?; Ok(rec) @@ -211,6 +224,45 @@ impl BackupStore { restores: None, codes, module: Some(module), + block: None, + old_hex: None, + new_hex: None, + }; + self.append(&rec)?; + Ok(rec) + } + + /// Record a whole-block change durably, status `planned`, *before* it is sent. + /// Holds the complete old block, so the change can be undone byte for byte. + #[allow(clippy::too_many_arguments)] + pub fn plan_block( + &self, + protocol: &str, + module_address: u8, + module: String, + block: u16, + old: &[u8], + new: &[u8], + restores: Option, + ) -> Result { + let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02X}")).collect::(); + let rec = BackupRecord { + id: self.next_id()?, + created_unix: Self::now_unix(), + protocol: protocol.to_string(), + module_address, + kind: "block_write".to_string(), + channel: 0, + old_value: 0, + new_value: 0, + status: BackupStatus::Planned, + note: None, + restores, + codes: Vec::new(), + module: Some(module), + block: Some(block), + old_hex: Some(hex(old)), + new_hex: Some(hex(new)), }; self.append(&rec)?; Ok(rec) diff --git a/crates/opendiag-services/src/block.rs b/crates/opendiag-services/src/block.rs new file mode 100644 index 0000000..d025adf --- /dev/null +++ b/crates/opendiag-services/src/block.rs @@ -0,0 +1,252 @@ +//! Guarded writes of a whole data block (raw coding data), over any protocol +//! that can read and write a block by identifier. +//! +//! The flow, in order. Any failure before step 5 means **nothing was sent**: +//! +//! 1. the confirmation must be for exactly the change that was shown; +//! 2. refuse blocks that must never be written, and changes that are not +//! changes (identical) or that alter the block's length; +//! 3. the block is re-read; if it no longer equals what was shown, abort; +//! 4. the complete old block is written to the backup file and flushed; +//! 5. the write is sent, using a [`WriteToken`] only this crate can create; +//! 6. the block is read back and must equal what was written. A mismatch is +//! recorded as `verification_failed` and reported with the backup id. +//! +//! Nothing is rewritten automatically: putting the old block back is itself a +//! write, so it is a separate guarded change ([`plan_block_restore`]). +//! +//! This layer is raw bytes only. It knows nothing about what the bytes mean. + +use opendiag_core::{Error, Result}; + +use crate::adaptation::WriteToken; +use crate::backup::{with_record_failure, BackupStatus, BackupStore}; + +/// A module with readable and writable data blocks. +pub trait BlockAccess { + fn protocol(&self) -> &'static str; + fn module_address(&self) -> u8; + fn describe(&self) -> String; + /// Read a block. Never writes. + fn read_block(&mut self, id: u16) -> Result>; + /// Whether this block may be written at all (identity data never may). + fn writable(&self, id: u16) -> std::result::Result<(), String>; + /// Write a block. Needs the token the guarded flow issues. + fn write_block(&mut self, token: &WriteToken, id: u16, data: &[u8]) -> Result<()>; +} + +/// What would change: one block, from its current bytes to new ones. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlockChange { + pub id: u16, + pub old: Vec, + pub new: Vec, + /// Backup id this change puts back, when it is a restore. + pub restores: Option, +} + +impl BlockChange { + /// Byte offsets where old and new differ. + pub fn differing_offsets(&self) -> Vec { + self.old + .iter() + .zip(&self.new) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(i, _)| i) + .collect() + } +} + +/// A person's agreement to one specific change. A front end creates it after +/// showing the diff; [`apply_block_change`] refuses one that does not match. +#[derive(Debug)] +pub struct BlockConfirmation { + change: BlockChange, +} + +impl BlockConfirmation { + pub fn for_change(change: &BlockChange) -> Self { + Self { + change: change.clone(), + } + } +} + +fn protocol(msg: impl Into) -> Error { + Error::Protocol(format!("block write: {}", msg.into())) +} + +/// Read the current block and describe the change. Writes nothing. +pub fn plan_block_change( + access: &mut dyn BlockAccess, + id: u16, + new: Vec, +) -> Result { + access.writable(id).map_err(protocol)?; + let old = access.read_block(id)?; + Ok(BlockChange { + id, + old, + new, + restores: None, + }) +} + +/// Describe putting a recorded block back. Writes nothing. +pub fn plan_block_restore( + access: &mut dyn BlockAccess, + store: &BackupStore, + backup_id: &str, +) -> Result { + let rec = store + .get(backup_id)? + .ok_or_else(|| protocol(format!("no backup record `{backup_id}`")))?; + if rec.kind != "block_write" { + return Err(protocol(format!("`{backup_id}` is not a block backup"))); + } + if rec.protocol != access.protocol() || rec.module_address != access.module_address() { + return Err(protocol(format!( + "`{backup_id}` was taken from a different module ({})", + rec.module.as_deref().unwrap_or("unknown") + ))); + } + let (Some(id), Some(old_hex)) = (rec.block, rec.old_hex.as_deref()) else { + return Err(protocol(format!("`{backup_id}` holds no block data"))); + }; + let new = unhex(old_hex).ok_or_else(|| protocol("the recorded block data is not valid hex"))?; + access.writable(id).map_err(protocol)?; + let old = access.read_block(id)?; + Ok(BlockChange { + id, + old, + new, + restores: Some(backup_id.to_string()), + }) +} + +/// Parse a hex string (no separators) into bytes. +pub fn unhex(s: &str) -> Option> { + if s.len() % 2 != 0 || !s.is_ascii() { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) + .collect() +} + +/// A change that was written and read back correctly. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlockApplied { + pub backup_id: String, +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02X}")).collect() +} + +/// Write a block with a confirmation, a durable backup and a read-back check. +pub fn apply_block_change( + access: &mut dyn BlockAccess, + store: &BackupStore, + change: &BlockChange, + confirmation: &BlockConfirmation, +) -> Result { + // 1. Exactly what was shown. + if &confirmation.change != change { + return Err(protocol( + "the confirmation is for a different change than the one being applied", + )); + } + // 2. Allowed, a real change, same size. + access.writable(change.id).map_err(protocol)?; + if change.old == change.new { + return Err(protocol( + "the new block equals the current one; nothing to do", + )); + } + if change.old.len() != change.new.len() { + return Err(protocol(format!( + "the new block has {} bytes but the current one has {}; the length must not change", + change.new.len(), + change.old.len() + ))); + } + // 3. The block must still be what the person saw. + let current = access.read_block(change.id)?; + if current != change.old { + return Err(protocol( + "the block changed since it was shown; nothing was written", + )); + } + // 4. Durable backup first. If this fails, nothing has been sent. + let rec = store.plan_block( + access.protocol(), + access.module_address(), + access.describe(), + change.id, + &change.old, + &change.new, + change.restores.clone(), + )?; + let id = rec.id; + + // 5. Write. From here on the module may have changed. + let token = WriteToken::new(); + if let Err(e) = access.write_block(&token, change.id, &change.new) { + let update = store.set_status( + &id, + BackupStatus::SaveFailed, + Some(format!("write failed: {e}")), + ); + return Err(protocol(with_record_failure( + format!("the module did not accept the block: {e} (backup {id})"), + &id, + update, + ))); + } + + // 6. Read it back. + let (status, note, problem) = match access.read_block(change.id) { + Ok(b) if b == change.new => (BackupStatus::Verified, None, None), + Ok(b) => ( + BackupStatus::VerificationFailed, + Some(format!( + "read back {} instead of {}", + hex(&b), + hex(&change.new) + )), + Some(format!( + "the block reads back differently from what was written (backup {id} holds the \ + original; put it back with a restore)" + )), + ), + Err(e) => ( + BackupStatus::VerificationFailed, + Some(format!("could not read back: {e}")), + Some(format!( + "written, but the block could not be read back to verify it ({e}) (backup {id})" + )), + ), + }; + let update = store.set_status(&id, status, note); + if let Some(msg) = problem { + return Err(protocol(with_record_failure(msg, &id, update))); + } + if let Err(e) = update { + return Err(protocol(format!( + "the block WAS written and verified, but backup {id} could not be updated: {e}. \ + It still says `planned`" + ))); + } + if let Some(orig) = &change.restores { + // The restore itself succeeded and is recorded under its own id. + let _ = store.set_status( + orig, + BackupStatus::Restored, + Some(format!("restored by {id}")), + ); + } + Ok(BlockApplied { backup_id: id }) +} diff --git a/crates/opendiag-services/src/lib.rs b/crates/opendiag-services/src/lib.rs index e6e3356..6566efe 100644 --- a/crates/opendiag-services/src/lib.rs +++ b/crates/opendiag-services/src/lib.rs @@ -5,6 +5,7 @@ pub mod adaptation; pub mod backup; +pub mod block; pub mod demo; pub mod fault_clear; mod kw1281_module; @@ -17,6 +18,10 @@ pub use adaptation::{ WriteConfirmation, WriteToken, }; pub use backup::{BackupRecord, BackupStatus, BackupStore}; +pub use block::{ + apply_block_change, plan_block_change, plan_block_restore, unhex, BlockAccess, BlockApplied, + BlockChange, BlockConfirmation, +}; pub use fault_clear::{apply_clear, plan_clear, ClearConfirmation, ClearOutcome, FaultAccess}; pub use kw1281_module::Kw1281Module; pub use kwp_module::KwpModule; diff --git a/crates/opendiag-services/tests/write_safety.rs b/crates/opendiag-services/tests/write_safety.rs index 969e32c..8d34d59 100644 --- a/crates/opendiag-services/tests/write_safety.rs +++ b/crates/opendiag-services/tests/write_safety.rs @@ -27,8 +27,9 @@ use opendiag_proto::tp20::sim::Tp20Sim; use opendiag_proto::tp20::{Tp20Config, Tp20KwpClient, Tp20Link}; use opendiag_proto::uds::{UdsClient, UdsConfig}; use opendiag_services::{ - apply_change, apply_clear, plan_change, plan_clear, BackupStore, ClearConfirmation, - Kw1281Module, KwpModule, Module, WriteConfirmation, + apply_block_change, apply_change, apply_clear, plan_block_change, plan_change, plan_clear, + BackupStore, BlockAccess, BlockConfirmation, ClearConfirmation, Kw1281Module, KwpModule, + Module, WriteConfirmation, }; use opendiag_transport::{Capabilities, Frame, Simulator, Transport}; @@ -410,15 +411,42 @@ fn run_bmw_clear(store: &BackupStore, seed: u64, watch: &Watch) { ); } +fn run_bmw_block_write(store: &BackupStore, seed: u64, watch: &Watch) { + let stream = LoopbackStream::new(VirtualVehicle::demo()) + .on_write(watch.hook(store.path(), "\"kind\":\"block_write\"")); + let stream = MutBytes { + inner: stream, + rng: Rng(seed ^ 0xB7), + rate: rate(seed), + }; + let gw = HsfzGateway::new(stream, FakeClock::new(), 0xF4); + let mut ecu = BmwEcu::new(gw.link(0x12), 0x12, UdsConfig::default()); + let Ok(old) = ecu.read_block(0x2000) else { + return; + }; + let mut new = old.clone(); + new[3] = 0xAA; + let Ok(change) = plan_block_change(&mut ecu, 0x2000, new) else { + return; + }; + let _ = apply_block_change( + &mut ecu, + store, + &change, + &BlockConfirmation::for_change(&change), + ); +} + type Run = fn(&BackupStore, u64, &Watch); -const FLOWS: [(&str, Run); 6] = [ +const FLOWS: [(&str, Run); 7] = [ ("clear over KW1281", run_kw1281_clear), ("clear over KWP2000 (K-line)", run_kwp_clear), ("adaptation over KW1281", run_kw1281_adaptation), ("clear over UDS (ISO-TP)", run_uds_clear), ("clear over KWP2000 over TP2.0", run_tp20_clear), ("clear over BMW HSFZ (UDS)", run_bmw_clear), + ("block write over BMW HSFZ (UDS)", run_bmw_block_write), ]; #[test] diff --git a/docs/bmw.md b/docs/bmw.md index 431f3a9..6f50ed7 100644 --- a/docs/bmw.md +++ b/docs/bmw.md @@ -1,6 +1,6 @@ # BMW F-series (ENET / HSFZ) -**Status: simulator-tested only.** None of this has run against a real car, gateway or ENET cable. Read-only, except `dtc clear`, which uses the guarded flow below. +**Status: simulator-tested only.** None of this has run against a real car, gateway or ENET cable. Read-only by default. The only writes are `dtc clear` and `block write/restore`, both through the guarded flow below. ```bash opendiag bmw discover # find gateways (UDP broadcast, port 6811) @@ -9,6 +9,9 @@ opendiag bmw did --target 0x12 0xF190 # read one data identifier from one ECU opendiag bmw scan [--all] # which ECUs answer, and how many fault codes each holds opendiag bmw dtc read --target 0x12 # stored fault codes (raw hex + status flags) opendiag bmw dtc clear --target 0x12 # guarded: snapshot, typed YES, clear, re-read +opendiag bmw block read --target 0x12 --did 0x2000 # raw block as hex +opendiag bmw block write --target 0x12 --did 0x2000 --hex ... # guarded write +opendiag bmw block restore b0003 --target 0x12 # put a backed-up block back opendiag bmw live --target 0x12 --did 0x4002,0xF190 --samples 20 # raw CSV log opendiag bmw ident --simulate # no car: built-in virtual BMW (works for every command) ``` @@ -46,6 +49,32 @@ write mode. - **ECU address table** (`crates/opendiag-bmw/src/ecus.rs`): six names, **NOT VERIFIED**, labels only. It does not affect what is sent. +### Step 3: raw block write (guarded) + +`block write` replaces one data block, addressed by a data identifier **you** supply, with new bytes of the same +length. It is raw bytes only: nothing here knows what the bytes mean, and no DID for coding data is built in, +because we have no verified one. Decoding (FDL/CAFD) is design only and will load from your own local +PSdZData path; BMW data is never bundled (see [legal.md](legal.md)). + +The flow (`opendiag-services/src/block.rs`, shared by any protocol): + +1. the confirmation must be bound to the exact change shown (old bytes, new bytes, DID); +2. identification identifiers (`0xF100`-`0xF1FF`, VIN and part numbers), identical blocks and length changes are refused; +3. the block is re-read and must still equal what was shown; +4. the complete old block is written to the backup file and flushed. If that fails, nothing is sent; +5. the write is sent (a `WriteToken` only this flow can create); +6. the block is read back and must equal what was written. Otherwise the backup is marked `verification_failed` + and the error names it. Nothing is rewritten automatically. + +`block restore ` is the same guarded flow in reverse, from the stored old block, and marks the original +`restored`. It refuses a backup taken from a different ECU. There is no `--yes`. The block-write path is part of +`write_safety.rs`. Programming sessions and flash services stay refused at the link; `--extended-session` opens +`0x10 03` only, and is off by default because whether it is needed is unverified. + +**Do not use this on a real car yet.** The write itself, the DID, the ECU's session and any security-access +requirement are all unverified. Keep a charger connected and the ignition on, and expect to need a capture from +your own car first. + ## Verified vs unverified Verified against public sources (see [sources.md](sources.md)): @@ -73,3 +102,5 @@ Verified against public sources (see [sources.md](sources.md)): - How a real gateway reports an address with no ECU (silence or an error frame). The scan treats both as absent. - The names in the ECU address table. - Whether `0x14 FFFFFF` clears every ECU's codes on a real F30, or only some groups. +- Which data identifiers hold coding blocks on an F-series ECU, whether `0x2E` on them needs an extended session + or security access, and whether the ECU accepts a whole-block write. Not guessed anywhere: you pass the DID. From fcc333486b5817d617c11323f239f6aca5d1445e Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:58:30 +0000 Subject: [PATCH 5/9] docs(bmw): design for coding decode, Vehicle trait and launcher Design only. BMW data is read from a user-supplied local path, never bundled; the decoder sits behind a trait and cannot write; the Vehicle trait is extracted from the two implementations; brand is chosen at launch. Co-Authored-By: Claude Sonnet 5.5 --- PROJECT_PLAN.md | 2 +- docs/design-bmw-coding-and-launcher.md | 152 +++++++++++++++++++++++++ 2 files changed, 153 insertions(+), 1 deletion(-) create mode 100644 docs/design-bmw-coding-and-launcher.md diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md index 683848e..1bc5403 100644 --- a/PROJECT_PLAN.md +++ b/PROJECT_PLAN.md @@ -105,7 +105,7 @@ Key design points: ### Phase B - BMW F-series over ENET (branch `feat/bmw-backend`) -Status: steps 1-3 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Step 3 added: guarded raw block write/restore (`opendiag-services::block`, backup-first, read-back verify, in `write_safety.rs`; DID supplied by the user). Next: FDL decode (design only), local-only PSdZData/CAFD decoding, and the `VehicleBackend` trait extracted from the two implementations. See [docs/bmw.md](docs/bmw.md). +Status: steps 1-3 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Step 3 added: guarded raw block write/restore (`opendiag-services::block`, backup-first, read-back verify, in `write_safety.rs`; DID supplied by the user). Next: see the design for coding decode, `Vehicle` and the launcher in [docs/design-bmw-coding-and-launcher.md](docs/design-bmw-coding-and-launcher.md) (design only). See [docs/bmw.md](docs/bmw.md). ## 5. Repo layout diff --git a/docs/design-bmw-coding-and-launcher.md b/docs/design-bmw-coding-and-launcher.md new file mode 100644 index 0000000..bdd6a3a --- /dev/null +++ b/docs/design-bmw-coding-and-launcher.md @@ -0,0 +1,152 @@ +# Design: BMW coding decode, `VehicleBackend`, and the launcher + +**Status: design only. No code in this document exists yet.** It covers the last three items of the BMW brief. +Everything about BMW file formats below is *unknown to us* and is stated as such; the design is shaped so that +it does not depend on guesses. + +## 1. Decoding coding blocks from the user's own local files (FDL / CAFD) + +### Goal +Turn the raw bytes `opendiag bmw block read` returns into named options ("this bit enables X"), and let a user +change an option by name instead of by hand-editing hex, through the **same guarded block flow** (backup, +typed confirmation of the exact diff, read-back verify). Decoding never bypasses that flow. + +### Hard rules (from CLAUDE.md and `docs/legal.md`) +- **Never bundle, commit, copy or redistribute BMW proprietary data** (PSdZData, CAFD files, FDL tables). Not in + `data/`, not in test fixtures, not in the repo history, not in release artifacts. +- The loader reads **only a path the user supplies** (`--bmw-data ` or `OPENDIAG_BMW_DATA`). No + default search path, no download, no network fetch. +- BMW data is **not** CC0 and does not enter `opendiag-data`. `data validate` and `load_data()` never see it. +- Nothing decoded from it is written to disk by OpenDiag except in the user's own backup/log files. No cache + directory of extracted definitions. +- Tests use **synthetic fixtures we author ourselves** in our own format. No test may need real BMW files. + +### What we do not know (and will not guess) +The binary layout of CAFD/FDL files, how a CAFD is matched to an ECU and I-level, and which DIDs carry the +coding blocks. We have no verified public specification for any of these. So the design has two stages: + +1. **Format investigation, done by the user's own files, before any decoder is written.** A read-only + `opendiag bmw data inspect ` that prints only structural facts (size, magic bytes, section offsets) + so the format can be worked out from the user's own files. Anything learned goes into `docs/sources.md` + with how it was derived. If a format cannot be established from public sources or the user's own + observation, the decoder is not built. That is an acceptable outcome. +2. **Decoder behind a trait** (below), so the rest of the system is written and tested without any real file. + +### Proposed structure +New crate `opendiag-bmw-coding` (keeps BMW-file knowledge out of `opendiag-bmw`'s protocol code): + +```rust +/// One named option inside a block, described in OUR schema. +pub struct CodingField { name: String, bit_offset: u32, bit_len: u32, values: Vec<(u64, String)> } + +pub trait CodingSource { + /// Field layout for one block of one ECU, if this source knows it. + fn layout(&self, ecu: u8, i_level: &str, block: u16) -> Result>>; +} + +pub fn decode(layout: &[CodingField], block: &[u8]) -> Vec; +pub fn encode_change(layout: &[CodingField], block: &[u8], field: &str, value: &str) -> Result>; +``` + +- `encode_change` returns a **new full block** (same length). The caller hands that to + `plan_block_change`, so everything after is the existing guarded flow. The decoder cannot write. +- Two `CodingSource` implementations: + - `SyntheticSource`: loads our own open JSON format (`opendiag-bmw-coding/0`, with a provenance field, + separate from `opendiag-data`'s schema). Used by tests and by anyone who writes definitions by hand. + - `LocalFilesSource`: reads the user's own files from the supplied path. Built only after stage 1 succeeds. +- Unknown field or value: error, never a guess. A block whose length does not match the layout is not decoded. +- Decoded values are display aids. The authority on what gets written is the byte diff shown to the user. + +### CLI sketch +``` +opendiag bmw coding show --target 0x12 --did --bmw-data +opendiag bmw coding set --target 0x12 --did --bmw-data --field NAME --value VALUE +``` +`set` prints the named change *and* the byte diff, then goes through the typed confirmation as `block write`. + +### Safety additions specific to decoding +- Refuse `set` when the source cannot match the ECU's current I-level exactly. A layout for the wrong software + level could flip the wrong bit. +- Refuse to run decode on a block whose read-back differs between two consecutive reads. +- Show raw hex before and after in every confirmation, not just the names. + +## 2. Extracting `VehicleBackend` + +### Principle +Extract the trait from the two working implementations; do not design it ahead of them. We now have both. + +### What the two implementations actually share +| Need | VAG today | BMW today | +|---|---|---| +| Identify | `Module::identify` -> `Ident` | `read_ident` -> `BmwIdent` (VIN, raw I-level, raw FA) | +| Fault codes | `Module::read_dtcs` / `FaultAccess` | same trait, hex text | +| Guarded clear | `FaultAccess` + `apply_clear` | same | +| Keep-alive | `Module::keep_alive` | same | +| Multi-ECU scan | none (one module at a time) | `scan` through the gateway | +| Live data | `LiveData::read_group` (KW1281 groups) | `log_dids_csv` (DIDs) | +| Block writes | none | `BlockAccess` | +| Adaptation | `AdaptationAccess` (KW1281) | none | + +Shared and already abstracted: `Module`, `FaultAccess`, the backup store, the clear flow. Genuinely different: +connection setup, how ECUs are enumerated, live data shape, and coding. + +### Proposed trait (to be written only when a launcher needs it) +```rust +pub trait Vehicle { + fn brand(&self) -> Brand; // Vag | Bmw + fn connect(&mut self, opts: &ConnectOptions) -> Result<()>; + fn identify(&mut self) -> Result; // vin + brand-specific extras as labelled lines + fn scan(&mut self) -> Result>; // address/name/fault count + fn ecu(&mut self, id: EcuId) -> Result<&mut dyn Module>; + fn keep_alive(&mut self) -> Result<()>; +} +``` +- `ecu()` returns the existing `Module`, so every front end keeps using `faults()`, `plan_clear`, etc. +- Optional capabilities stay **optional traits reached through accessors** (`block()`, `adaptation()`, + `live()`), exactly as `Module::adaptation()` already works. No brand-wide "does everything" interface, and + no default method that pretends a capability exists. +- `VehicleIdent` carries VIN plus a list of labelled `(label, value, verified: bool)` lines, so unverified BMW + items (I-level, FA) stay visibly marked in every front end. +- Live data is **not** unified in v1: KW1281 groups and DID logging stay separate. Forcing them together would + invent an abstraction neither implementation justifies. +- `opendiag-session` (a VAG whole-vehicle scan) was never built. The trait must not assume it; VAG's `scan` + can return a single entry until that exists. + +### Where it lives +A small `opendiag-vehicle` crate depending on `opendiag-services` and re-used by CLI and `serve`. VAG and BMW +backends are adapters in their own crates or a thin module each, so neither crate depends on the other. + +## 3. Launcher + +### Selection +1. `--brand vag|bmw` on the CLI. Explicit always wins. +2. `serve --brand vag|bmw`: **chosen at launch**, not changed from inside a page. The web handler is GET-only + and holds one module; a brand switch mid-session would mean tearing down a live connection from a GET. + The page shows which brand it is serving. +3. Optional auto-detect, **off unless asked** (`--brand auto`): an ENET discovery reply (UDP 6811) on the + local link means BMW; a K-line/CAN adapter selected means VAG. This is a hint, not a decision: the chosen + brand is printed before anything is sent, and ambiguity (both present) is an error asking for `--brand`. + +### Migration path (no behaviour change to VAG) +- Existing commands (`scan`, `dtc`, `clear`, `kw1281 ...`) stay as they are. `opendiag bmw ...` stays. +- `--brand` is added first as a pure router to the existing code paths. Only after that does anything move + onto `Vehicle`. +- Each step is a separate commit with the full suite green. The VAG tests are the safety net, as with the + `MessageLink` refactor. + +### Out of scope +Any GUI launcher (that waits for the Tauri app), an HTTP API, and cross-brand features. + +## 4. Order of work and what blocks it + +1. `--brand` router and `serve --brand` (no new abstraction; low risk, can start now). +2. `Vehicle` extraction, driven by step 1's actual call sites. +3. Synthetic coding format and `encode_change`/`decode` with synthetic fixtures (can start now, no BMW data). +4. `bmw data inspect` and the real-file decoder: **blocked on the user's own files and on a car or capture** + to confirm coding DIDs. Not started until both exist. + +## 5. Open questions for the user +- Are you willing to share *structural* facts from your own PSdZData (sizes, headers) so stage 1 can start? + Never the files themselves. +- Is `--brand auto` wanted at all, or is an explicit flag enough? +- Should `serve` stay one-brand-per-process, or is running two instances acceptable? From 653d78f7b93a78b8fd540d8613b53f10ef8e2b31 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:02:54 +0000 Subject: [PATCH 6/9] feat(cli,bmw): --brand router, bmw serve, and name-based coding from our own format - global --brand vag|bmw|auto: no flag changes nothing; bmw routes serve; auto uses one ENET discovery broadcast and prints its choice - opendiag bmw serve (read-only web page for one ECU); serve loop shared - new crate opendiag-bmw-coding: strict opendiag-bmw-coding/0 definitions with provenance, decode, encode_change (only the field's bits change) - opendiag bmw coding show|set: refuses unknown fields/values, wrong length, software-level mismatch and unstable reads; set uses the guarded block flow - synthetic example in docs/examples; BMW's own files are not read Simulator-tested only. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 10 + Cargo.toml | 1 + PROJECT_PLAN.md | 2 +- crates/opendiag-bmw-coding/Cargo.toml | 16 + crates/opendiag-bmw-coding/src/lib.rs | 473 ++++++++++++++++++++++++ crates/opendiag-cli/Cargo.toml | 1 + crates/opendiag-cli/src/bmw.rs | 169 +++++++++ crates/opendiag-cli/src/main.rs | 176 ++++++++- crates/opendiag-cli/tests/cli.rs | 142 +++++++ docs/bmw.md | 21 ++ docs/design-bmw-coding-and-launcher.md | 2 + docs/examples/bmw-coding-synthetic.json | 16 + 12 files changed, 1025 insertions(+), 4 deletions(-) create mode 100644 crates/opendiag-bmw-coding/Cargo.toml create mode 100644 crates/opendiag-bmw-coding/src/lib.rs create mode 100644 docs/examples/bmw-coding-synthetic.json diff --git a/Cargo.lock b/Cargo.lock index c68cb1c..e595b2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -371,6 +371,15 @@ dependencies = [ "opendiag-services", ] +[[package]] +name = "opendiag-bmw-coding" +version = "0.1.0" +dependencies = [ + "opendiag-core", + "serde", + "serde_json", +] + [[package]] name = "opendiag-cli" version = "0.1.0" @@ -378,6 +387,7 @@ dependencies = [ "clap", "getrandom", "opendiag-bmw", + "opendiag-bmw-coding", "opendiag-core", "opendiag-data", "opendiag-proto", diff --git a/Cargo.toml b/Cargo.toml index 81220a0..2f175aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "crates/opendiag-services", "crates/opendiag-data", "crates/opendiag-bmw", + "crates/opendiag-bmw-coding", "crates/opendiag-cli", "crates/opendiag-web", ] diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md index 1bc5403..f89ac15 100644 --- a/PROJECT_PLAN.md +++ b/PROJECT_PLAN.md @@ -105,7 +105,7 @@ Key design points: ### Phase B - BMW F-series over ENET (branch `feat/bmw-backend`) -Status: steps 1-3 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Step 3 added: guarded raw block write/restore (`opendiag-services::block`, backup-first, read-back verify, in `write_safety.rs`; DID supplied by the user). Next: see the design for coding decode, `Vehicle` and the launcher in [docs/design-bmw-coding-and-launcher.md](docs/design-bmw-coding-and-launcher.md) (design only). See [docs/bmw.md](docs/bmw.md). +Status: steps 1-3 done and **simulator-tested only**. New crate `opendiag-bmw`: HSFZ framing, TCP gateway session, UDP discovery, VIN / I-level / FA reads, mock gateway, `opendiag bmw` CLI. UDS now runs over a `MessageLink` trait so HSFZ reuses the VAG-proven client. Step 2 added: ECU scan, BMW hex DTC read and guarded clear (in `write_safety.rs`), raw DID live logging, a small unverified ECU address table. Step 3 added: guarded raw block write/restore (`opendiag-services::block`, backup-first, read-back verify, in `write_safety.rs`; DID supplied by the user). Also done: `--brand vag|bmw|auto` router with `serve` for BMW, and `opendiag-bmw-coding` (our own definition format, decode/encode by field name). Next: see the design for the real-file decode, `Vehicle` and the launcher in [docs/design-bmw-coding-and-launcher.md](docs/design-bmw-coding-and-launcher.md) (design only). See [docs/bmw.md](docs/bmw.md). ## 5. Repo layout diff --git a/crates/opendiag-bmw-coding/Cargo.toml b/crates/opendiag-bmw-coding/Cargo.toml new file mode 100644 index 0000000..ec59d85 --- /dev/null +++ b/crates/opendiag-bmw-coding/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "opendiag-bmw-coding" +description = "Name-based view of raw coding blocks, from our own open definition format. Pure: it never talks to an ECU." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] +opendiag-core = { path = "../opendiag-core" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[lints] +workspace = true diff --git a/crates/opendiag-bmw-coding/src/lib.rs b/crates/opendiag-bmw-coding/src/lib.rs new file mode 100644 index 0000000..0ecd554 --- /dev/null +++ b/crates/opendiag-bmw-coding/src/lib.rs @@ -0,0 +1,473 @@ +//! A name-based view of raw coding blocks, from **our own** open definition +//! format (`opendiag-bmw-coding/0`). +//! +//! Pure functions over bytes: nothing here talks to an ECU or writes anything. +//! [`encode_change`] returns a complete new block; handing that to the guarded +//! block flow (`opendiag-services::block`: backup, typed confirmation of the +//! byte diff, read-back verify) is the caller's job, and the only way it gets +//! written. +//! +//! The definitions are community-authored (or written by hand) and carry a +//! provenance field. This crate never reads BMW files: their format is not +//! known to us (see `docs/design-bmw-coding-and-launcher.md`). +//! +//! Bit numbering is our own choice and is part of the format: bit `n` of a +//! block is bit `n % 8` (0 = least significant) of byte `n / 8`, and a field's +//! value is its bits read least-significant first starting at `bit_offset`. + +use std::collections::{BTreeMap, BTreeSet}; + +use opendiag_core::{Error, Result}; +use serde::Deserialize; + +pub const FORMAT_ID: &str = "opendiag-bmw-coding/0"; + +fn err(msg: impl Into) -> Error { + Error::Protocol(format!("coding: {}", msg.into())) +} + +/// One named option inside a block. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodingField { + pub name: String, + pub bit_offset: u32, + pub bit_len: u32, + /// Known values and their labels, sorted by value. Empty: any value is allowed. + pub values: Vec<(u64, String)>, +} + +impl CodingField { + fn mask(&self) -> u64 { + if self.bit_len >= 64 { + u64::MAX + } else { + (1u64 << self.bit_len) - 1 + } + } +} + +/// The fields of one block of one ECU. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlockLayout { + pub ecu: u8, + pub block: u16, + /// Exact block length in bytes. + pub length: usize, + /// The software level this layout is for, if the definition says. + pub i_level: Option, + pub fields: Vec, +} + +/// A field as it reads in a particular block. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecodedField { + pub name: String, + pub raw: u64, + /// The label for `raw`, if the definition has one. + pub label: Option, +} + +/// Where layouts come from. +pub trait CodingSource { + /// The layout for one block. An error says why there is none (unknown block, + /// or the definition is for a different software level). + fn layout(&self, ecu: u8, i_level: Option<&str>, block: u16) -> Result<&BlockLayout>; +} + +// ---- the open JSON format ---- + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FileDef { + format: String, + provenance: String, + blocks: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BlockDef { + ecu: u8, + block: u16, + length: usize, + #[serde(default)] + i_level: Option, + fields: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FieldDef { + name: String, + bit_offset: u32, + bit_len: u32, + #[serde(default)] + values: BTreeMap, +} + +/// Definitions loaded from our own JSON format. +#[derive(Debug, Clone, Default)] +pub struct SyntheticSource { + layouts: Vec, + pub provenance: String, +} + +fn parse_number(s: &str) -> Option { + let s = s.trim(); + match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) { + Some(h) => u64::from_str_radix(h, 16).ok(), + None => s.parse().ok(), + } +} + +impl SyntheticSource { + /// Parse and validate a definition file. Strict: unknown keys, an empty + /// provenance, fields outside the block, overlapping fields, values that do + /// not fit their field and duplicate names are all errors. + pub fn from_json(text: &str) -> Result { + let def: FileDef = serde_json::from_str(text).map_err(|e| err(format!("bad JSON: {e}")))?; + if def.format != FORMAT_ID { + return Err(err(format!( + "format is `{}`, expected `{FORMAT_ID}`", + def.format + ))); + } + if def.provenance.trim().is_empty() { + return Err(err("`provenance` must say where the definitions come from")); + } + let mut layouts: Vec = Vec::new(); + for b in def.blocks { + let at = format!("ECU {:#04X} block {:#06X}", b.ecu, b.block); + if layouts + .iter() + .any(|l| l.ecu == b.ecu && l.block == b.block && l.i_level == b.i_level) + { + return Err(err(format!("{at}: defined twice"))); + } + if b.length == 0 { + return Err(err(format!("{at}: length must be at least 1"))); + } + let total_bits = b.length as u64 * 8; + let mut used = BTreeSet::new(); + let mut names = BTreeSet::new(); + let mut fields = Vec::new(); + for f in b.fields { + if f.name.trim().is_empty() || !names.insert(f.name.clone()) { + return Err(err(format!( + "{at}: empty or duplicate field name `{}`", + f.name + ))); + } + if f.bit_len == 0 || f.bit_len > 64 { + return Err(err(format!( + "{at}: field `{}` bit_len must be 1..=64", + f.name + ))); + } + if u64::from(f.bit_offset) + u64::from(f.bit_len) > total_bits { + return Err(err(format!( + "{at}: field `{}` runs past the end of the block", + f.name + ))); + } + for bit in f.bit_offset..f.bit_offset + f.bit_len { + if !used.insert(bit) { + return Err(err(format!( + "{at}: field `{}` overlaps another field", + f.name + ))); + } + } + let mut field = CodingField { + name: f.name, + bit_offset: f.bit_offset, + bit_len: f.bit_len, + values: Vec::new(), + }; + let mut labels = BTreeSet::new(); + for (k, label) in f.values { + let v = parse_number(&k).ok_or_else(|| { + err(format!( + "{at}: value key `{k}` of `{}` is not a number", + field.name + )) + })?; + if v > field.mask() { + return Err(err(format!( + "{at}: value {v} does not fit in {} bit(s) of `{}`", + field.bit_len, field.name + ))); + } + if !labels.insert(label.clone()) || parse_number(&label).is_some() { + return Err(err(format!( + "{at}: label `{label}` of `{}` is duplicated or looks like a number", + field.name + ))); + } + if field.values.iter().any(|(x, _)| *x == v) { + return Err(err(format!( + "{at}: value {v} of `{}` is listed twice", + field.name + ))); + } + field.values.push((v, label)); + } + field.values.sort(); + fields.push(field); + } + layouts.push(BlockLayout { + ecu: b.ecu, + block: b.block, + length: b.length, + i_level: b.i_level, + fields, + }); + } + Ok(Self { + layouts, + provenance: def.provenance, + }) + } +} + +impl CodingSource for SyntheticSource { + fn layout(&self, ecu: u8, i_level: Option<&str>, block: u16) -> Result<&BlockLayout> { + let candidates: Vec<&BlockLayout> = self + .layouts + .iter() + .filter(|l| l.ecu == ecu && l.block == block) + .collect(); + if candidates.is_empty() { + return Err(err(format!( + "no definition for ECU {ecu:#04X} block {block:#06X}" + ))); + } + // A definition that names a software level is used only for exactly that level. + if let Some(l) = candidates.iter().find(|l| match (&l.i_level, i_level) { + (None, _) => true, + (Some(want), Some(have)) => want == have, + (Some(_), None) => false, + }) { + return Ok(l); + } + let wanted: Vec<&str> = candidates + .iter() + .filter_map(|l| l.i_level.as_deref()) + .collect(); + Err(err(format!( + "the definitions for ECU {ecu:#04X} block {block:#06X} are for software level(s) {wanted:?}, but {} was given; refusing to guess", + i_level.map_or("none".to_string(), |s| format!("`{s}`")) + ))) + } +} + +// ---- decode / encode ---- + +fn check_len(layout: &BlockLayout, block: &[u8]) -> Result<()> { + if block.len() != layout.length { + return Err(err(format!( + "the block has {} bytes but the definition says {}", + block.len(), + layout.length + ))); + } + Ok(()) +} + +fn get_bits(block: &[u8], offset: u32, len: u32) -> u64 { + (0..len).fold(0u64, |acc, i| { + let bit = offset + i; + let b = (block[(bit / 8) as usize] >> (bit % 8)) & 1; + acc | (u64::from(b) << i) + }) +} + +fn set_bits(block: &mut [u8], offset: u32, len: u32, value: u64) { + for i in 0..len { + let bit = offset + i; + let byte = &mut block[(bit / 8) as usize]; + let mask = 1u8 << (bit % 8); + if (value >> i) & 1 == 1 { + *byte |= mask; + } else { + *byte &= !mask; + } + } +} + +/// Read every field of `block`. Refuses a block of the wrong length. +pub fn decode(layout: &BlockLayout, block: &[u8]) -> Result> { + check_len(layout, block)?; + Ok(layout + .fields + .iter() + .map(|f| { + let raw = get_bits(block, f.bit_offset, f.bit_len); + DecodedField { + name: f.name.clone(), + raw, + label: f + .values + .iter() + .find(|(v, _)| *v == raw) + .map(|(_, l)| l.clone()), + } + }) + .collect()) +} + +/// A complete new block with one field changed and every other bit untouched +/// (including bits that no field describes). `value` is a label or a number +/// (decimal or `0x` hex). When the field lists its values, anything else is refused. +pub fn encode_change( + layout: &BlockLayout, + block: &[u8], + field: &str, + value: &str, +) -> Result> { + check_len(layout, block)?; + let f = layout + .fields + .iter() + .find(|f| f.name == field) + .ok_or_else(|| err(format!("no field named `{field}`")))?; + let v = match f.values.iter().find(|(_, l)| l == value) { + Some((v, _)) => *v, + None => parse_number(value).ok_or_else(|| { + let known: Vec<&str> = f.values.iter().map(|(_, l)| l.as_str()).collect(); + err(format!( + "`{value}` is neither a number nor one of {known:?}" + )) + })?, + }; + if v > f.mask() { + return Err(err(format!( + "{v} does not fit in the {} bit(s) of `{field}`", + f.bit_len + ))); + } + if !f.values.is_empty() && !f.values.iter().any(|(x, _)| *x == v) { + return Err(err(format!( + "{v} is not a known value of `{field}`; known: {:?}", + f.values + ))); + } + let mut out = block.to_vec(); + set_bits(&mut out, f.bit_offset, f.bit_len, v); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + const DEF: &str = r#"{ + "format": "opendiag-bmw-coding/0", + "provenance": "synthetic test data written for OpenDiag; not from any car", + "blocks": [{ + "ecu": 18, "block": 8192, "length": 4, "i_level": "TEST-00", + "fields": [ + {"name": "mode", "bit_offset": 0, "bit_len": 2, "values": {"0": "off", "1": "eco", "2": "sport"}}, + {"name": "flag", "bit_offset": 7, "bit_len": 1, "values": {"0": "no", "1": "yes"}}, + {"name": "limit", "bit_offset": 12, "bit_len": 8} + ] + }] + }"#; + + fn src() -> SyntheticSource { + SyntheticSource::from_json(DEF).unwrap() + } + + fn layout() -> BlockLayout { + src().layout(0x12, Some("TEST-00"), 0x2000).unwrap().clone() + } + + #[test] + fn decodes_fields_across_byte_boundaries() { + // mode=2 (bits0-1), flag=1 (bit7), limit=0xAB at bits 12..20. + let mut b = vec![0u8; 4]; + set_bits(&mut b, 0, 2, 2); + set_bits(&mut b, 7, 1, 1); + set_bits(&mut b, 12, 8, 0xAB); + assert_eq!(b, vec![0x82, 0xB0, 0x0A, 0x00]); + let d = decode(&layout(), &b).unwrap(); + assert_eq!((d[0].raw, d[0].label.as_deref()), (2, Some("sport"))); + assert_eq!((d[1].raw, d[1].label.as_deref()), (1, Some("yes"))); + assert_eq!((d[2].raw, d[2].label.as_deref()), (0xAB, None)); + } + + #[test] + fn a_change_touches_only_its_own_bits() { + let block = vec![0xFF, 0xFF, 0xFF, 0xFF]; + let out = encode_change(&layout(), &block, "mode", "eco").unwrap(); + assert_eq!(out, vec![0xFD, 0xFF, 0xFF, 0xFF]); + let out = encode_change(&layout(), &block, "limit", "0x10").unwrap(); + // bits 12..20 now 0x10; every other bit, including undescribed ones, stays 1. + let d = decode(&layout(), &out).unwrap(); + assert_eq!(d[2].raw, 0x10); + let diff: u32 = block + .iter() + .zip(&out) + .map(|(a, b)| (a ^ b).count_ones()) + .sum(); + assert_eq!(diff, 7, "0xFF -> 0x10 clears seven of the eight bits"); + // Round trip: decode, change to the same value, nothing differs. + assert_eq!(encode_change(&layout(), &out, "limit", "16").unwrap(), out); + } + + #[test] + fn bad_changes_are_refused() { + let b = vec![0u8; 4]; + let l = layout(); + assert!(encode_change(&l, &b, "nope", "1").is_err()); + assert!(encode_change(&l, &b, "mode", "turbo").is_err()); + assert!( + encode_change(&l, &b, "mode", "3").is_err(), + "3 is not a listed value" + ); + assert!( + encode_change(&l, &b, "limit", "256").is_err(), + "does not fit 8 bits" + ); + assert!( + encode_change(&l, &b[..3], "mode", "eco").is_err(), + "wrong length" + ); + assert!(decode(&l, &b[..3]).is_err()); + } + + #[test] + fn the_software_level_must_match_exactly() { + let s = src(); + assert!(s.layout(0x12, Some("TEST-00"), 0x2000).is_ok()); + let e = s + .layout(0x12, Some("TEST-01"), 0x2000) + .unwrap_err() + .to_string(); + assert!(e.contains("refusing to guess"), "{e}"); + assert!(s.layout(0x12, None, 0x2000).is_err()); + assert!(s.layout(0x12, Some("TEST-00"), 0x9999).is_err()); + assert!(s.layout(0x60, Some("TEST-00"), 0x2000).is_err()); + } + + #[test] + fn invalid_definitions_are_rejected() { + let bad = |from: &str, to: &str| { + SyntheticSource::from_json(&DEF.replace(from, to)) + .unwrap_err() + .to_string() + }; + assert!(bad("opendiag-bmw-coding/0", "other/1").contains("format")); + assert!(bad( + "synthetic test data written for OpenDiag; not from any car", + " " + ) + .contains("provenance")); + assert!(bad("\"bit_offset\": 12", "\"bit_offset\": 28").contains("past the end")); + assert!(bad("\"bit_offset\": 7", "\"bit_offset\": 1").contains("overlaps")); + assert!(bad("\"2\": \"sport\"", "\"4\": \"sport\"").contains("does not fit")); + assert!(bad("\"name\": \"flag\"", "\"name\": \"mode\"").contains("duplicate")); + assert!(bad("\"ecu\": 18,", "\"ecu\": 18, \"extra\": 1,").contains("bad JSON")); + assert!(bad("\"yes\"", "\"1\"").contains("looks like a number")); + } +} diff --git a/crates/opendiag-cli/Cargo.toml b/crates/opendiag-cli/Cargo.toml index c78cd76..8045580 100644 --- a/crates/opendiag-cli/Cargo.toml +++ b/crates/opendiag-cli/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" [dependencies] opendiag-bmw = { path = "../opendiag-bmw" } +opendiag-bmw-coding = { path = "../opendiag-bmw-coding" } opendiag-core = { path = "../opendiag-core" } opendiag-data = { path = "../opendiag-data" } opendiag-proto = { path = "../opendiag-proto" } diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs index 4ea7c5a..0103f7c 100644 --- a/crates/opendiag-cli/src/bmw.rs +++ b/crates/opendiag-cli/src/bmw.rs @@ -12,6 +12,7 @@ use opendiag_bmw::{ broadcast_target, discover, log_dids_csv, read_did, read_ident, scan, BmwEcu, DidLogConfig, Discovered, HsfzGateway, HsfzLink, TcpByteStream, }; +use opendiag_bmw_coding::{decode, encode_change, CodingSource, SyntheticSource}; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; use opendiag_services::{ @@ -67,6 +68,21 @@ pub enum BmwCmd { #[command(subcommand)] action: BmwBlock, }, + /// Show or change a block by field name, using a definition file in OpenDiag's own + /// format (docs/examples/bmw-coding-synthetic.json). Changes go through `block write`'s + /// guarded flow. BMW's own files are not read. + Coding { + #[command(subcommand)] + action: BmwCoding, + }, + /// Serve a read-only web page for one ECU on 127.0.0.1 (this computer only). + Serve { + #[command(flatten)] + conn: Conn, + /// Port to listen on (default: any free port). + #[arg(long, default_value_t = 0)] + listen_port: u16, + }, /// Log data identifiers from one ECU as raw CSV at a steady rate. Live { #[command(flatten)] @@ -96,6 +112,40 @@ pub struct BlockConn { extended_session: bool, } +#[derive(Args)] +pub struct CodingArgs { + #[command(flatten)] + bc: BlockConn, + /// Data identifier of the block, in hex. + #[arg(long, value_parser = parse_hex_u16)] + did: u16, + /// Definition file in the `opendiag-bmw-coding/0` format. + #[arg(long)] + coding_file: std::path::PathBuf, + /// Software level of the ECU, if the definitions name one. Must match exactly. + #[arg(long)] + i_level: Option, +} + +#[derive(Subcommand)] +pub enum BmwCoding { + /// Print every field of the block by name (read-only). + Show(CodingArgs), + /// Change one field by name. Prints the named change and the byte diff, then asks for YES. + Set { + #[command(flatten)] + args: CodingArgs, + /// Field name. + #[arg(long)] + field: String, + /// A label from the definitions, or a number (decimal or 0x hex). + #[arg(long)] + value: String, + #[command(flatten)] + store: StoreArg, + }, +} + #[derive(Subcommand)] pub enum BmwBlock { /// Print one block as hex (read-only). @@ -162,6 +212,45 @@ pub struct Conn { tester: u8, } +impl Conn { + /// Default options, used when `--brand bmw` routes another command here. + pub fn routed(simulate: bool) -> Self { + Self { + ip: None, + port: TCP_PORT, + simulate, + target: None, + tester: opendiag_bmw::hsfz::DEFAULT_TESTER, + } + } +} + +/// How many gateways answer on the local network right now (UDP discovery, about +/// 1.5 s). Used by `--brand auto`; sends only the discovery broadcast. +pub fn count_gateways() -> usize { + discover(broadcast_target(), Duration::from_millis(1500)).map_or(0, |v| v.len()) +} + +fn serve_cmd(c: &Conn, listen_port: u16) -> Result<(), String> { + let s = connect(c)?; + let ecu = ecu_of(&s); + let (connection, simulated) = if c.simulate { + ("Simulated: built-in virtual BMW (HSFZ)".to_string(), true) + } else { + ( + format!( + "BMW ENET (HSFZ), ECU {:#04X}. Experimental: simulator-tested only", + s.target + ), + false, + ) + }; + // `s` stays alive until the server stops (it owns the simulator, when there is one). + let result = crate::serve_module(Box::new(ecu), connection, simulated, listen_port); + drop(s); + result +} + fn parse_hex_u16(s: &str) -> Result { u16::from_str_radix(s.trim_start_matches("0x").trim_start_matches("0X"), 16) .map_err(|e| e.to_string()) @@ -192,6 +281,8 @@ pub fn run(cmd: BmwCmd) -> Result<(), String> { action: BmwDtc::Clear { conn, store }, } => dtc_clear_cmd(&conn, &store), BmwCmd::Block { action } => block_cmd(action), + BmwCmd::Coding { action } => coding_cmd(action), + BmwCmd::Serve { conn, listen_port } => serve_cmd(&conn, listen_port), BmwCmd::Live { conn, did, @@ -583,3 +674,81 @@ fn block_apply( ); Ok(()) } + +fn show_fields(fields: &[opendiag_bmw_coding::DecodedField]) { + for f in fields { + println!( + " {:<16} = {} ({})", + f.name, + f.label.as_deref().unwrap_or("no label"), + f.raw + ); + } +} + +/// Load definitions and read the block twice: if two reads differ the data is not +/// stable and nothing is decoded. +fn coding_context( + a: &CodingArgs, +) -> Result<(CliEcu, Session, opendiag_bmw_coding::BlockLayout, Vec), String> { + let text = std::fs::read_to_string(&a.coding_file) + .map_err(|e| format!("cannot read {}: {e}", a.coding_file.display()))?; + let source = SyntheticSource::from_json(&text).map_err(|e| e.to_string())?; + eprintln!("Definitions: {}", source.provenance); + let (mut ecu, s) = block_ecu(&a.bc)?; + let layout = source + .layout(s.target, a.i_level.as_deref(), a.did) + .map_err(|e| e.to_string())? + .clone(); + let first = ecu.read_block(a.did).map_err(|e| e.to_string())?; + let second = ecu.read_block(a.did).map_err(|e| e.to_string())?; + if first != second { + return Err("two consecutive reads of the block differ; not decoding unstable data".into()); + } + Ok((ecu, s, layout, first)) +} + +fn coding_cmd(action: BmwCoding) -> Result<(), String> { + match action { + BmwCoding::Show(a) => { + let (_, s, layout, block) = coding_context(&a)?; + println!( + "ECU {:#04X} block {:#06X}: {}", + s.target, + a.did, + hex_str(&block) + ); + show_fields(&decode(&layout, &block).map_err(|e| e.to_string())?); + Ok(()) + } + BmwCoding::Set { + args, + field, + value, + store, + } => { + let (mut ecu, s, layout, block) = coding_context(&args)?; + let new = encode_change(&layout, &block, &field, &value).map_err(|e| e.to_string())?; + let before = decode(&layout, &block).map_err(|e| e.to_string())?; + let after = decode(&layout, &new).map_err(|e| e.to_string())?; + for (b, a) in before.iter().zip(&after) { + if b.raw != a.raw { + println!( + "Field {}: {} -> {}", + b.name, + b.label.as_deref().map_or(b.raw.to_string(), str::to_string), + a.label.as_deref().map_or(a.raw.to_string(), str::to_string) + ); + } + } + let change = plan_block_change(&mut ecu, args.did, new).map_err(|e| e.to_string())?; + block_apply( + &mut ecu, + &s, + &backup_store(&store), + &change, + args.bc.conn.simulate, + ) + } + } +} diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index a4411f9..f35f674 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -28,10 +28,24 @@ use opendiag_transport::{ TraceStatus, Tracing, Transport, }; -/// Open source VAG group diagnostic tool. +/// Which vehicle family a command talks to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] +enum BrandArg { + Vag, + Bmw, + /// Look for a BMW ENET gateway on the network: one found means BMW, none means VAG. + Auto, +} + +/// Open source diagnostic tool for VAG group vehicles, with experimental BMW F-series support. #[derive(Parser)] #[command(name = "opendiag", version, about)] struct Cli { + /// Vehicle family. Without this flag every command behaves exactly as before (VAG; `bmw ...` + /// is BMW). `bmw` routes `serve` to the BMW backend; `auto` decides by ENET discovery and + /// prints what it chose before anything else is sent. + #[arg(long, global = true, value_enum)] + brand: Option, #[command(subcommand)] command: Option, } @@ -307,9 +321,84 @@ struct Target { ecu_id: u32, } +/// Commands that open a connection to a vehicle (the ones `--brand` is about). +fn is_vehicle_command(c: &Cmd) -> bool { + matches!( + c, + Cmd::Scan(_) + | Cmd::Dtc { .. } + | Cmd::Adaptation { .. } + | Cmd::Log { .. } + | Cmd::Report { .. } + | Cmd::Serve { .. } + ) +} + +/// Apply `--brand`. With no flag the command is returned untouched, so existing +/// behaviour does not change. `detect` counts BMW gateways (only called for `auto`). +fn route( + brand: Option, + detect: impl FnOnce() -> usize, + cmd: Option, +) -> Result, String> { + let Some(cmd) = cmd else { return Ok(None) }; + let Some(brand) = brand else { + return Ok(Some(cmd)); + }; + if matches!(cmd, Cmd::Bmw { .. }) { + return match brand { + BrandArg::Vag => { + Err("--brand vag conflicts with `opendiag bmw ...`, which is always BMW".into()) + } + _ => Ok(Some(cmd)), + }; + } + if !is_vehicle_command(&cmd) { + return Ok(Some(cmd)); + } + let chosen = match brand { + BrandArg::Auto => match detect() { + 0 => { + eprintln!("--brand auto: no BMW gateway answered; using VAG."); + BrandArg::Vag + } + 1 => { + eprintln!("--brand auto: a BMW gateway answered; using BMW."); + BrandArg::Bmw + } + n => { + return Err(format!( + "--brand auto: {n} BMW gateways answered; say which with `--brand bmw` and `opendiag bmw ... --ip`" + )) + } + }, + b => b, + }; + match (chosen, cmd) { + (BrandArg::Bmw, Cmd::Serve { target, listen_port }) => Ok(Some(Cmd::Bmw { + action: bmw::BmwCmd::Serve { + conn: bmw::Conn::routed(target.simulate), + listen_port, + }, + })), + (BrandArg::Bmw, _) => Err( + "with --brand bmw only `serve` is routed; use `opendiag bmw scan`, `bmw dtc read|clear`, `bmw block ...` or `bmw live`" + .into(), + ), + (_, c) => Ok(Some(c)), + } +} + fn main() -> ExitCode { let cli = Cli::parse(); - let result = match cli.command { + let command = match route(cli.brand, bmw::count_gateways, cli.command) { + Ok(c) => c, + Err(e) => { + eprintln!("error: {e}"); + return ExitCode::FAILURE; + } + }; + let result = match command { None => { println!( "opendiag {} - no command given; try --help", @@ -978,9 +1067,19 @@ fn random_token() -> Result { fn serve_cmd(target: &Target, listen_port: u16) -> Result<(), String> { let conn = connect(target)?; let Connection { module, _trace } = conn; + let (connection, simulated) = describe_connection(target); + serve_module(module, connection, simulated, listen_port) +} + +/// Serve any connected module read-only on localhost until stopped. +pub(crate) fn serve_module( + module: Box, + connection: String, + simulated: bool, + listen_port: u16, +) -> Result<(), String> { let mut module = module; let module_name = module.faults().describe(); - let (connection, simulated) = describe_connection(target); let server = tiny_http::Server::http(("127.0.0.1", listen_port)) .map_err(|e| format!("cannot listen on 127.0.0.1:{listen_port}: {e}"))?; @@ -1364,3 +1463,74 @@ fn confirm() -> Result { // Windows PowerShell prepends a UTF-8 BOM when piping text into a program. Ok(line.trim_start_matches('\u{feff}').trim() == "YES") } + +#[cfg(test)] +mod brand_tests { + use super::*; + + fn parse(args: &[&str]) -> Cli { + let mut v = vec!["opendiag"]; + v.extend_from_slice(args); + Cli::try_parse_from(v).unwrap() + } + + fn never() -> usize { + panic!("discovery must not run"); + } + + fn is_bmw_serve(c: &Option) -> bool { + matches!( + c, + Some(Cmd::Bmw { + action: bmw::BmwCmd::Serve { .. } + }) + ) + } + + #[test] + fn without_the_flag_nothing_is_routed_and_nothing_is_probed() { + let cli = parse(&["serve", "--simulate"]); + let out = route(cli.brand, never, cli.command).unwrap(); + assert!(matches!(out, Some(Cmd::Serve { .. }))); + } + + #[test] + fn brand_vag_is_a_no_op_and_conflicts_with_the_bmw_command() { + let cli = parse(&["--brand", "vag", "scan", "--simulate"]); + assert!(matches!( + route(cli.brand, never, cli.command).unwrap(), + Some(Cmd::Scan(_)) + )); + let cli = parse(&["--brand", "vag", "bmw", "discover", "--simulate"]); + assert!(route(cli.brand, never, cli.command).is_err()); + } + + #[test] + fn brand_bmw_routes_serve_and_explains_the_rest() { + let cli = parse(&["serve", "--simulate", "--brand", "bmw"]); + assert!(is_bmw_serve(&route(cli.brand, never, cli.command).unwrap())); + let cli = parse(&["--brand", "bmw", "scan", "--simulate"]); + let err = route(cli.brand, never, cli.command).err().unwrap(); + assert!(err.contains("opendiag bmw scan"), "{err}"); + // Commands that do not talk to a vehicle are left alone. + let cli = parse(&["--brand", "bmw", "backup", "list"]); + assert!(matches!( + route(cli.brand, never, cli.command).unwrap(), + Some(Cmd::Backup { .. }) + )); + } + + #[test] + fn auto_decides_by_how_many_gateways_answer() { + let go = |n: usize| { + let cli = parse(&["--brand", "auto", "serve", "--simulate"]); + route(cli.brand, move || n, cli.command) + }; + assert!(matches!(go(0).unwrap(), Some(Cmd::Serve { .. }))); + assert!(is_bmw_serve(&go(1).unwrap())); + assert!(go(2).err().unwrap().contains("2 BMW gateways")); + // Not a vehicle command: no discovery at all. + let cli = parse(&["--brand", "auto", "data", "schema"]); + assert!(route(cli.brand, never, cli.command).is_ok()); + } +} diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index 32ce002..0c2feb8 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -1372,3 +1372,145 @@ fn bmw_block_write_refuses_identity_data_wrong_length_and_has_no_yes_flag() { assert!(!ok && err.contains("--yes"), "{err}"); assert!(!backups.exists()); } + +#[test] +fn serve_brand_bmw_serves_the_simulated_bmw_read_only() { + let srv = start_server(&["--brand", "bmw", "--simulate"]); + let host = format!("127.0.0.1:{}", srv.port); + let (status, _, body) = http(srv.port, "GET", "/api/info", &host, Some(&srv.token)); + assert_eq!(status, 200); + assert!( + body.contains("\"simulated\":true") && body.contains("BMW"), + "{body}" + ); + let (status, _, body) = http(srv.port, "GET", "/api/ident", &host, Some(&srv.token)); + assert_eq!(status, 200); + assert!(body.contains("WBASIMULATED00001"), "{body}"); + let (status, _, _) = http(srv.port, "POST", "/api/dtc", &host, Some(&srv.token)); + assert_ne!(status, 200, "serve must stay read-only"); +} + +#[test] +fn bmw_serve_command_works_directly_and_brand_flag_does_not_change_vag() { + // `--brand vag` leaves a VAG command working as before. + let (ok, out, err) = run(&["--brand", "vag", "scan", "--simulate"], ""); + assert!(ok, "{err}"); + assert!(!out.is_empty()); + let (ok, _, err) = run(&["--brand", "bmw", "scan", "--simulate"], ""); + assert!(!ok); + assert!(err.contains("opendiag bmw scan"), "{err}"); +} + +fn coding_example() -> String { + format!( + "{}/../../docs/examples/bmw-coding-synthetic.json", + env!("CARGO_MANIFEST_DIR") + ) +} + +#[test] +fn bmw_coding_show_names_the_fields() { + let f = coding_example(); + let (ok, out, err) = run( + &[ + "bmw", + "coding", + "show", + "--simulate", + "--target", + "0x12", + "--did", + "0x2000", + "--coding-file", + &f, + ], + "", + ); + assert!(ok, "{err}"); + assert!( + err.contains("Synthetic example"), + "provenance must be shown: {err}" + ); + assert!(out.contains("demo_mode") && out.contains("eco"), "{out}"); + assert!( + out.contains("demo_limit") && out.contains("no label"), + "{out}" + ); +} + +#[test] +fn bmw_coding_set_goes_through_the_guarded_flow() { + let f = coding_example(); + let backups = temp_file("bmw-coding.jsonl"); + let _ = std::fs::remove_file(&backups); + let b = backups.to_str().unwrap(); + let args = [ + "bmw", + "coding", + "set", + "--simulate", + "--target", + "0x12", + "--did", + "0x2000", + "--coding-file", + &f, + "--field", + "demo_mode", + "--value", + "sport", + "--backup-file", + b, + ]; + let (ok, out, _) = run(&args, "no\n"); + assert!(ok); + assert!(out.contains("Field demo_mode: eco -> sport"), "{out}"); + assert!(out.contains("Cancelled") && !backups.exists(), "{out}"); + let (ok, out, err) = run(&args, "YES\n"); + assert!(ok, "{err}"); + assert!(out.contains("verified by reading it back"), "{out}"); + let text = std::fs::read_to_string(&backups).unwrap(); + assert!( + text.contains("\"old_hex\":\"0102030405060708\"") + && text.contains("\"new_hex\":\"0202030405060708\""), + "{text}" + ); + let _ = std::fs::remove_file(&backups); +} + +#[test] +fn bmw_coding_refuses_unknown_values_fields_and_blocks_without_writing() { + let f = coding_example(); + let backups = temp_file("bmw-coding-bad.jsonl"); + let _ = std::fs::remove_file(&backups); + let b = backups.to_str().unwrap(); + let base = |field: &'static str, value: &'static str, did: &'static str| { + run( + &[ + "bmw", + "coding", + "set", + "--simulate", + "--target", + "0x12", + "--did", + did, + "--coding-file", + &f, + "--field", + field, + "--value", + value, + "--backup-file", + b, + ], + "YES\n", + ) + }; + assert!(!base("demo_mode", "turbo", "0x2000").0); + assert!(!base("demo_mode", "3", "0x2000").0); + assert!(!base("nope", "1", "0x2000").0); + let (ok, _, err) = base("demo_mode", "eco", "0x2001"); + assert!(!ok && err.contains("no definition"), "{err}"); + assert!(!backups.exists(), "nothing may be backed up or written"); +} diff --git a/docs/bmw.md b/docs/bmw.md index 6f50ed7..5ca8681 100644 --- a/docs/bmw.md +++ b/docs/bmw.md @@ -12,6 +12,9 @@ opendiag bmw dtc clear --target 0x12 # guarded: snapshot, typed YES, clear, re- opendiag bmw block read --target 0x12 --did 0x2000 # raw block as hex opendiag bmw block write --target 0x12 --did 0x2000 --hex ... # guarded write opendiag bmw block restore b0003 --target 0x12 # put a backed-up block back +opendiag bmw coding show --target 0x12 --did 0x2000 --coding-file docs/examples/bmw-coding-synthetic.json +opendiag bmw coding set ... --field demo_mode --value sport # by name, through the guarded block flow +opendiag bmw serve --simulate # read-only web page for one ECU (also: opendiag serve --brand bmw) opendiag bmw live --target 0x12 --did 0x4002,0xF190 --samples 20 # raw CSV log opendiag bmw ident --simulate # no car: built-in virtual BMW (works for every command) ``` @@ -75,6 +78,24 @@ The flow (`opendiag-services/src/block.rs`, shared by any protocol): requirement are all unverified. Keep a charger connected and the ignition on, and expect to need a capture from your own car first. +### Choosing the brand + +`opendiag bmw ...` is always BMW and every existing command is VAG, exactly as before. The global `--brand` +flag is optional: `--brand bmw` routes `serve` to the BMW backend (other VAG commands are refused with a pointer +to their `bmw` equivalent); `--brand auto` sends one UDP discovery broadcast, uses BMW if exactly one gateway +answers and VAG if none, errors on several, and prints what it chose before anything else is sent. The brand +is chosen at launch, never from inside the web page. + +### Coding by name (our own format only) + +`opendiag-bmw-coding` turns a raw block into named fields using definition files in our own format +(`opendiag-bmw-coding/0`, provenance required, strict validation; example in +`docs/examples/bmw-coding-synthetic.json`). It is pure: `coding set` computes a complete new block with only +that field's bits changed and hands it to the same guarded flow as `block write`. It refuses unknown fields or +values, a block of the wrong length, a definition for a different software level (`--i-level` must match +exactly), and unstable data (two reads must agree). **It does not read BMW's own files** (PSdZData, CAFD): their +format is not known to us. See [design-bmw-coding-and-launcher.md](design-bmw-coding-and-launcher.md). + ## Verified vs unverified Verified against public sources (see [sources.md](sources.md)): diff --git a/docs/design-bmw-coding-and-launcher.md b/docs/design-bmw-coding-and-launcher.md index bdd6a3a..cb72c8d 100644 --- a/docs/design-bmw-coding-and-launcher.md +++ b/docs/design-bmw-coding-and-launcher.md @@ -139,6 +139,8 @@ Any GUI launcher (that waits for the Tauri app), an HTTP API, and cross-brand fe ## 4. Order of work and what blocks it +Status: steps 1 and 3 below are implemented (router; synthetic format with `coding show/set`). Step 2 and 4 are not. + 1. `--brand` router and `serve --brand` (no new abstraction; low risk, can start now). 2. `Vehicle` extraction, driven by step 1's actual call sites. 3. Synthetic coding format and `encode_change`/`decode` with synthetic fixtures (can start now, no BMW data). diff --git a/docs/examples/bmw-coding-synthetic.json b/docs/examples/bmw-coding-synthetic.json new file mode 100644 index 0000000..f754e83 --- /dev/null +++ b/docs/examples/bmw-coding-synthetic.json @@ -0,0 +1,16 @@ +{ + "format": "opendiag-bmw-coding/0", + "provenance": "Synthetic example written for OpenDiag's simulator. Not from any car, ECU or BMW file.", + "blocks": [ + { + "ecu": 18, + "block": 8192, + "length": 8, + "fields": [ + { "name": "demo_mode", "bit_offset": 0, "bit_len": 2, "values": { "0": "off", "1": "eco", "2": "sport" } }, + { "name": "demo_flag", "bit_offset": 8, "bit_len": 1, "values": { "0": "no", "1": "yes" } }, + { "name": "demo_limit", "bit_offset": 16, "bit_len": 8 } + ] + } + ] +} From 4c8da6ca037adb3b980133aed39ee7fbac778787 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:34:35 +0000 Subject: [PATCH 7/9] refactor(services,bmw,cli): extract the Vehicle trait from the two backends - services::vehicle: Vehicle (identify, scan, ecu as Module, keep_alive), SingleModule for VAG connections, VehicleModule to present one ECU of any vehicle as a Module; identification lines carry a verified flag - bmw::BmwVehicle over the HSFZ gateway, one BmwEcu per address - serve runs both brands through the same path; bmw scan/ident use the trait - no connect() on the trait: connecting shares nothing between brands Behaviour unchanged; full suite passes. Co-Authored-By: Claude Sonnet 5.5 --- crates/opendiag-bmw/src/lib.rs | 2 + crates/opendiag-bmw/src/vehicle.rs | 126 +++++++++++++ crates/opendiag-bmw/tests/vehicle.rs | 73 ++++++++ crates/opendiag-cli/src/bmw.rs | 101 ++++++---- crates/opendiag-cli/src/main.rs | 7 +- crates/opendiag-services/src/lib.rs | 4 + crates/opendiag-services/src/vehicle.rs | 205 +++++++++++++++++++++ crates/opendiag-services/tests/services.rs | 40 ++++ docs/bmw.md | 7 + docs/design-bmw-coding-and-launcher.md | 4 +- 10 files changed, 533 insertions(+), 36 deletions(-) create mode 100644 crates/opendiag-bmw/src/vehicle.rs create mode 100644 crates/opendiag-bmw/tests/vehicle.rs create mode 100644 crates/opendiag-services/src/vehicle.rs diff --git a/crates/opendiag-bmw/src/lib.rs b/crates/opendiag-bmw/src/lib.rs index 120b756..161e3ed 100644 --- a/crates/opendiag-bmw/src/lib.rs +++ b/crates/opendiag-bmw/src/lib.rs @@ -18,6 +18,7 @@ pub mod ident; pub mod live; pub mod mock; pub mod scan; +pub mod vehicle; pub use discovery::{broadcast_target, discover, Discovered}; pub use ecu::{format_bmw_dtc, BmwEcu}; @@ -25,3 +26,4 @@ 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 vehicle::BmwVehicle; diff --git a/crates/opendiag-bmw/src/vehicle.rs b/crates/opendiag-bmw/src/vehicle.rs new file mode 100644 index 0000000..ce7d0cc --- /dev/null +++ b/crates/opendiag-bmw/src/vehicle.rs @@ -0,0 +1,126 @@ +//! A BMW car behind its gateway, as an `opendiag_services::Vehicle`. +//! +//! One TCP connection, many ECUs: [`BmwVehicle::ecu`] makes a [`BmwEcu`] per +//! diagnostic address on first use and keeps it, so each ECU keeps its own +//! session state (for example an opened extended session). + +use std::collections::BTreeMap; +use std::time::Duration; + +use opendiag_core::Result; +use opendiag_proto::clock::Clock; +use opendiag_proto::uds::{UdsClient, UdsConfig}; +use opendiag_services::{Brand, EcuEntry, EcuId, IdentLine, Module, Vehicle, VehicleIdent}; + +use crate::ecu::BmwEcu; +use crate::ecus; +use crate::gateway::{ByteStream, HsfzGateway, HsfzLink}; +use crate::ident::read_ident; +use crate::scan::scan; + +pub struct BmwVehicle { + gateway: HsfzGateway, + default_ecu: u8, + description: String, + probe_timeout: Duration, + ecus: BTreeMap>>, +} + +impl BmwVehicle { + /// `default_ecu` is the gateway's diagnostic address (usually 0x10). + pub fn new(gateway: HsfzGateway, default_ecu: u8, description: String) -> Self { + Self { + gateway, + default_ecu, + description, + probe_timeout: Duration::from_millis(300), + ecus: BTreeMap::new(), + } + } + + /// How long a scan waits for each address. + pub fn with_probe_timeout(mut self, t: Duration) -> Self { + self.probe_timeout = t; + self + } + + pub fn gateway(&self) -> &HsfzGateway { + &self.gateway + } +} + +fn hex(b: &[u8]) -> String { + b.iter() + .map(|x| format!("{x:02X}")) + .collect::>() + .join(" ") +} + +impl Vehicle for BmwVehicle { + fn brand(&self) -> Brand { + Brand::Bmw + } + + fn describe(&self) -> String { + self.description.clone() + } + + fn identify(&mut self) -> Result { + let mut uds = UdsClient::new(self.gateway.link(self.default_ecu), UdsConfig::default()); + let id = read_ident(&mut uds)?; + let mut lines = Vec::new(); + // Raw bytes, and marked unverified: the DIDs are recalled, not confirmed. + if let Some(t) = id.i_level_text() { + lines.push(IdentLine { + label: "I-level".into(), + value: t, + verified: false, + }); + } else if let Some(raw) = &id.i_level_raw { + lines.push(IdentLine { + label: "I-level (raw)".into(), + value: hex(raw), + verified: false, + }); + } + if let Some(raw) = &id.fa_raw { + lines.push(IdentLine { + label: "FA (raw, not decoded)".into(), + value: hex(raw), + verified: false, + }); + } + Ok(VehicleIdent { vin: id.vin, lines }) + } + + fn scan(&mut self) -> Result> { + Ok( + scan(&self.gateway, &ecus::known_addresses(), self.probe_timeout)? + .into_iter() + .filter(|e| e.present) + .map(|e| EcuEntry { + id: e.address, + name: ecus::name(e.address).map(str::to_string), + dtc_count: e.dtc_count, + }) + .collect(), + ) + } + + fn default_ecu(&self) -> EcuId { + self.default_ecu + } + + fn ecu(&mut self, id: EcuId) -> Result<&mut dyn Module> { + let gateway = &self.gateway; + Ok(self + .ecus + .entry(id) + .or_insert_with(|| BmwEcu::new(gateway.link(id), id, UdsConfig::default()))) + } + + fn keep_alive(&mut self) -> Result<()> { + // TesterPresent to the gateway keeps the connection up. + UdsClient::new(self.gateway.link(self.default_ecu), UdsConfig::default()).tester_present() + } +} diff --git a/crates/opendiag-bmw/tests/vehicle.rs b/crates/opendiag-bmw/tests/vehicle.rs new file mode 100644 index 0000000..128ec09 --- /dev/null +++ b/crates/opendiag-bmw/tests/vehicle.rs @@ -0,0 +1,73 @@ +//! `BmwVehicle` through the brand-neutral `Vehicle` trait, over the in-memory loopback. + +use opendiag_bmw::mock::{LoopbackStream, VirtualVehicle}; +use opendiag_bmw::{BmwVehicle, HsfzGateway}; +use opendiag_proto::clock::FakeClock; +use opendiag_services::{ + apply_clear, plan_clear, BackupStore, Brand, ClearConfirmation, Module, Vehicle, VehicleModule, +}; + +fn car() -> BmwVehicle { + let gw = HsfzGateway::new( + LoopbackStream::new(VirtualVehicle::demo()), + FakeClock::new(), + 0xF4, + ); + BmwVehicle::new(gw, 0x10, "virtual BMW".into()) +} + +#[test] +fn identify_labels_the_unverified_items() { + let mut v = car(); + assert_eq!(v.brand(), Brand::Bmw); + let id = v.identify().unwrap(); + assert_eq!(id.vin.as_deref(), Some("WBASIMULATED00001")); + let i_level = id.lines.iter().find(|l| l.label == "I-level").unwrap(); + assert_eq!(i_level.value, "F020-00-00-000"); + assert!( + id.lines.iter().all(|l| !l.verified), + "I-level and FA must be marked unverified: {:?}", + id.lines + ); +} + +#[test] +fn scan_lists_only_ecus_that_answer_with_their_code_counts() { + let found = car().scan().unwrap(); + let ids: Vec = found.iter().map(|e| e.id).collect(); + assert_eq!(ids, vec![0x10, 0x12, 0x18, 0x60]); + let dme = found.iter().find(|e| e.id == 0x12).unwrap(); + assert_eq!((dme.name.as_deref(), dme.dtc_count), (Some("DME"), Some(2))); +} + +#[test] +fn each_ecu_is_a_module_and_the_vehicle_stays_alive() { + let mut v = car(); + assert_eq!(v.default_ecu(), 0x10); + assert_eq!(v.ecu(0x12).unwrap().read_dtcs().unwrap().len(), 2); + assert_eq!(v.ecu(0x60).unwrap().read_dtcs().unwrap()[0].text, "930001"); + v.keep_alive().unwrap(); +} + +#[test] +fn the_guarded_clear_works_through_a_vehicle_module() { + let store = BackupStore::new( + std::env::temp_dir().join(format!("opendiag-vehicle-{}.jsonl", std::process::id())), + ); + let _ = std::fs::remove_file(store.path()); + let mut m = VehicleModule::new(Box::new(car()), 0x12).unwrap(); + let shown = plan_clear(m.faults()).unwrap(); + assert_eq!(shown.len(), 2); + let out = apply_clear( + m.faults(), + &store, + &shown, + &ClearConfirmation::for_codes(&shown), + ) + .unwrap(); + assert!(out.remaining.is_empty()); + assert!(std::fs::read_to_string(store.path()) + .unwrap() + .contains("\"kind\":\"dtc_clear\"")); + let _ = std::fs::remove_file(store.path()); +} diff --git a/crates/opendiag-cli/src/bmw.rs b/crates/opendiag-cli/src/bmw.rs index 0103f7c..9c3e6b8 100644 --- a/crates/opendiag-cli/src/bmw.rs +++ b/crates/opendiag-cli/src/bmw.rs @@ -8,16 +8,18 @@ use clap::{Args, Subcommand}; use opendiag_bmw::ecus; use opendiag_bmw::hsfz::{DEFAULT_GATEWAY, TCP_PORT}; use opendiag_bmw::mock::{MockGateway, VirtualVehicle}; +use opendiag_bmw::BmwVehicle; use opendiag_bmw::{ - broadcast_target, discover, log_dids_csv, read_did, read_ident, scan, BmwEcu, DidLogConfig, - Discovered, HsfzGateway, HsfzLink, TcpByteStream, + broadcast_target, discover, log_dids_csv, read_did, scan, BmwEcu, DidLogConfig, Discovered, + HsfzGateway, HsfzLink, TcpByteStream, }; use opendiag_bmw_coding::{decode, encode_change, CodingSource, SyntheticSource}; use opendiag_proto::clock::SystemClock; use opendiag_proto::uds::{UdsClient, UdsConfig}; use opendiag_services::{ apply_block_change, apply_clear, plan_block_change, plan_block_restore, plan_clear, unhex, - BlockAccess, BlockChange, BlockConfirmation, ClearConfirmation, DtcReport, Module, + BlockAccess, BlockChange, BlockConfirmation, ClearConfirmation, DtcReport, EcuEntry, Module, + Vehicle, VehicleModule, }; use crate::{backup_store, confirm, StoreArg}; @@ -233,22 +235,20 @@ pub fn count_gateways() -> usize { fn serve_cmd(c: &Conn, listen_port: u16) -> Result<(), String> { let s = connect(c)?; - let ecu = ecu_of(&s); - let (connection, simulated) = if c.simulate { - ("Simulated: built-in virtual BMW (HSFZ)".to_string(), true) + let simulated = c.simulate; + let connection = if simulated { + "Simulated: built-in virtual BMW (HSFZ)".to_string() } else { - ( - format!( - "BMW ENET (HSFZ), ECU {:#04X}. Experimental: simulator-tested only", - s.target - ), - false, + format!( + "BMW ENET (HSFZ), ECU {:#04X}. Experimental: simulator-tested only", + s.target ) }; - // `s` stays alive until the server stops (it owns the simulator, when there is one). - let result = crate::serve_module(Box::new(ecu), connection, simulated, listen_port); - drop(s); - result + // `_mock` stays alive until the server stops (it owns the simulator, when there is one). + 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) } fn parse_hex_u16(s: &str) -> Result { @@ -386,23 +386,33 @@ fn hex(b: &[u8]) -> String { .join(" ") } +fn vehicle_of(s: Session) -> (BmwVehicle, Option) { + let Session { + gateway, + target, + _mock, + } = s; + ( + BmwVehicle::new( + gateway, + target, + format!("BMW ENET (HSFZ), ECU {target:#04X}"), + ), + _mock, + ) +} + fn ident_cmd(c: &Conn) -> Result<(), String> { - let s = connect(c)?; - let mut uds = UdsClient::new(s.gateway.link(s.target), UdsConfig::default()); - let id = read_ident(&mut uds).map_err(|e| e.to_string())?; - println!("ECU {:#04X}", s.target); + let (mut v, _mock) = vehicle_of(connect(c)?); + let id = v.identify().map_err(|e| e.to_string())?; + println!("ECU {:#04X}", v.default_ecu()); println!( " VIN: {}", id.vin.as_deref().unwrap_or("(not available)") ); - match (&id.i_level_raw, id.i_level_text()) { - (_, Some(t)) => println!(" I-level: {t}"), - (Some(raw), None) => println!(" I-level: raw {}", hex(raw)), - (None, _) => println!(" I-level: (not available)"), - } - match &id.fa_raw { - Some(raw) => println!(" FA (raw): {} (not decoded)", hex(raw)), - None => println!(" FA: (not available)"), + for l in &id.lines { + let note = if l.verified { "" } else { " [unverified]" }; + println!(" {}: {}{note}", l.label, l.value); } println!("The I-level and FA data identifiers are unverified guesses (docs/bmw.md)."); Ok(()) @@ -433,11 +443,13 @@ fn did_cmd(c: &Conn, did: u16) -> Result<(), String> { fn scan_cmd(c: &Conn, all: bool, probe_ms: u64) -> Result<(), String> { let s = connect(c)?; - let addresses: Vec = if all { - (0..=0xFFu8).filter(|a| *a != c.tester).collect() - } else { - ecus::known_addresses() - }; + if !all { + // The brand-neutral path: ask the vehicle which ECUs it has. + let (mut v, _mock) = vehicle_of(s); + let found = v.scan().map_err(|e| e.to_string())?; + return print_vehicle_scan(&found); + } + let addresses: Vec = (0..=0xFFu8).filter(|a| *a != c.tester).collect(); let found = scan(&s.gateway, &addresses, Duration::from_millis(probe_ms)).map_err(|e| e.to_string())?; let present: Vec<_> = found.iter().filter(|e| e.present).collect(); @@ -460,6 +472,29 @@ fn scan_cmd(c: &Conn, all: bool, probe_ms: u64) -> Result<(), String> { Ok(()) } +fn print_vehicle_scan(found: &[EcuEntry]) -> Result<(), String> { + if found.is_empty() { + println!("No ECU answered. Check the ENET cable and that the ignition is on."); + return Ok(()); + } + println!("{} ECU(s) answered:", found.len()); + for e in found { + let desc = ecus::description(e.id).unwrap_or("not in the address table"); + let codes = match e.dtc_count { + Some(0) => "no fault codes".to_string(), + Some(n) => format!("{n} fault code(s)"), + None => "fault codes unreadable".to_string(), + }; + println!( + " {:#04X} {:<6} {desc}: {codes}", + e.id, + e.name.as_deref().unwrap_or("?") + ); + } + println!("Names come from a short unverified table (docs/bmw.md); they are labels only."); + Ok(()) +} + type CliEcu = BmwEcu>; fn ecu_of(s: &Session) -> CliEcu { diff --git a/crates/opendiag-cli/src/main.rs b/crates/opendiag-cli/src/main.rs index f35f674..61a3d0a 100644 --- a/crates/opendiag-cli/src/main.rs +++ b/crates/opendiag-cli/src/main.rs @@ -21,7 +21,7 @@ use opendiag_services::demo::{ use opendiag_services::{ apply_change, apply_clear, apply_restore, format_unix_utc, log_csv, plan_change, plan_clear, plan_restore, render_html, BackupStore, ClearConfirmation, DtcReport, Kw1281Module, KwpModule, - Limit, LogConfig, Module, Report, ReportFault, WriteConfirmation, + Limit, LogConfig, Module, Report, ReportFault, SingleModule, VehicleModule, WriteConfirmation, }; use opendiag_transport::{ list_serial_ports, open_can, Elm327, Elm327Emulator, Elm327Serial, KLineSerial, SerialIo, @@ -1068,7 +1068,10 @@ fn serve_cmd(target: &Target, listen_port: u16) -> Result<(), String> { let conn = connect(target)?; let Connection { module, _trace } = conn; let (connection, simulated) = describe_connection(target); - serve_module(module, connection, simulated, listen_port) + // 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 any connected module read-only on localhost until stopped. diff --git a/crates/opendiag-services/src/lib.rs b/crates/opendiag-services/src/lib.rs index 6566efe..fa1b482 100644 --- a/crates/opendiag-services/src/lib.rs +++ b/crates/opendiag-services/src/lib.rs @@ -12,6 +12,7 @@ mod kw1281_module; mod kwp_module; pub mod live; pub mod report; +pub mod vehicle; pub use adaptation::{ apply_change, apply_restore, plan_change, plan_restore, AdaptationAccess, Applied, Change, @@ -27,6 +28,9 @@ pub use kw1281_module::Kw1281Module; pub use kwp_module::KwpModule; pub use live::{log_csv, Limit, LiveData, LogConfig, LogSummary, CSV_HEADER}; pub use report::{escape_html, format_unix_utc, render_html, Report, ReportFault}; +pub use vehicle::{ + Brand, EcuEntry, EcuId, IdentLine, SingleModule, Vehicle, VehicleIdent, VehicleModule, +}; use opendiag_core::{Error, Result, WriteMode}; use opendiag_proto::link::MessageLink; diff --git a/crates/opendiag-services/src/vehicle.rs b/crates/opendiag-services/src/vehicle.rs new file mode 100644 index 0000000..faf730e --- /dev/null +++ b/crates/opendiag-services/src/vehicle.rs @@ -0,0 +1,205 @@ +//! A connected vehicle, whatever the brand: what the VAG and BMW backends have +//! in common once connected. +//! +//! Extracted from the two working implementations, not designed ahead of them. +//! What turned out to be shared: identify, list ECUs, reach one ECU as a +//! [`Module`] (so fault codes, the guarded clear and every front end keep +//! working unchanged), and keep the session alive. What did not: *connecting* +//! (adapters, serial ports, TCP and discovery have nothing in common), so there +//! is deliberately no `connect` on the trait: each backend is constructed +//! already connected. Optional abilities (live data, adaptation, block access) +//! stay optional traits reached from the ECU, never promised by the vehicle. + +use opendiag_core::{Error, Result}; + +use crate::{AdaptationAccess, DtcReport, FaultAccess, Ident, LiveData, Module, WriteToken}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Brand { + Vag, + Bmw, +} + +/// Brand-specific address of an ECU. For VAG this is 0 (one module at a time); +/// for BMW it is the diagnostic address. +pub type EcuId = u8; + +/// One ECU that answered a scan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EcuEntry { + pub id: EcuId, + pub name: Option, + /// Stored fault codes, when they could be counted. + pub dtc_count: Option, +} + +/// One labelled line of identification. `verified` is false for items whose +/// meaning or source is not confirmed (for example BMW's I-level and FA), so a +/// front end can show that instead of presenting a guess as fact. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentLine { + pub label: String, + pub value: String, + pub verified: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct VehicleIdent { + pub vin: Option, + pub lines: Vec, +} + +pub trait Vehicle { + fn brand(&self) -> Brand; + /// How it is connected, for display. + fn describe(&self) -> String; + fn identify(&mut self) -> Result; + /// ECUs that answer. VAG connections are one module, so this is one entry. + fn scan(&mut self) -> Result>; + /// The ECU to use when none is named. + fn default_ecu(&self) -> EcuId; + /// One ECU as a [`Module`]. + fn ecu(&mut self, id: EcuId) -> Result<&mut dyn Module>; + fn keep_alive(&mut self) -> Result<()>; +} + +/// A [`Vehicle`] that is a single already-connected module: how every VAG +/// connection works today. +pub struct SingleModule { + module: Box, + description: String, +} + +impl SingleModule { + pub fn new(module: Box, description: String) -> Self { + Self { + module, + description, + } + } +} + +impl Vehicle for SingleModule { + fn brand(&self) -> Brand { + Brand::Vag + } + + fn describe(&self) -> String { + self.description.clone() + } + + fn identify(&mut self) -> Result { + let id: Ident = self.module.identify()?; + let mut lines = Vec::new(); + let mut add = |label: &str, v: Option| { + if let Some(value) = v { + lines.push(IdentLine { + label: label.into(), + value, + verified: true, + }); + } + }; + add("Part number", id.part_number); + add("Software version", id.software_version); + for l in id.lines { + add("Ident", Some(l)); + } + Ok(VehicleIdent { vin: id.vin, lines }) + } + + fn scan(&mut self) -> Result> { + Ok(vec![EcuEntry { + id: 0, + name: Some(self.module.faults().describe()), + dtc_count: self.module.read_dtcs().ok().map(|v| v.len()), + }]) + } + + fn default_ecu(&self) -> EcuId { + 0 + } + + fn ecu(&mut self, id: EcuId) -> Result<&mut dyn Module> { + if id != 0 { + return Err(Error::Protocol(format!( + "this connection has one module (id 0), not {id}" + ))); + } + Ok(self.module.as_mut()) + } + + fn keep_alive(&mut self) -> Result<()> { + self.module.keep_alive() + } +} + +/// Stands in when the selected ECU cannot be reached: every call fails, none panics. +struct Unavailable(String); + +impl FaultAccess for Unavailable { + fn protocol(&self) -> &'static str { + "unavailable" + } + fn module_address(&self) -> u8 { + 0 + } + fn describe(&self) -> String { + self.0.clone() + } + fn read(&mut self) -> Result> { + Err(Error::Protocol(self.0.clone())) + } + fn clear(&mut self, _token: &WriteToken) -> Result<()> { + Err(Error::Protocol(self.0.clone())) + } +} + +/// One ECU of a vehicle, as a [`Module`]. Lets every front end that works on a +/// `Module` (the web server, the CLI) work on any brand's vehicle unchanged. +pub struct VehicleModule { + vehicle: Box, + id: EcuId, + unavailable: Unavailable, +} + +impl VehicleModule { + /// Fails now, not later, if the ECU cannot be reached. + pub fn new(mut vehicle: Box, id: EcuId) -> Result { + vehicle.ecu(id)?; + Ok(Self { + vehicle, + id, + unavailable: Unavailable(format!("ECU {id:#04X} is not available")), + }) + } +} + +impl Module for VehicleModule { + fn identify(&mut self) -> Result { + self.vehicle.ecu(self.id)?.identify() + } + + fn read_dtcs(&mut self) -> Result> { + self.vehicle.ecu(self.id)?.read_dtcs() + } + + fn faults(&mut self) -> &mut dyn FaultAccess { + match self.vehicle.ecu(self.id) { + Ok(m) => m.faults(), + Err(_) => &mut self.unavailable, + } + } + + fn keep_alive(&mut self) -> Result<()> { + self.vehicle.keep_alive() + } + + fn live(&mut self) -> Option<&mut dyn LiveData> { + self.vehicle.ecu(self.id).ok()?.live() + } + + fn adaptation(&mut self) -> Option<&mut dyn AdaptationAccess> { + self.vehicle.ecu(self.id).ok()?.adaptation() + } +} diff --git a/crates/opendiag-services/tests/services.rs b/crates/opendiag-services/tests/services.rs index 9e61bd3..c6b7cb0 100644 --- a/crates/opendiag-services/tests/services.rs +++ b/crates/opendiag-services/tests/services.rs @@ -64,3 +64,43 @@ fn reads_and_formats_dtcs() { assert_eq!(dtcs[0].flags, vec!["testFailed", "confirmed"]); assert_eq!(dtcs[1].text, "P0300-00"); } + +mod vehicle_view { + use opendiag_services::demo::virtual_kw1281_module; + use opendiag_services::{Brand, SingleModule, Vehicle, VehicleModule}; + + fn single() -> SingleModule { + SingleModule::new( + Box::new(virtual_kw1281_module().unwrap()), + "virtual KW1281".into(), + ) + } + + #[test] + fn a_single_module_is_a_one_ecu_vehicle() { + let mut v = single(); + assert_eq!(v.brand(), Brand::Vag); + assert_eq!(v.default_ecu(), 0); + let scan = v.scan().unwrap(); + assert_eq!(scan.len(), 1); + assert!(scan[0].dtc_count.is_some()); + assert!(v.identify().unwrap().lines.iter().all(|l| l.verified)); + assert!(v.ecu(0).is_ok()); + assert!(v.ecu(1).is_err(), "there is only one module"); + } + + #[test] + fn a_vehicle_module_forwards_everything_including_optional_abilities() { + use opendiag_services::Module; + assert!(VehicleModule::new(Box::new(single()), 1).is_err()); + let mut m = VehicleModule::new(Box::new(single()), 0).unwrap(); + assert!(m.identify().is_ok()); + assert!(m.read_dtcs().is_ok()); + assert!(m.live().is_some(), "KW1281 live data must stay reachable"); + assert!( + m.adaptation().is_some(), + "KW1281 adaptation must stay reachable" + ); + m.keep_alive().unwrap(); + } +} diff --git a/docs/bmw.md b/docs/bmw.md index 5ca8681..7e2b1fa 100644 --- a/docs/bmw.md +++ b/docs/bmw.md @@ -78,6 +78,13 @@ The flow (`opendiag-services/src/block.rs`, shared by any protocol): requirement are all unverified. Keep a charger connected and the ignition on, and expect to need a capture from your own car first. +### The `Vehicle` view + +`opendiag_services::Vehicle` (identify, scan, one ECU as a `Module`, keep-alive) is implemented by `BmwVehicle` +here and by `SingleModule` for VAG connections. Identification lines carry a `verified` flag, so BMW's I-level +and FA stay marked `[unverified]` wherever they are shown. Live data, adaptation and block access are not part +of it: they stay optional abilities of an ECU. + ### Choosing the brand `opendiag bmw ...` is always BMW and every existing command is VAG, exactly as before. The global `--brand` diff --git a/docs/design-bmw-coding-and-launcher.md b/docs/design-bmw-coding-and-launcher.md index cb72c8d..8ddc0bd 100644 --- a/docs/design-bmw-coding-and-launcher.md +++ b/docs/design-bmw-coding-and-launcher.md @@ -139,7 +139,9 @@ Any GUI launcher (that waits for the Tauri app), an HTTP API, and cross-brand fe ## 4. Order of work and what blocks it -Status: steps 1 and 3 below are implemented (router; synthetic format with `coding show/set`). Step 2 and 4 are not. +Status: steps 1, 2 and 3 below are implemented (router; `Vehicle` trait; synthetic format with `coding show/set`). Step 4 is not. + +Step 2 as built differs from the sketch in section 2: there is **no `connect` on the trait** (each backend is constructed already connected, since connecting shares nothing between brands), `scan` returns only ECUs that answered, and the trait lives in `opendiag-services` (no new crate, so no dependency cycle). VAG connections are wrapped by `SingleModule`; BMW by `BmwVehicle`; `VehicleModule` presents one ECU of any vehicle as a `Module`, so `serve` now runs both brands through the same path, and `bmw scan`/`bmw ident` use the trait. 1. `--brand` router and `serve --brand` (no new abstraction; low risk, can start now). 2. `Vehicle` extraction, driven by step 1's actual call sites. From 5fe130b2778d5b2dc22e534a1e511a9d2e978d94 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:40:39 +0000 Subject: [PATCH 8/9] chore: ignore /builds/ Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 8a074f3..d6235cf 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ Cargo.lock.bak node_modules/ *.log .env +/builds/ From 7dbd491b596e218ca236a223494e9a6ff49e750a Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:53:25 +0000 Subject: [PATCH 9/9] chore(github): add PR and issue templates, dependabot and SECURITY.md Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Xe1HmJJjhbWaBGaF6FKosA --- .github/ISSUE_TEMPLATE/bug-report.yml | 34 ++++++++++++++++++++++ .github/ISSUE_TEMPLATE/feature-request.yml | 25 ++++++++++++++++ .github/PULL_REQUEST_TEMPLATE.md | 13 +++++++++ .github/dependabot.yml | 17 +++++++++++ SECURITY.md | 22 ++++++++++++++ 5 files changed, 111 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug-report.yml create mode 100644 .github/ISSUE_TEMPLATE/feature-request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/dependabot.yml create mode 100644 SECURITY.md diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000..ddb5b98 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,34 @@ +name: Bug report +description: Something in OpenDiag does not behave as documented. +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + For results from a real vehicle or bench module, use the hardware test report template instead. + Remove VINs and other identifying data from logs before posting. + - type: input + id: version + attributes: + label: OpenDiag version (from `opendiag --version`) + validations: + required: true + - type: dropdown + id: platform + attributes: + label: Platform + options: [Linux, Windows, macOS] + validations: + required: true + - type: textarea + id: what + attributes: + label: What happened, and what did you expect? + validations: + required: true + - type: textarea + id: repro + attributes: + label: Steps to reproduce (simulator commands preferred) + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000..f33c121 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,25 @@ +name: Feature request +description: Propose a feature or improvement. +labels: ["enhancement"] +body: + - type: textarea + id: problem + attributes: + label: What problem does this solve? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed behaviour + validations: + required: true + - type: textarea + id: sources + attributes: + label: Public sources for any protocol or data involved + description: Specs, open source projects or your own captures. Proprietary datasets (Ross-Tech labels, ODIS, BMW PSdZData) cannot be used. + - type: markdown + attributes: + value: | + Out of scope: flashing or ECU reprogramming, and anything that bypasses immobiliser, odometer or tuning protection. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..5b58e79 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +## Summary + + +## Checklist +- [ ] `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo test --workspace` pass +- [ ] No test depends on hardware (use Simulator or Replay) +- [ ] Protocol sources are recorded in `docs/sources.md` +- [ ] Clean-room: no Ross-Tech labels, VCDS/ODIS data or other proprietary datasets +- [ ] Any new vehicle write goes through the guarded flow and is added to `crates/opendiag-services/tests/write_safety.rs` +- [ ] Data contributions include provenance and are CC0-1.0 + +## Verification + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8a1e639 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +version: 2 +updates: + - package-ecosystem: cargo + directory: / + schedule: + interval: weekly + commit-message: + prefix: "chore(deps)" + groups: + cargo-minor-patch: + update-types: [minor, patch] + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: "chore(ci)" diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ba9e224 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,22 @@ +# Security policy + +## Reporting a vulnerability + +Please report security issues privately through GitHub's +[private vulnerability reporting](https://github.com/JoeeDeveloper/OpenDiag/security/advisories/new) +rather than a public issue. Include the version, platform and steps to reproduce. + +This is a hobby project with no fixed response time; reports are handled on a best-effort basis. + +## Scope + +In scope: memory-safety or parsing bugs in the protocol decoders, flaws in the guarded write flow +(a write that skips the durable backup, confirmation or read-back), and the `serve` HTTP interface. + +Out of scope: requests to bypass immobiliser, odometer or tuning protection, or to add flashing support. +These are refused by design (see [docs/safety.md](docs/safety.md)). + +## Status + +OpenDiag has not been verified against real vehicles ([docs/status.md](docs/status.md)). Do not rely +on it for safety-critical decisions, and use write functions only on a bench module you can afford to lose.