Skip to main content

Crate cal_model

Crate cal_model 

Source
Expand description

A2L calibration data model and session layer — characteristic binding, COMPU_METHOD conversions, limit validation, curve calibration.

cal-model is the estate’s L2 application layer for the automotive calibration stack. It sits on three L0/L1 substrates and turns their declarations into an actionable calibration session:

SubstrateLayerWhat it contributes
a2l_parseL1the A2L description: addresses, datatypes, limits, COMPU_METHODs
dbc_parseL0the CAN layout: start bit, width, byte order, scaling
xcp_coreL1the XCP protocol: resource masks, command framing

§The layer’s job

  A2L text ──a2l_parse──► PROJECT/MODULE/CHARACTERISTIC/MEASUREMENT
                                 │  resolve every reference
                                 ▼
                         CalibrationProject ──── dbc_parse ───► SignalBinding
                                 │
       COMPU_METHOD ◄─────────────┤ apply / invert      LOWER_LIMIT / UPPER_LIMIT
                                 ▼
                         CalibrationSession ──── XcpTransport ───► ECU
                                 │ read / write / SET_CAL_PAGE
                                 ▼
                         Snapshot ──► diff ──► CalibrationDelta report

Five things happen here that no substrate does:

  1. Reference resolution. A characteristic whose COMPU_METHOD or RECORD_LAYOUT is undeclared, or whose COMPU_TAB_REF has no registered points, is a typed CalError::Unsupported — never a silently defaulted conversion. A wrong conversion writes the wrong number into an ECU.
  2. Inversion. to_physical is evaluation; to_raw is the part that matters, and it bracket-checks against the deposit’s datatype range so the tool cannot ask for a value the ECU cannot hold.
  3. Transport framing. XcpTransport is deliberately two methods wide, which makes a session testable against mock::MockTransport while CalibrationSession::upload_frames and friends hand a real bridge the exact xcp_core frames to send.
  4. Verified writes. A session write reads the value back and fails if the ECU did not latch it.
  5. Calibration arithmetic. calibrate_curve fits a monotone piecewise-linear curve through measured nodes; optimize_working_point finds a bounded working point by deterministic coordinate descent.

§Raw values are bit patterns

Every raw value in this crate is the memory bit pattern, so a signed SBYTE characteristic holding −1 °C reads 0xFF. Sign extension happens in Characteristic::raw_value, on the way into the conversion, and in Characteristic::raw_bits, on the way out. This is what makes a read-modify-write cycle bit-exact: nothing is re-derived from a float.

§Example

use cal_model::{
    CalibrationProject, CalibrationSession, CalError, ResourceMode, XcpTransport, SAMPLE_A2L,
};

// 1. Load the description and resolve every reference it makes.
let mut project = CalibrationProject::from_a2l(SAMPLE_A2L)?;
project.register_table("boost_curve_tab", vec![(0.0, 0.0), (6000.0, 150.0)])?;
assert_eq!(project.module("engine")?.characteristics.len(), 9);

// 2. Look a parameter up and convert both ways.
let idle = project.characteristic("engine", "idle_target_rpm")?;
assert_eq!(idle.address, 0x720108);
// 3200 counts · 0.25 rpm/count = 800 rpm.
let physical = project.to_physical("engine", "idle_target_rpm", 3200)?;
assert!((physical - 800.0).abs() < 1e-9, "{physical}");
assert_eq!(project.to_raw("engine", "idle_target_rpm", 800.0)?, 3200);

// 3. Limits are enforced on the way in.
project.check_limits("engine", "idle_target_rpm", 3200)?;
assert!(project.check_limits("engine", "idle_target_rpm", 0).is_err());

// 4. Calibrate against a bench ECU: write, read back, diff.
let bench = cal_model::mock::MockTransport::seeded(&cal_model::seed_memory());
let mut session = CalibrationSession::connect(
    &project, Box::new(bench), ResourceMode::CONNECT_NORMAL,
)?;
// The seed memory holds 800 rpm; the write is limit-checked (500…1200),
// inverted through `rpm_lin`, and read back before it is reported.
session.write_characteristic("engine", "idle_target_rpm", 900.0)?;
let live = session.read_characteristic("engine", "idle_target_rpm")?;
assert!((live - 900.0).abs() < 1e-9, "{live}");

// 5. Snapshot, adjust, and report the diff.
let before = session.snapshot(&["idle_target_rpm", "eng_torque_max"])?;
session.write_characteristic("engine", "idle_target_rpm", 950.0)?;
let after = session.snapshot(&["idle_target_rpm", "eng_torque_max"])?;
let deltas = cal_model::diff_snapshots(Some(&before), &after, &project);
assert_eq!(deltas[0].before, 900.0);
assert_eq!(deltas[0].after, 950.0);
assert!((deltas[0].delta - 50.0).abs() < 1e-9);
assert!(deltas[0].within_limits);

Re-exports§

pub use sample::complete;
pub use sample::element_counts;
pub use sample::sample_project;
pub use sample::seed_memory;
pub use sample::tables;
pub use sample::SAMPLE_A2L;
pub use sample::SAMPLE_DBC;
pub use a2l_parse as a2l;
pub use dbc_parse as dbc;
pub use xcp_core as xcp;

Modules§

mock
An in-memory XCP transport: ECU calibration memory as a sparse map.
sample
The embedded demo project: a realistic two-ECU powertrain description and the CAN database that binds it.

Structs§

CalParameter
One node of a curve under construction, or one adjustable of an optimisation.
CalibrationDelta
One change between two calibration states.
CalibrationProject
A calibration project: an A2L description, optionally bound to a DBC database.
CalibrationSession
A calibration session against one ECU, over one transport.
Characteristic
A CHARACTERISTIC: one calibration parameter, resolved and ready to read, write, and validate.
Curve
A monotone piecewise-linear calibration curve.
Measurement
A MEASUREMENT: an ECU-internal quantity, resolved for measurement.
Module
One /begin MODULE resolved into the calibration vocabulary.
ResourceMode
Bit set of XCP resources: which feature groups a slave offers (CONNECT response / GET_STATUS protection status) and which access is requested in the CONNECT mode byte.
SignalBinding
A resolved binding between a CHARACTERISTIC and a DBC signal.
Snapshot
A captured calibration set: the values of every named characteristic, with the page they were read on.
SnapshotEntry
One characteristic as captured: every element it deposits.
SnapshotValue
One captured value of one characteristic element.

Enums§

ByteOrder
Byte order of a signal’s bit layout.
CalError
The single crate-level error for every calibration operation.
CharKind
The ASAP2 CHARACTERISTIC type keywords, as the calibration layer consumes them.
CompuMethod
A raw ↔ physical conversion, driven by an A2L COMPU_METHOD.

Traits§

XcpTransport
Byte-level ECU memory access, as a calibration session needs it.

Functions§

calibrate_curve
Fit a monotone piecewise-linear curve through the given nodes.
diff_snapshots
Diff two calibration states: before → after, one entry per element, limit-checked against project’s current A2L limits.
optimal_point
Maximise objective over the box defined by params, returning the point and its value.
optimize_working_point
Maximise objective over the box defined by params and return the best value found.
render_deltas
Render a diff report: one header line, then one row per delta, then a summary.