Skip to main content

cal_model/
model.rs

1//! The calibration data model: modules, characteristics, measurements, and
2//! the CAN signal bindings a DBC database attaches to them.
3//!
4//! Every type here is a *resolved* view of an [`a2l_parse`] declaration —
5//! the COMPU_METHOD a CHARACTERISTIC references has already been turned
6//! into a [`CompuMethod`], and the RECORD_LAYOUT it deposits through has
7//! already yielded a datatype and a byte offset. Nothing in this module
8//! parses; it is the vocabulary [`CalibrationProject`](crate::CalibrationProject),
9//! [`CalibrationSession`](crate::CalibrationSession), and
10//! [`calibrate_curve`](crate::calibrate_curve) speak.
11
12use crate::conversion::CompuMethod;
13use a2l_parse::{CharType, DataType};
14
15/// The ASAP2 CHARACTERISTIC type keywords, as the calibration layer
16/// consumes them.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum CharKind {
19    /// `VALUE` — a single scalar.
20    Value,
21    /// `CURVE` — one-dimensional table.
22    Curve,
23    /// `MAP` — two-dimensional table.
24    Map,
25    /// `VAL_BLK` — multi-dimensional value block without axes.
26    ValBlk,
27    /// `ASCII` — a string.
28    Ascii,
29}
30
31impl CharKind {
32    /// Re-tag an [`a2l_parse::CharType`] for the calibration layer.
33    #[must_use]
34    pub const fn from_char_type(kind: CharType) -> Self {
35        match kind {
36            CharType::Value => Self::Value,
37            CharType::Curve => Self::Curve,
38            CharType::Map => Self::Map,
39            CharType::ValBlk => Self::ValBlk,
40            CharType::Ascii => Self::Ascii,
41        }
42    }
43
44    /// The keyword this kind came from.
45    #[must_use]
46    pub const fn keyword(self) -> &'static str {
47        match self {
48            Self::Value => "VALUE",
49            Self::Curve => "CURVE",
50            Self::Map => "MAP",
51            Self::ValBlk => "VAL_BLK",
52            Self::Ascii => "ASCII",
53        }
54    }
55
56    /// `true` when the characteristic is an array of values rather than a
57    /// single scalar.
58    #[must_use]
59    pub const fn is_multi_element(self) -> bool {
60        matches!(self, Self::Curve | Self::Map | Self::ValBlk)
61    }
62}
63
64/// A CHARACTERISTIC: one calibration parameter, resolved and ready to read,
65/// write, and validate.
66#[derive(Debug, Clone, PartialEq)]
67pub struct Characteristic {
68    /// CHARACTERISTIC name.
69    pub name: String,
70    /// `VALUE`/`CURVE`/`MAP`/`VAL_BLK`/`ASCII`.
71    pub kind: CharKind,
72    /// ECU address of the deposit's first byte.
73    pub address: u32,
74    /// RECORD_LAYOUT the values deposit through.
75    pub deposit: String,
76    /// Byte offset of the value array inside the deposit record
77    /// (`FNC_VALUES POSITION`).
78    pub deposit_position: u8,
79    /// Element datatype, from the deposit's `FNC_VALUES DATATYPE`.
80    pub datatype: DataType,
81    /// Number of elements in the deposit. `a2l_parse` does not retain the
82    /// ASAP2 `NUMBER` keyword, so this is `1` until declared with
83    /// [`CalibrationProject::declare_elements`](crate::CalibrationProject::declare_elements)
84    /// — see that method's documentation for why it is an explicit
85    /// declaration rather than a guess.
86    pub elements: usize,
87    /// The resolved conversion.
88    pub conversion: CompuMethod,
89    /// `LOWER_LIMIT` — physical.
90    pub lower_limit: f64,
91    /// `UPPER_LIMIT` — physical.
92    pub upper_limit: f64,
93    /// `MAX_DIFF` — the largest step a single adjustment may take.
94    pub max_diff: f64,
95}
96
97impl Characteristic {
98    /// Element width in bits.
99    #[must_use]
100    pub fn element_bits(&self) -> u32 {
101        // size_bytes() is 1..=8 for every DataType, so the multiplication
102        // cannot overflow and the conversion to u32 is exact.
103        u32::try_from(self.datatype.size_bytes() * 8).unwrap_or(32)
104    }
105
106    /// `true` when the deposit datatype is two's-complement signed.
107    #[must_use]
108    pub const fn is_signed(&self) -> bool {
109        matches!(
110            self.datatype,
111            DataType::Sbyte | DataType::Sword | DataType::Slong | DataType::Int64
112        )
113    }
114
115    /// Bit mask covering one element's bits.
116    #[must_use]
117    pub fn element_mask(&self) -> u64 {
118        let bits = self.element_bits();
119        if bits >= 64 {
120            u64::MAX
121        } else {
122            (1_u64 << bits) - 1
123        }
124    }
125
126    /// Total deposit size in bytes (all elements).
127    #[must_use]
128    pub fn size_bytes(&self) -> usize {
129        self.elements * self.datatype.size_bytes()
130    }
131
132    /// Interpret a raw *bit pattern* as the numeric value the conversion
133    /// sees: signed datatypes are sign-extended, unsigned ones masked.
134    #[must_use]
135    pub fn raw_value(&self, raw: u64) -> f64 {
136        let masked = raw & self.element_mask();
137        if self.is_signed() {
138            #[allow(clippy::cast_precision_loss)]
139            {
140                sign_extend(masked, self.element_bits()) as f64
141            }
142        } else {
143            #[allow(clippy::cast_precision_loss)]
144            {
145                masked as f64
146            }
147        }
148    }
149
150    /// Encode a numeric raw value back into its memory bit pattern.
151    #[must_use]
152    pub fn raw_bits(&self, value: f64) -> u64 {
153        if self.is_signed() {
154            #[allow(clippy::cast_possible_wrap)]
155            let bits = (value as i64 as u64) & self.element_mask();
156            bits
157        } else {
158            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
159            let bits = (value as u64) & self.element_mask();
160            bits
161        }
162    }
163
164    /// The raw-value bounds of the deposit, in *numeric* terms (negative
165    /// for signed datatypes).
166    #[must_use]
167    pub fn value_bounds(&self) -> (f64, f64) {
168        let bits = self.element_bits();
169        let exponent = i32::try_from(bits).unwrap_or(32);
170        if self.is_signed() {
171            let half = 2_f64.powi(exponent - 1);
172            (-half, half - 1.0)
173        } else if bits >= 64 {
174            #[allow(clippy::cast_precision_loss)]
175            {
176                (0.0, u64::MAX as f64)
177            }
178        } else {
179            (0.0, 2_f64.powi(exponent) - 1.0)
180        }
181    }
182
183    /// `true` when the A2L declaration constrains the physical value at
184    /// all. A degenerate range (`lower >= upper`, as generators emit for
185    /// ASCII identifiers) imposes no constraint — the same convention
186    /// `dbc-parse` applies to an empty `[min|max]`.
187    #[must_use]
188    pub fn has_limits(&self) -> bool {
189        self.lower_limit.is_finite()
190            && self.upper_limit.is_finite()
191            && self.lower_limit < self.upper_limit
192    }
193
194    /// `true` when `physical` is inside the declared limits (or no limits
195    /// are declared).
196    #[must_use]
197    pub fn within_limits(&self, physical: f64) -> bool {
198        if !physical.is_finite() {
199            return false;
200        }
201        if !self.has_limits() {
202            return true;
203        }
204        physical >= self.lower_limit && physical <= self.upper_limit
205    }
206
207    /// Return a copy with the element count set (the builder form of
208    /// [`CalibrationProject::declare_elements`](crate::CalibrationProject::declare_elements)).
209    #[must_use]
210    pub fn with_elements(mut self, elements: usize) -> Self {
211        self.elements = elements;
212        self
213    }
214}
215
216/// A MEASUREMENT: an ECU-internal quantity, resolved for measurement.
217#[derive(Debug, Clone, PartialEq)]
218pub struct Measurement {
219    /// MEASUREMENT name.
220    pub name: String,
221    /// `ECU_ADDRESS` (`0` when the declaration omitted it).
222    pub address: u32,
223    /// The resolved conversion.
224    pub conversion: CompuMethod,
225    /// Raw datatype in ECU memory.
226    pub datatype: DataType,
227}
228
229impl Measurement {
230    /// Element width in bytes.
231    #[must_use]
232    pub fn size_bytes(&self) -> usize {
233        self.datatype.size_bytes()
234    }
235
236    /// `true` when the datatype is two's-complement signed.
237    #[must_use]
238    pub const fn is_signed(&self) -> bool {
239        matches!(
240            self.datatype,
241            DataType::Sbyte | DataType::Sword | DataType::Slong | DataType::Int64
242        )
243    }
244
245    /// Interpret a raw bit pattern as the numeric value the conversion
246    /// sees.
247    #[must_use]
248    pub fn raw_value(&self, raw: u64) -> f64 {
249        let bits = u32::try_from(self.datatype.size_bytes() * 8).unwrap_or(32);
250        let mask = if bits >= 64 {
251            u64::MAX
252        } else {
253            (1_u64 << bits) - 1
254        };
255        let masked = raw & mask;
256        #[allow(clippy::cast_precision_loss)]
257        let value = if self.is_signed() {
258            sign_extend(masked, bits) as f64
259        } else {
260            masked as f64
261        };
262        value
263    }
264}
265
266/// One `/begin MODULE` resolved into the calibration vocabulary.
267#[derive(Debug, Clone, PartialEq, Default)]
268pub struct Module {
269    /// MODULE name.
270    pub name: String,
271    /// Characteristics, in declaration order.
272    pub characteristics: Vec<Characteristic>,
273    /// Measurements, in declaration order.
274    pub measurements: Vec<Measurement>,
275}
276
277impl Module {
278    /// The CHARACTERISTIC named `name`.
279    #[must_use]
280    pub fn characteristic(&self, name: &str) -> Option<&Characteristic> {
281        self.characteristics.iter().find(|c| c.name == name)
282    }
283
284    /// The MEASUREMENT named `name`.
285    #[must_use]
286    pub fn measurement(&self, name: &str) -> Option<&Measurement> {
287        self.measurements.iter().find(|m| m.name == name)
288    }
289
290    /// Characteristic names, in declaration order.
291    pub fn characteristic_names(&self) -> impl Iterator<Item = &str> {
292        self.characteristics.iter().map(|c| c.name.as_str())
293    }
294
295    /// Measurement names, in declaration order.
296    pub fn measurement_names(&self) -> impl Iterator<Item = &str> {
297        self.measurements.iter().map(|m| m.name.as_str())
298    }
299}
300
301/// Sign-extend the low `bits` bits of `raw` to an `i64`.
302fn sign_extend(raw: u64, bits: u32) -> i64 {
303    if bits == 0 || bits >= 64 {
304        #[allow(clippy::cast_possible_wrap)]
305        {
306            return raw as i64;
307        }
308    }
309    let sign_bit = 1_u64 << (bits - 1);
310    #[allow(clippy::cast_possible_wrap)]
311    if raw & sign_bit != 0 {
312        (raw | (u64::MAX << bits)) as i64
313    } else {
314        #[allow(clippy::cast_possible_wrap)]
315        {
316            raw as i64
317        }
318    }
319}