cal_model/lib.rs
1//! A2L calibration data model and session layer — characteristic binding,
2//! COMPU_METHOD conversions, limit validation, curve calibration.
3//!
4//! `cal-model` is the estate's **L2 application layer** for the automotive
5//! calibration stack. It sits on three L0/L1 substrates and turns their
6//! declarations into an actionable calibration session:
7//!
8//! | Substrate | Layer | What it contributes |
9//! |---|---|---|
10//! | [`a2l_parse`] | L1 | the A2L description: addresses, datatypes, limits, COMPU_METHODs |
11//! | [`dbc_parse`] | L0 | the CAN layout: start bit, width, byte order, scaling |
12//! | [`xcp_core`] | L1 | the XCP protocol: resource masks, command framing |
13//!
14//! # The layer's job
15//!
16//! ```text
17//! A2L text ──a2l_parse──► PROJECT/MODULE/CHARACTERISTIC/MEASUREMENT
18//! │ resolve every reference
19//! ▼
20//! CalibrationProject ──── dbc_parse ───► SignalBinding
21//! │
22//! COMPU_METHOD ◄─────────────┤ apply / invert LOWER_LIMIT / UPPER_LIMIT
23//! ▼
24//! CalibrationSession ──── XcpTransport ───► ECU
25//! │ read / write / SET_CAL_PAGE
26//! ▼
27//! Snapshot ──► diff ──► CalibrationDelta report
28//! ```
29//!
30//! Five things happen here that no substrate does:
31//!
32//! 1. **Reference resolution.** A characteristic whose `COMPU_METHOD` or
33//! `RECORD_LAYOUT` is undeclared, or whose `COMPU_TAB_REF` has no
34//! registered points, is a typed [`CalError::Unsupported`] — never a
35//! silently defaulted conversion. A wrong conversion writes the wrong
36//! number into an ECU.
37//! 2. **Inversion.** [`to_physical`](CalibrationProject::to_physical) is
38//! evaluation; [`to_raw`](CalibrationProject::to_raw) is the part that
39//! matters, and it bracket-checks against the deposit's datatype range so
40//! the tool cannot ask for a value the ECU cannot hold.
41//! 3. **Transport framing.** [`XcpTransport`] is deliberately two methods
42//! wide, which makes a session testable against [`mock::MockTransport`]
43//! while [`CalibrationSession::upload_frames`] and friends hand a real
44//! bridge the exact `xcp_core` frames to send.
45//! 4. **Verified writes.** A session write reads the value back and fails if
46//! the ECU did not latch it.
47//! 5. **Calibration arithmetic.** [`calibrate_curve`] fits a monotone
48//! piecewise-linear curve through measured nodes;
49//! [`optimize_working_point`] finds a bounded working point by
50//! deterministic coordinate descent.
51//!
52//! # Raw values are bit patterns
53//!
54//! Every raw value in this crate is the **memory bit pattern**, so a signed
55//! `SBYTE` characteristic holding −1 °C reads `0xFF`. Sign extension happens
56//! in [`Characteristic::raw_value`], on the way into the conversion, and in
57//! [`Characteristic::raw_bits`], on the way out. This is what makes a
58//! read-modify-write cycle bit-exact: nothing is re-derived from a float.
59//!
60//! # Example
61//!
62//! ```
63//! use cal_model::{
64//! CalibrationProject, CalibrationSession, CalError, ResourceMode, XcpTransport, SAMPLE_A2L,
65//! };
66//! # fn main() -> Result<(), CalError> {
67//!
68//! // 1. Load the description and resolve every reference it makes.
69//! let mut project = CalibrationProject::from_a2l(SAMPLE_A2L)?;
70//! project.register_table("boost_curve_tab", vec![(0.0, 0.0), (6000.0, 150.0)])?;
71//! assert_eq!(project.module("engine")?.characteristics.len(), 9);
72//!
73//! // 2. Look a parameter up and convert both ways.
74//! let idle = project.characteristic("engine", "idle_target_rpm")?;
75//! assert_eq!(idle.address, 0x720108);
76//! // 3200 counts · 0.25 rpm/count = 800 rpm.
77//! let physical = project.to_physical("engine", "idle_target_rpm", 3200)?;
78//! assert!((physical - 800.0).abs() < 1e-9, "{physical}");
79//! assert_eq!(project.to_raw("engine", "idle_target_rpm", 800.0)?, 3200);
80//!
81//! // 3. Limits are enforced on the way in.
82//! project.check_limits("engine", "idle_target_rpm", 3200)?;
83//! assert!(project.check_limits("engine", "idle_target_rpm", 0).is_err());
84//!
85//! // 4. Calibrate against a bench ECU: write, read back, diff.
86//! let bench = cal_model::mock::MockTransport::seeded(&cal_model::seed_memory());
87//! let mut session = CalibrationSession::connect(
88//! &project, Box::new(bench), ResourceMode::CONNECT_NORMAL,
89//! )?;
90//! // The seed memory holds 800 rpm; the write is limit-checked (500…1200),
91//! // inverted through `rpm_lin`, and read back before it is reported.
92//! session.write_characteristic("engine", "idle_target_rpm", 900.0)?;
93//! let live = session.read_characteristic("engine", "idle_target_rpm")?;
94//! assert!((live - 900.0).abs() < 1e-9, "{live}");
95//!
96//! // 5. Snapshot, adjust, and report the diff.
97//! let before = session.snapshot(&["idle_target_rpm", "eng_torque_max"])?;
98//! session.write_characteristic("engine", "idle_target_rpm", 950.0)?;
99//! let after = session.snapshot(&["idle_target_rpm", "eng_torque_max"])?;
100//! let deltas = cal_model::diff_snapshots(Some(&before), &after, &project);
101//! assert_eq!(deltas[0].before, 900.0);
102//! assert_eq!(deltas[0].after, 950.0);
103//! assert!((deltas[0].delta - 50.0).abs() < 1e-9);
104//! assert!(deltas[0].within_limits);
105//! # Ok(())
106//! # }
107//! ```
108
109// A2L/ASAM grammar keywords (CHARACTERISTIC, COMPU_METHOD, ECU_ADDRESS …)
110// are proper nouns of the formats this crate reads; backticking every
111// occurrence would bury the prose. Allowed with this justification per the
112// fleet pedantic policy.
113#![allow(clippy::doc_markdown)]
114
115mod calibrate;
116mod conversion;
117mod error;
118pub mod mock;
119mod model;
120mod project;
121pub mod sample;
122mod session;
123mod signal;
124
125pub use calibrate::{calibrate_curve, optimal_point, optimize_working_point, CalParameter, Curve};
126pub use conversion::CompuMethod;
127pub use dbc_parse::ByteOrder;
128pub use error::CalError;
129pub use model::{CharKind, Characteristic, Measurement, Module};
130pub use project::CalibrationProject;
131pub use sample::{
132 complete, element_counts, sample_project, seed_memory, tables, SAMPLE_A2L, SAMPLE_DBC,
133};
134pub use session::{
135 diff_snapshots, render_deltas, CalibrationDelta, CalibrationSession, Snapshot, SnapshotEntry,
136 SnapshotValue, XcpTransport,
137};
138pub use signal::SignalBinding;
139pub use xcp_core::ResourceMode;
140
141/// Re-export of the A2L substrate, so a consumer needs one dependency.
142pub use a2l_parse as a2l;
143/// Re-export of the DBC substrate, so a consumer needs one dependency.
144pub use dbc_parse as dbc;
145/// Re-export of the XCP substrate, so a consumer needs one dependency.
146pub use xcp_core as xcp;