From a942013395bc5edc5144c9c5d4ea6f7d635178f2 Mon Sep 17 00:00:00 2001 From: JoeeDeveloper <20745897+JoeeDeveloper@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:26:30 +0000 Subject: [PATCH] feat(services,cli): log --ids reads raw bytes by identifier over KWP2000 and UDS ReadDataByLocalIdentifier (0x21) and ReadDataByIdentifier (0x22) are logged as uninterpreted hex. No public source was found for the VAG measuring-block layout over KWP2000, so nothing is decoded (see docs/sources.md). Also refreshes the stale status line in CLAUDE.md and the README. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Xe1HmJJjhbWaBGaF6FKosA --- CLAUDE.md | 2 +- README.md | 2 +- crates/opendiag-cli/src/main.rs | 73 +++++++++++--- crates/opendiag-cli/tests/cli.rs | 80 +++++++++++++++- crates/opendiag-proto/src/kwp/sim.rs | 28 ++++++ crates/opendiag-services/src/demo.rs | 3 + crates/opendiag-services/src/kwp_module.rs | 21 +++- crates/opendiag-services/src/lib.rs | 21 ++++ crates/opendiag-services/src/live.rs | 83 +++++++++------- crates/opendiag-services/src/raw_data.rs | 70 ++++++++++++++ crates/opendiag-services/src/vehicle.rs | 8 +- crates/opendiag-services/tests/raw_data.rs | 106 +++++++++++++++++++++ docs/sources.md | 5 + docs/status.md | 2 +- 14 files changed, 455 insertions(+), 49 deletions(-) create mode 100644 crates/opendiag-services/src/raw_data.rs create mode 100644 crates/opendiag-services/tests/raw_data.rs diff --git a/CLAUDE.md b/CLAUDE.md index faa69cb..93826c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,4 +58,4 @@ It extracts the Windows build (ready to run, `.exe` already executable) into `, + /// 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, /// Stop after this many rounds (default 20 if no limit is given). #[arg(long)] samples: Option, @@ -175,6 +181,12 @@ fn parse_hex_u8(s: &str) -> Result { 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 { + 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 { 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)")) @@ -462,6 +474,7 @@ fn main() -> ExitCode { Some(Cmd::Log { target, groups, + ids, samples, duration_secs, interval_ms, @@ -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 { @@ -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) => { diff --git a/crates/opendiag-cli/tests/cli.rs b/crates/opendiag-cli/tests/cli.rs index 8f5ea13..2cf9907 100644 --- a/crates/opendiag-cli/tests/cli.rs +++ b/crates/opendiag-cli/tests/cli.rs @@ -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( @@ -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", + ); +} diff --git a/crates/opendiag-proto/src/kwp/sim.rs b/crates/opendiag-proto/src/kwp/sim.rs index 1e09b8e..1b23347 100644 --- a/crates/opendiag-proto/src/kwp/sim.rs +++ b/crates/opendiag-proto/src/kwp/sim.rs @@ -20,6 +20,9 @@ pub struct KwpSim { keywords: (u8, u8), ident: Vec, faults: Vec<(u16, u8)>, + /// ReadDataByLocalIdentifier (0x21) data by id; the last byte changes on every read. + local_data: Vec<(u8, Vec)>, + local_reads: u8, echo: bool, parser: Parser, @@ -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(), @@ -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 @@ -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 { diff --git a/crates/opendiag-services/src/demo.rs b/crates/opendiag-services/src/demo.rs index e5d5b17..f138020 100644 --- a/crates/opendiag-services/src/demo.rs +++ b/crates/opendiag-services/src/demo.rs @@ -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. diff --git a/crates/opendiag-services/src/kwp_module.rs b/crates/opendiag-services/src/kwp_module.rs index d59e09b..58dbfa0 100644 --- a/crates/opendiag-services/src/kwp_module.rs +++ b/crates/opendiag-services/src/kwp_module.rs @@ -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. @@ -125,6 +125,25 @@ impl Module for KwpModule { fn keep_alive(&mut self) -> Result<()> { self.service.tester_present() } + + fn raw_data(&mut self) -> Option<&mut dyn RawData> { + Some(self) + } +} + +impl RawData for KwpModule { + fn id_kind(&self) -> &'static str { + "local identifier" + } + + fn read_raw(&mut self, id: u16) -> Result> { + 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 FaultAccess for KwpModule { diff --git a/crates/opendiag-services/src/lib.rs b/crates/opendiag-services/src/lib.rs index fa1b482..37b82fb 100644 --- a/crates/opendiag-services/src/lib.rs +++ b/crates/opendiag-services/src/lib.rs @@ -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; @@ -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, @@ -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 @@ -171,6 +178,20 @@ impl Module for UdsClient { fn keep_alive(&mut self) -> Result<()> { self.tester_present() } + + fn raw_data(&mut self) -> Option<&mut dyn RawData> { + Some(self) + } +} + +impl RawData for UdsClient { + fn id_kind(&self) -> &'static str { + "data identifier (DID)" + } + + fn read_raw(&mut self, id: u16) -> Result> { + self.read_data_by_identifier(id) + } } impl FaultAccess for UdsClient { diff --git a/crates/opendiag-services/src/live.rs b/crates/opendiag-services/src/live.rs index c68d133..9c84722 100644 --- a/crates/opendiag-services/src/live.rs +++ b/crates/opendiag-services/src/live.rs @@ -47,12 +47,54 @@ fn io_err(e: std::io::Error) -> Error { Error::Io(e.to_string()) } +/// Run `round` on a fixed time grid until `limit`; `round` gets the logged time in ms and +/// returns how many rows it wrote. +/// +/// Rounds start on a grid (`interval` apart) so timestamps do not drift. If a round takes +/// longer than the interval, the missed rounds are skipped rather than fired back to back. +pub(crate) fn run_rounds( + clock: &C, + interval: Duration, + limit: Limit, + mut round: impl FnMut(u128) -> Result, +) -> Result { + if interval.is_zero() { + return Err(Error::Protocol( + "live data: interval must be above zero".into(), + )); + } + let start = clock.now(); + let mut summary = LogSummary { + samples: 0, + rows: 0, + }; + let mut tick: u32 = 0; + // A schedule too far out to represent is the end of any real log. + while let Some(scheduled) = interval.checked_mul(tick) { + match limit { + Limit::Samples(n) if summary.samples >= n => break, + Limit::Duration(d) if scheduled >= d => break, + _ => {} + } + clock.wait_until(start + scheduled); + let time_ms = (clock.now() - start).as_millis(); + summary.rows += round(time_ms)?; + summary.samples += 1; + + // Next grid point after "now"; never fire missed rounds back to back. + let elapsed = clock.now() - start; + let after_now = u32::try_from(elapsed.as_nanos() / interval.as_nanos()) + .unwrap_or(u32::MAX) + .saturating_add(1); + tick = tick.saturating_add(1).max(after_now); + } + Ok(summary) +} + /// Log `cfg.groups` from `source` to `out` as CSV at a fixed rate. /// -/// Rounds start on a fixed grid (`interval` apart) so timestamps do not drift. -/// If reading takes longer than the interval, the missed rounds are skipped -/// rather than fired back to back. Output is flushed after every round, so a -/// failure part-way through still leaves the earlier rows in the file. +/// Output is flushed after every round, so a failure part-way through still leaves the +/// earlier rows in the file. pub fn log_csv( source: &mut L, clock: &C, @@ -73,23 +115,8 @@ where )); } writeln!(out, "{CSV_HEADER}").map_err(io_err)?; - - let start = clock.now(); - let mut summary = LogSummary { - samples: 0, - rows: 0, - }; - let mut tick: u32 = 0; - // A schedule too far out to represent is the end of any real log. - while let Some(scheduled) = cfg.interval.checked_mul(tick) { - match cfg.limit { - Limit::Samples(n) if summary.samples >= n => break, - Limit::Duration(d) if scheduled >= d => break, - _ => {} - } - clock.wait_until(start + scheduled); - let time_ms = (clock.now() - start).as_millis(); - + run_rounds(clock, cfg.interval, cfg.limit, |time_ms| { + let mut rows = 0; for &group in &cfg.groups { let cells = source.read_group(group)?; for (i, c) in cells.iter().enumerate() { @@ -102,18 +129,10 @@ where c.b ) .map_err(io_err)?; - summary.rows += 1; + rows += 1; } } out.flush().map_err(io_err)?; - summary.samples += 1; - - // Next grid point after "now"; never fire missed rounds back to back. - let elapsed = clock.now() - start; - let after_now = u32::try_from(elapsed.as_nanos() / cfg.interval.as_nanos()) - .unwrap_or(u32::MAX) - .saturating_add(1); - tick = tick.saturating_add(1).max(after_now); - } - Ok(summary) + Ok(rows) + }) } diff --git a/crates/opendiag-services/src/raw_data.rs b/crates/opendiag-services/src/raw_data.rs new file mode 100644 index 0000000..9cd2c98 --- /dev/null +++ b/crates/opendiag-services/src/raw_data.rs @@ -0,0 +1,70 @@ +//! Raw data by identifier: read what a module returns for an identifier and log it as hex, +//! without interpreting it. +//! +//! Over KWP2000 this is ReadDataByLocalIdentifier (0x21) and over UDS ReadDataByIdentifier +//! (0x22). The layout of the returned bytes is module-specific and, for VAG measuring blocks +//! over KWP2000, not documented in a public source we could cite. So nothing is decoded here: +//! the bytes are logged as they arrive, and a decoder belongs in the open data format once a +//! source or a real capture exists. + +use std::io::Write; + +use opendiag_core::{Error, Result}; +use opendiag_proto::clock::Clock; + +use crate::live::{run_rounds, Limit, LogSummary}; + +/// A module that returns raw bytes for an identifier. +pub trait RawData { + /// What an identifier is called on this protocol, for messages. + fn id_kind(&self) -> &'static str; + /// Read one identifier. Identifiers the protocol cannot express are an error. + fn read_raw(&mut self, id: u16) -> Result>; +} + +#[derive(Debug, Clone)] +pub struct RawLogConfig { + pub ids: Vec, + pub interval: std::time::Duration, + pub limit: Limit, +} + +/// One row per identifier read: the bytes have no known structure to split into cells. +pub const RAW_CSV_HEADER: &str = "time_ms,id,length,hex"; + +fn io_err(e: std::io::Error) -> Error { + Error::Io(e.to_string()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02X}")).collect() +} + +/// Log `cfg.ids` from `source` to `out` as CSV at a fixed rate (same schedule as +/// [`log_csv`](crate::log_csv): a fixed grid, missed rounds skipped, flushed every round). +pub fn log_raw_csv( + source: &mut R, + clock: &C, + cfg: &RawLogConfig, + out: &mut W, +) -> Result +where + R: RawData + ?Sized, + C: Clock, + W: Write, +{ + if cfg.ids.is_empty() { + return Err(Error::Protocol("raw data: no identifiers to log".into())); + } + writeln!(out, "{RAW_CSV_HEADER}").map_err(io_err)?; + run_rounds(clock, cfg.interval, cfg.limit, |time_ms| { + let mut rows = 0; + for &id in &cfg.ids { + let data = source.read_raw(id)?; + writeln!(out, "{time_ms},{id:#06X},{},{}", data.len(), hex(&data)).map_err(io_err)?; + rows += 1; + } + out.flush().map_err(io_err)?; + Ok(rows) + }) +} diff --git a/crates/opendiag-services/src/vehicle.rs b/crates/opendiag-services/src/vehicle.rs index faf730e..1551a28 100644 --- a/crates/opendiag-services/src/vehicle.rs +++ b/crates/opendiag-services/src/vehicle.rs @@ -12,7 +12,9 @@ use opendiag_core::{Error, Result}; -use crate::{AdaptationAccess, DtcReport, FaultAccess, Ident, LiveData, Module, WriteToken}; +use crate::{ + AdaptationAccess, DtcReport, FaultAccess, Ident, LiveData, Module, RawData, WriteToken, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Brand { @@ -199,6 +201,10 @@ impl Module for VehicleModule { self.vehicle.ecu(self.id).ok()?.live() } + fn raw_data(&mut self) -> Option<&mut dyn RawData> { + self.vehicle.ecu(self.id).ok()?.raw_data() + } + fn adaptation(&mut self) -> Option<&mut dyn AdaptationAccess> { self.vehicle.ecu(self.id).ok()?.adaptation() } diff --git a/crates/opendiag-services/tests/raw_data.rs b/crates/opendiag-services/tests/raw_data.rs new file mode 100644 index 0000000..faed5af --- /dev/null +++ b/crates/opendiag-services/tests/raw_data.rs @@ -0,0 +1,106 @@ +use std::time::Duration; + +use opendiag_core::{Error, Result}; +use opendiag_proto::clock::{Clock, FakeClock}; +use opendiag_services::demo::{virtual_kwp_module, virtual_uds_client}; +use opendiag_services::{log_raw_csv, Limit, Module, RawData, RawLogConfig, RAW_CSV_HEADER}; + +fn cfg(ids: &[u16], interval_ms: u64, limit: Limit) -> RawLogConfig { + RawLogConfig { + ids: ids.to_vec(), + interval: Duration::from_millis(interval_ms), + limit, + } +} + +fn log( + src: &mut dyn RawData, + cfg: &RawLogConfig, +) -> (Result, String) { + let clock = FakeClock::new(); + let mut out = Vec::new(); + let r = log_raw_csv(src, &clock, cfg, &mut out); + (r, String::from_utf8(out).unwrap()) +} + +#[test] +fn kwp_local_identifiers_are_logged_as_uninterpreted_hex_on_a_steady_grid() { + let mut m = virtual_kwp_module().unwrap(); + let raw = m.raw_data().expect("KWP2000 offers raw data"); + assert_eq!(raw.id_kind(), "local identifier"); + let (r, csv) = log(raw, &cfg(&[1, 2], 100, Limit::Samples(2))); + let s = r.unwrap(); + assert_eq!((s.samples, s.rows), (2, 4)); + let lines: Vec<&str> = csv.lines().collect(); + assert_eq!(lines[0], RAW_CSV_HEADER); + // time, id, length, hex: the module's bytes, nothing decoded. + assert_eq!(lines[1], "0,0x0001,4,10203000"); + assert_eq!(lines[2], "0,0x0002,2,0065"); + assert!(lines[3].starts_with("100,0x0001,4,"), "{}", lines[3]); + assert_ne!( + lines[1][8..], + lines[3][10..], + "the demo values move between reads" + ); +} + +#[test] +fn uds_data_identifiers_are_logged_too() { + let mut m = virtual_uds_client(); + let raw = m.raw_data().expect("UDS offers raw data"); + let (r, csv) = log(raw, &cfg(&[0xF190], 50, Limit::Samples(1))); + r.unwrap(); + assert!( + csv.contains("0,0xF190,17,44454D4F303030303030303056494E3031"), + "{csv}" + ); +} + +#[test] +fn an_identifier_the_protocol_cannot_express_is_refused_before_anything_is_sent() { + let mut m = virtual_kwp_module().unwrap(); + let raw = m.raw_data().unwrap(); + let (r, _) = log(raw, &cfg(&[0x1FF], 100, Limit::Samples(1))); + assert!(matches!(r, Err(Error::Protocol(m)) if m.contains("local identifier"))); +} + +#[test] +fn an_unknown_identifier_is_the_modules_negative_response_not_a_guess() { + let mut m = virtual_kwp_module().unwrap(); + let raw = m.raw_data().unwrap(); + let (r, csv) = log(raw, &cfg(&[1, 0x99], 100, Limit::Samples(1))); + assert!(matches!(r, Err(Error::NegativeResponse { .. })), "{r:?}"); + // The row read before the failure is already in the output. + assert!(csv.contains("0,0x0001,4,"), "{csv}"); +} + +#[test] +fn no_identifiers_or_a_zero_interval_is_refused() { + let mut m = virtual_kwp_module().unwrap(); + let raw = m.raw_data().unwrap(); + assert!(log(raw, &cfg(&[], 100, Limit::Samples(1))).0.is_err()); + assert!(log(raw, &cfg(&[1], 0, Limit::Samples(1))).0.is_err()); +} + +#[test] +fn a_duration_limit_stops_on_the_grid() { + let clock = FakeClock::new(); + let mut m = virtual_kwp_module().unwrap(); + let raw = m.raw_data().unwrap(); + let mut out = Vec::new(); + let s = log_raw_csv( + raw, + &clock, + &cfg(&[1], 100, Limit::Duration(Duration::from_millis(300))), + &mut out, + ) + .unwrap(); + assert_eq!(s.samples, 3); + assert_eq!(clock.now(), Duration::from_millis(200)); +} + +#[test] +fn kw1281_has_no_raw_identifiers() { + let mut m = opendiag_services::demo::virtual_kw1281_module().unwrap(); + assert!(m.raw_data().is_none()); +} diff --git a/docs/sources.md b/docs/sources.md index f4b77ab..540dc70 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -20,3 +20,8 @@ Do not cite or derive from Ross-Tech label files, VCDS or ODIS. - 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. + +## Raw data by identifier over KWP2000 and UDS (`log --ids`) + +- ISO 14230-3 (ReadDataByLocalIdentifier 0x21) and ISO 14229 (ReadDataByIdentifier 0x22): the request/response structure only. +- Searched 2026-11-24 for a public description of how VAG modules lay out measuring-block bytes in an 0x21 response. Found only an unverified community snippet (jazdw-software group, one display type) and a note in PyVCDS that "block" is a KWP1281 holdover; nothing authoritative for the (display type, a, b) layout over KWP2000. Therefore **the returned bytes are logged raw and never decoded**. Add the source here, and a decoder to the open data format, when one exists or a real capture confirms it. diff --git a/docs/status.md b/docs/status.md index 89ccf14..d35795e 100644 --- a/docs/status.md +++ b/docs/status.md @@ -55,7 +55,7 @@ Real captures are the only thing that can, which is why `--trace`/`capture` and now share one `KwpService` trait.) - **KWP2000 in `scan`/`dtc` is VAG-unverified.** It follows ISO 14230-3: the session mode (0x89, from the public TP2.0 capture), the identification option (0x9B) and the fault-code display (5-digit decimal, raw status byte) - are assumptions. Identification is shown raw with no part number claimed. There is no live data or adaptation + are assumptions. Identification is shown raw with no part number claimed. There is no decoded live data or adaptation over KWP2000 yet. - `Drop` on a dead link can block for one byte timeout (~1 s) while it tries to end the session. - `serde_yaml` is unmaintained upstream; plan a migration. YAML alias expansion was measured and is bounded.