cal_model/signal.rs
1//! CAN signal bindings: the bridge from an A2L CHARACTERISTIC to a DBC
2//! message signal.
3//!
4//! A calibration engineer routinely needs the *bus* view of a parameter —
5//! "which frame carries the boost target, and at which bit?" — as well as
6//! its ECU-memory view. [`attach_dbc`](crate::CalibrationProject::attach_dbc)
7//! produces one [`SignalBinding`] per characteristic that has a
8//! same-named signal, and this module is where its bits are coded: the
9//! Motorola sawtooth and the Intel linear layout both come from
10//! `dbc_parse::bits`, the estate's single implementation of the two DBC
11//! bit-numbering systems.
12
13use crate::CalError;
14use dbc_parse::ByteOrder;
15
16/// A resolved binding between a CHARACTERISTIC and a DBC signal.
17#[derive(Debug, Clone, PartialEq)]
18pub struct SignalBinding {
19 /// The CHARACTERISTIC this binding describes.
20 pub characteristic: String,
21 /// The message's CAN identifier, widened to `u32`
22 /// (`dbc_parse::CanId::raw`).
23 pub can_id: u32,
24 /// DBC start bit: the MSB for [`ByteOrder::Motorola`], the LSB for
25 /// [`ByteOrder::Intel`]. `u16` because DBC numbers up to 511 (CAN FD
26 /// payloads reach byte 64).
27 pub start_bit: u16,
28 /// Signal width in bits (1–64).
29 pub length: u8,
30 /// Bit layout order (`@0`/`@1` in the DBC grammar).
31 pub byte_order: ByteOrder,
32 /// Physical value = `raw * factor + offset`.
33 pub factor: f64,
34 /// Physical value = `raw * factor + offset`.
35 pub offset: f64,
36}
37
38impl SignalBinding {
39 /// Build a binding from a DBC signal in message `can_id`.
40 #[must_use]
41 pub fn from_signal(characteristic: &str, can_id: u32, signal: &dbc_parse::Signal) -> Self {
42 Self {
43 characteristic: characteristic.to_string(),
44 can_id,
45 start_bit: signal.start_bit,
46 length: signal.bit_length,
47 byte_order: signal.byte_order,
48 factor: signal.scale,
49 offset: signal.offset,
50 }
51 }
52
53 /// Bytes a payload must have for this layout.
54 #[must_use]
55 pub fn payload_len(&self) -> usize {
56 dbc_parse::bits::max_bit_position(self.start_bit, self.length, self.byte_order) / 8 + 1
57 }
58
59 /// The raw bit pattern the signal occupies in `data`.
60 ///
61 /// Total: positions beyond the buffer read as zero bits (the same
62 /// documented semantics `dbc_parse` uses), so a truncated capture
63 /// decodes rather than panicking.
64 #[must_use]
65 pub fn extract_raw(&self, data: &[u8]) -> u64 {
66 dbc_parse::bits::extract_raw(self.start_bit, self.length, self.byte_order, data)
67 }
68
69 /// Decode the signal's physical value from a payload.
70 #[must_use]
71 pub fn decode(&self, data: &[u8]) -> f64 {
72 #[allow(clippy::cast_precision_loss)]
73 {
74 self.extract_raw(data) as f64 * self.factor + self.offset
75 }
76 }
77
78 /// Encode a physical value into `data` at this signal's bits — the
79 /// exact inverse of [`decode`](Self::decode), modulo the rounding to the
80 /// signal's raw resolution.
81 ///
82 /// # Errors
83 ///
84 /// [`CalError::Unsupported`] when `factor` is zero (nothing can be
85 /// inverted), [`CalError::Dbc`] when the raw value does not fit the
86 /// signal's width or the buffer is too short.
87 pub fn encode(&self, data: &mut [u8], physical: f64) -> Result<(), CalError> {
88 if self.factor == 0.0 || !self.factor.is_finite() {
89 return Err(CalError::Unsupported {
90 subject: format!("signal `{}`", self.characteristic),
91 reason: format!("factor {} is not invertible", self.factor),
92 });
93 }
94 // f64::round is half-away-from-zero, the convention CAN tooling uses.
95 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
96 let raw = ((physical - self.offset) / self.factor).round() as u64;
97 if u32::from(self.length) < 64 && u128::from(raw) >= (1_u128 << u32::from(self.length)) {
98 #[allow(clippy::cast_precision_loss)]
99 return Err(CalError::Dbc(dbc_parse::DbcError::RawOutOfRange {
100 raw: raw as f64,
101 bit_length: self.length,
102 }));
103 }
104 dbc_parse::bits::insert_raw(self.start_bit, self.length, self.byte_order, data, raw)
105 .map_err(CalError::Dbc)
106 }
107
108 /// Decode every binding of `bindings` from one payload, as
109 /// `(can_id, name, physical)` triples in the order given.
110 #[must_use]
111 pub fn decode_all(bindings: &[Self], data: &[u8]) -> Vec<(u32, String, f64)> {
112 bindings
113 .iter()
114 .map(|b| (b.can_id, b.characteristic.clone(), b.decode(data)))
115 .collect()
116 }
117}
118
119impl std::fmt::Display for SignalBinding {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 let order = match self.byte_order {
122 ByteOrder::Motorola => "motorola",
123 ByteOrder::Intel => "intel",
124 };
125 write!(
126 f,
127 "0x{:03X} {} start_bit {} len {} {order} factor {} offset {}",
128 self.can_id, self.characteristic, self.start_bit, self.length, self.factor, self.offset
129 )
130 }
131}