use crate::CalError;
use dbc_parse::ByteOrder;
#[derive(Debug, Clone, PartialEq)]
pub struct SignalBinding {
pub characteristic: String,
pub can_id: u32,
pub start_bit: u16,
pub length: u8,
pub byte_order: ByteOrder,
pub factor: f64,
pub offset: f64,
}
impl SignalBinding {
#[must_use]
pub fn from_signal(characteristic: &str, can_id: u32, signal: &dbc_parse::Signal) -> Self {
Self {
characteristic: characteristic.to_string(),
can_id,
start_bit: signal.start_bit,
length: signal.bit_length,
byte_order: signal.byte_order,
factor: signal.scale,
offset: signal.offset,
}
}
#[must_use]
pub fn payload_len(&self) -> usize {
dbc_parse::bits::max_bit_position(self.start_bit, self.length, self.byte_order) / 8 + 1
}
#[must_use]
pub fn extract_raw(&self, data: &[u8]) -> u64 {
dbc_parse::bits::extract_raw(self.start_bit, self.length, self.byte_order, data)
}
#[must_use]
pub fn decode(&self, data: &[u8]) -> f64 {
#[allow(clippy::cast_precision_loss)]
{
self.extract_raw(data) as f64 * self.factor + self.offset
}
}
pub fn encode(&self, data: &mut [u8], physical: f64) -> Result<(), CalError> {
if self.factor == 0.0 || !self.factor.is_finite() {
return Err(CalError::Unsupported {
subject: format!("signal `{}`", self.characteristic),
reason: format!("factor {} is not invertible", self.factor),
});
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let raw = ((physical - self.offset) / self.factor).round() as u64;
if u32::from(self.length) < 64 && u128::from(raw) >= (1_u128 << u32::from(self.length)) {
#[allow(clippy::cast_precision_loss)]
return Err(CalError::Dbc(dbc_parse::DbcError::RawOutOfRange {
raw: raw as f64,
bit_length: self.length,
}));
}
dbc_parse::bits::insert_raw(self.start_bit, self.length, self.byte_order, data, raw)
.map_err(CalError::Dbc)
}
#[must_use]
pub fn decode_all(bindings: &[Self], data: &[u8]) -> Vec<(u32, String, f64)> {
bindings
.iter()
.map(|b| (b.can_id, b.characteristic.clone(), b.decode(data)))
.collect()
}
}
impl std::fmt::Display for SignalBinding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let order = match self.byte_order {
ByteOrder::Motorola => "motorola",
ByteOrder::Intel => "intel",
};
write!(
f,
"0x{:03X} {} start_bit {} len {} {order} factor {} offset {}",
self.can_id, self.characteristic, self.start_bit, self.length, self.factor, self.offset
)
}
}