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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ It extracts the Windows build (ready to run, `.exe` already executable) into `<s

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

Status: phases 0-2 are largely done (transports, ISO-TP, UDS, KWP2000, KW1281, serial and SocketCAN drivers). Phase 3 (read-only MVP) is in progress: the CLI works against a virtual ECU, and `probe` can talk to a real K-line module. BMW F-series (ENET/HSFZ, `opendiag-bmw`, see `docs/bmw.md`): step 1 read-only, simulator-tested only. Never bundle BMW proprietary data. 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. Done and simulator-tested: TP2.0, KWP2000/KW1281 scan and DTCs, KW1281 live-data logging, `--replay` of recorded traces, the `serve` dashboard, the open data format v0, raw `log --ids` over KWP2000/UDS. Not done: decoded KWP2000 measuring blocks (no public source), BMW replay, GUI. Nothing has been verified against a real car yet.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ An open source, cross-platform diagnostic suite for VAG group vehicles (VW, Audi
|---|---|
| Protocols | ISO-TP, UDS, KWP2000 (K-line), KW1281 (5-baud init), TP2.0, all against simulators |
| 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 |
| 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); measuring-block live data and adaptation are KW1281 only; `log --ids` reads raw bytes over KWP2000 and UDS |
| 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, 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) |
Expand Down
73 changes: 62 additions & 11 deletions crates/opendiag-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ use opendiag_services::demo::{
virtual_kwp_module_over, virtual_uds_client_over, TESTER_ID,
};
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, SingleModule, VehicleModule, WriteConfirmation,
apply_change, apply_clear, apply_restore, format_unix_utc, log_csv, log_raw_csv, plan_change,
plan_clear, plan_restore, render_html, BackupStore, ClearConfirmation, DtcReport, Kw1281Module,
KwpModule, Limit, LogConfig, Module, RawLogConfig, Report, ReportFault, SingleModule,
VehicleModule, WriteConfirmation,
};
use opendiag_transport::{
list_serial_ports, open_can, Elm327, Elm327Emulator, Elm327Serial, KLineSerial, SerialIo,
Expand Down Expand Up @@ -79,13 +80,18 @@ enum Cmd {
#[command(subcommand)]
action: DataCmd,
},
/// Log live measuring-block data to CSV (KW1281 modules). Values are raw cells.
/// Log live data to CSV. KW1281: measuring-block groups (`--groups`, raw cells).
/// KWP2000 and UDS: raw bytes by identifier (`--ids`), logged as hex and not interpreted.
Log {
#[command(flatten)]
target: Target,
/// Measuring-block groups to read each round, e.g. --groups 1,2.
#[arg(long, value_delimiter = ',', required = true)]
#[arg(long, value_delimiter = ',', required_unless_present = "ids")]
groups: Vec<u8>,
/// Identifiers to read each round, in hex, e.g. --ids 0x01,0x02 (KWP2000 local
/// identifiers) or --ids 0xF190 (UDS data identifiers).
#[arg(long, value_delimiter = ',', value_parser = parse_hex_u16, conflicts_with = "groups")]
ids: Vec<u16>,
/// Stop after this many rounds (default 20 if no limit is given).
#[arg(long)]
samples: Option<u32>,
Expand Down Expand Up @@ -175,6 +181,12 @@ fn parse_hex_u8(s: &str) -> Result<u8, String> {
u8::from_str_radix(digits, 16).map_err(|_| format!("`{s}` is not a hex byte (e.g. 0x01)"))
}

fn parse_hex_u16(s: &str) -> Result<u16, String> {
let digits = s.trim_start_matches("0x").trim_start_matches("0X");
u16::from_str_radix(digits, 16)
.map_err(|_| format!("`{s}` is not a hex identifier (e.g. 0x01 or 0xF190)"))
}

fn parse_hex_u32(s: &str) -> Result<u32, String> {
let digits = s.trim_start_matches("0x").trim_start_matches("0X");
u32::from_str_radix(digits, 16).map_err(|_| format!("`{s}` is not a hex number (e.g. 0x7E0)"))
Expand Down Expand Up @@ -462,6 +474,7 @@ fn main() -> ExitCode {
Some(Cmd::Log {
target,
groups,
ids,
samples,
duration_secs,
interval_ms,
Expand All @@ -471,12 +484,22 @@ fn main() -> ExitCode {
Some(s) => Limit::Duration(Duration::from_secs(s)),
None => Limit::Samples(samples.unwrap_or(20)),
};
let cfg = LogConfig {
groups,
interval: Duration::from_millis(interval_ms),
limit,
};
log_cmd(&target, &cfg, out.as_deref())
let interval = Duration::from_millis(interval_ms);
if ids.is_empty() {
let cfg = LogConfig {
groups,
interval,
limit,
};
log_cmd(&target, &cfg, out.as_deref())
} else {
let cfg = RawLogConfig {
ids,
interval,
limit,
};
log_raw_cmd(&target, &cfg, out.as_deref())
}
}
Some(Cmd::Report { target, out }) => report_cmd(&target, out.as_deref()),
Some(Cmd::Serve {
Expand Down Expand Up @@ -1385,6 +1408,34 @@ fn log_cmd(target: &Target, cfg: &LogConfig, out: Option<&Path>) -> Result<(), S
Ok(())
}

fn log_raw_cmd(target: &Target, cfg: &RawLogConfig, out: Option<&Path>) -> Result<(), String> {
let mut conn = connect(target)?;
let raw = conn.module.raw_data().ok_or(
"raw identifiers are only available over KWP2000 and UDS (use --ids with --fast-init, --can or a UDS connection); \
KW1281 modules use --groups",
)?;
let clock = SystemClock::new();
let summary = match out {
Some(path) => {
let file = std::fs::File::create(path)
.map_err(|e| format!("cannot create {}: {e}", path.display()))?;
let mut w = io::BufWriter::new(file);
log_raw_csv(raw, &clock, cfg, &mut w).map_err(|e| e.to_string())?
}
None => {
log_raw_csv(raw, &clock, cfg, &mut io::stdout().lock()).map_err(|e| e.to_string())?
}
};
eprintln!(
"Logged {} round(s), {} row(s){}.",
summary.samples,
summary.rows,
out.map(|p| format!(" to {}", p.display()))
.unwrap_or_default()
);
Ok(())
}

fn data_validate(dir: &Path) -> Result<(), String> {
match load_dir(dir) {
Ok(set) => {
Expand Down
80 changes: 79 additions & 1 deletion crates/opendiag-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ fn kwp2000_trace_starts_with_the_fast_init_wakeup() {
}

#[test]
fn kwp2000_has_no_live_data_or_adaptation_yet() {
fn kwp2000_has_no_measuring_block_groups_or_adaptation() {
let (ok, _, err) = run(&["log", "--simulate-kwp", "--groups", "1"], "");
assert!(!ok && err.contains("only available for KW1281"), "{err}");
let (ok, _, err) = run(
Expand Down Expand Up @@ -1756,3 +1756,81 @@ fn a_replayed_report_says_so() {
assert!(html.contains("REPLAYED DATA"), "{html}");
assert!(!html.contains("SIMULATED DATA"), "{html}");
}

// ---- log --ids: raw bytes by identifier over KWP2000 and UDS ----

#[test]
fn log_ids_writes_raw_hex_for_kwp2000_and_uds() {
let (ok, out, err) = run(
&[
"log",
"--simulate-kwp",
"--ids",
"0x01,0x02",
"--samples",
"2",
"--interval-ms",
"10",
],
"",
);
assert!(ok, "{err}");
let lines: Vec<&str> = out.lines().collect();
assert_eq!(lines[0], "time_ms,id,length,hex");
assert_eq!(lines.len(), 5, "{out}");
assert!(lines[1].starts_with("0,0x0001,4,1020300"), "{out}");

let (ok, out, err) = run(
&["log", "--simulate", "--ids", "0xF190", "--samples", "1"],
"",
);
assert!(ok, "{err}");
assert!(out.contains("0,0xF190,17,44454D4F"), "{out}");
}

#[test]
fn log_ids_is_refused_for_kw1281_and_needs_groups_or_ids_but_not_both() {
let (ok, _, err) = run(&["log", "--simulate-kw1281", "--ids", "0x01"], "");
assert!(!ok && err.contains("KW1281 modules use --groups"), "{err}");
let (ok, _, err) = run(&["log", "--simulate-kwp"], "");
assert!(!ok && err.contains("--groups"), "{err}");
let (ok, _, err) = run(
&["log", "--simulate-kwp", "--groups", "1", "--ids", "1"],
"",
);
assert!(!ok && err.contains("cannot be used with"), "{err}");
let (ok, _, err) = run(&["log", "--simulate-kwp", "--ids", "0xZZ"], "");
assert!(!ok && err.contains("not a hex identifier"), "{err}");
}

#[test]
fn log_ids_can_be_replayed_from_a_recording() {
assert_replay_matches(
&[
"log",
"--ids",
"0x01,0x02",
"--samples",
"3",
"--interval-ms",
"10",
],
"--simulate-kwp",
&["--fast-init"],
"kwp-raw-log",
);
assert_replay_matches(
&[
"log",
"--ids",
"0xF190",
"--samples",
"2",
"--interval-ms",
"10",
],
"--simulate",
&[],
"uds-raw-log",
);
}
28 changes: 28 additions & 0 deletions crates/opendiag-proto/src/kwp/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ pub struct KwpSim {
keywords: (u8, u8),
ident: Vec<u8>,
faults: Vec<(u16, u8)>,
/// ReadDataByLocalIdentifier (0x21) data by id; the last byte changes on every read.
local_data: Vec<(u8, Vec<u8>)>,
local_reads: u8,
echo: bool,

parser: Parser,
Expand All @@ -46,6 +49,8 @@ impl KwpSim {
keywords: (0xEF, 0x8F),
ident: Vec::new(),
faults: Vec::new(),
local_data: Vec::new(),
local_reads: 0,
echo: true,
parser: Parser::new(),
inbox: VecDeque::new(),
Expand Down Expand Up @@ -77,6 +82,13 @@ impl KwpSim {
self
}

/// Data returned for ReadDataByLocalIdentifier `id`. To look alive, the last byte is
/// increased by one for every read of any local identifier (wrapping).
pub fn local_data(mut self, id: u8, data: &[u8]) -> Self {
self.local_data.push((id, data.to_vec()));
self
}

pub fn fault(mut self, code: u16, status: u8) -> Self {
self.faults.push((code, status));
self
Expand Down Expand Up @@ -159,6 +171,22 @@ impl KwpSim {
self.reply(r);
}
0x1A => self.negative(sid, 0x12),
0x21 => {
let id = arg(1);
match self.local_data.iter().find(|(i, _)| *i == id) {
Some((_, data)) => {
let mut r = vec![0x61, id];
r.extend_from_slice(data);
if let Some(last) = r.last_mut().filter(|_| !data.is_empty()) {
*last = last.wrapping_add(self.local_reads);
}
self.local_reads = self.local_reads.wrapping_add(1);
self.reply(r);
}
// requestOutOfRange
None => self.negative(sid, 0x31),
}
}
0x18 => {
let mut r = vec![0x58, self.faults.len() as u8];
for &(code, status) in &self.faults {
Expand Down
3 changes: 3 additions & 0 deletions crates/opendiag-services/src/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ pub fn virtual_kwp_bus() -> KwpSim {
.ident(b"VIRTUAL KWP2000 ECU")
.fault(12345, 0x20)
.fault(54321, 0x01)
// Made-up raw data for the local identifiers 0x01 and 0x02.
.local_data(0x01, &[0x10, 0x20, 0x30, 0x00])
.local_data(0x02, &[0x00, 0x64])
}

/// The virtual KWP2000 module with its session open.
Expand Down
21 changes: 20 additions & 1 deletion crates/opendiag-services/src/kwp_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use opendiag_core::{Error, Result, WriteMode};
use opendiag_proto::kwp::KwpService;

use crate::{DtcReport, FaultAccess, Ident, Module, WriteToken};
use crate::{DtcReport, FaultAccess, Ident, Module, RawData, WriteToken};

/// Diagnostic session mode requested after connecting. It is the mode that
/// appears in the public TP2.0 capture; not verified on K-line modules.
Expand Down Expand Up @@ -125,6 +125,25 @@ impl<S: KwpService> Module for KwpModule<S> {
fn keep_alive(&mut self) -> Result<()> {
self.service.tester_present()
}

fn raw_data(&mut self) -> Option<&mut dyn RawData> {
Some(self)
}
}

impl<S: KwpService> RawData for KwpModule<S> {
fn id_kind(&self) -> &'static str {
"local identifier"
}

fn read_raw(&mut self, id: u16) -> Result<Vec<u8>> {
let id = u8::try_from(id).map_err(|_| {
Error::Protocol(format!(
"{id:#06X} is not a KWP2000 local identifier (one byte, up to 0xFF)"
))
})?;
self.service.read_data_by_local_identifier(id)
}
}

impl<S: KwpService> FaultAccess for KwpModule<S> {
Expand Down
21 changes: 21 additions & 0 deletions crates/opendiag-services/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod fault_clear;
mod kw1281_module;
mod kwp_module;
pub mod live;
pub mod raw_data;
pub mod report;
pub mod vehicle;

Expand All @@ -27,6 +28,7 @@ pub use fault_clear::{apply_clear, plan_clear, ClearConfirmation, ClearOutcome,
pub use kw1281_module::Kw1281Module;
pub use kwp_module::KwpModule;
pub use live::{log_csv, Limit, LiveData, LogConfig, LogSummary, CSV_HEADER};
pub use raw_data::{log_raw_csv, RawData, RawLogConfig, RAW_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,
Expand Down Expand Up @@ -149,6 +151,11 @@ pub trait Module {
None
}

/// Raw bytes by identifier, if the protocol has it (KWP2000 and UDS).
fn raw_data(&mut self) -> Option<&mut dyn RawData> {
None
}

/// Adaptation channels, if this kind of module has them (KW1281 only so far).
fn adaptation(&mut self) -> Option<&mut dyn AdaptationAccess> {
None
Expand All @@ -171,6 +178,20 @@ impl<L: MessageLink> Module for UdsClient<L> {
fn keep_alive(&mut self) -> Result<()> {
self.tester_present()
}

fn raw_data(&mut self) -> Option<&mut dyn RawData> {
Some(self)
}
}

impl<L: MessageLink> RawData for UdsClient<L> {
fn id_kind(&self) -> &'static str {
"data identifier (DID)"
}

fn read_raw(&mut self, id: u16) -> Result<Vec<u8>> {
self.read_data_by_identifier(id)
}
}

impl<L: MessageLink> FaultAccess for UdsClient<L> {
Expand Down
Loading
Loading