use crate::bits;
use crate::error::DbcError;
use alloc::string::String;
use alloc::vec::Vec;
#[must_use]
fn two_pow(n: u8) -> f64 {
if n == 64 {
18_446_744_073_709_551_616.0
} else {
#[allow(clippy::cast_precision_loss)]
{
(1_u64 << n) as f64
}
}
}
#[must_use]
fn floor(x: f64) -> f64 {
if !x.is_finite() || x.abs() >= 9_007_199_254_740_992.0 {
return x;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
let t = x as i64 as f64;
#[allow(clippy::float_cmp)]
if x >= 0.0 || t == x {
t
} else {
t - 1.0
}
}
#[must_use]
fn round_half_away(x: f64) -> f64 {
let floor = floor(x);
let diff = x - floor;
if diff > 0.5 {
floor + 1.0
} else if diff < 0.5 || x < 0.0 {
floor
} else {
floor + 1.0
}
}
pub const STANDARD_ID_MAX: u32 = 0x7FF;
pub const EXTENDED_ID_MAX: u32 = 0x1FFF_FFFF;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanId {
Standard(u16),
Extended(u32),
}
impl CanId {
pub fn standard(raw: u16) -> Result<Self, DbcError> {
if u32::from(raw) > STANDARD_ID_MAX {
return Err(DbcError::InvalidId {
max: STANDARD_ID_MAX,
raw: u32::from(raw),
});
}
Ok(Self::Standard(raw))
}
pub fn extended(raw: u32) -> Result<Self, DbcError> {
if raw > EXTENDED_ID_MAX {
return Err(DbcError::InvalidId {
max: EXTENDED_ID_MAX,
raw,
});
}
Ok(Self::Extended(raw))
}
pub fn from_dbc_raw(raw: u32) -> Result<Self, DbcError> {
if raw & 0x8000_0000 != 0 {
Self::extended(raw & 0x1FFF_FFFF)
} else if raw > STANDARD_ID_MAX {
Err(DbcError::InvalidId {
max: STANDARD_ID_MAX,
raw,
})
} else {
#[allow(clippy::cast_possible_truncation)]
Ok(Self::Standard(raw as u16))
}
}
#[must_use]
pub const fn is_standard(&self) -> bool {
matches!(self, Self::Standard(_))
}
#[must_use]
pub const fn raw(&self) -> u32 {
match *self {
Self::Standard(v) => v as u32,
Self::Extended(v) => v,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Node {
pub name: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ByteOrder {
Motorola,
Intel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MultiplexingInfo {
None,
Multiplexor,
Value(i32),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Signal {
pub name: String,
pub start_bit: u16,
pub bit_length: u8,
pub byte_order: ByteOrder,
pub is_signed: bool,
pub scale: f64,
pub offset: f64,
pub min: f64,
pub max: f64,
pub unit: String,
pub receivers: Vec<String>,
pub multiplexing_info: MultiplexingInfo,
}
impl Signal {
#[must_use]
pub fn decode_raw(&self, data: &[u8]) -> f64 {
let raw = bits::extract_raw(self.start_bit, self.bit_length, self.byte_order, data);
#[allow(clippy::cast_precision_loss)]
let as_int = if self.is_signed {
bits::sign_extend(raw, self.bit_length) as f64
} else {
raw as f64
};
as_int * self.scale + self.offset
}
pub fn encode_raw(&self, data: &mut [u8], value: f64) -> Result<(), DbcError> {
if !value.is_finite() || (self.min < self.max && !(value >= self.min && value <= self.max))
{
return Err(DbcError::ValueOutOfRange {
value,
min: self.min,
max: self.max,
});
}
let raw = round_half_away((value - self.offset) / self.scale);
let width = self.bit_length;
let fits = if self.is_signed {
let half = two_pow(width - 1);
raw >= -half && raw < half
} else {
raw >= 0.0 && raw < two_pow(width)
};
#[allow(clippy::cast_precision_loss)]
let i64_min = i64::MIN as f64;
let needs_i64 = self.is_signed && (raw < i64_min || raw >= two_pow(63));
if !fits || needs_i64 {
return Err(DbcError::RawOutOfRange {
raw,
bit_length: self.bit_length,
});
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let raw_bits = if self.is_signed {
raw as i64 as u64
} else {
raw as u64
};
bits::insert_raw(
self.start_bit,
self.bit_length,
self.byte_order,
data,
raw_bits,
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
pub id: CanId,
pub name: String,
pub dlc: u8,
pub sender: String,
pub signals: Vec<Signal>,
}
impl Message {
#[must_use]
pub fn unpack(&self, data: &[u8]) -> Vec<(Signal, f64)> {
let selector = self
.signals
.iter()
.find(|signal| signal.multiplexing_info == MultiplexingInfo::Multiplexor)
.map(|switch| {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let raw = round_half_away(switch.decode_raw(data)) as i64;
raw
});
self.signals
.iter()
.filter(|signal| match (signal.multiplexing_info, selector) {
(MultiplexingInfo::Value(tag), Some(selected)) => i64::from(tag) == selected,
_ => true,
})
.map(|signal| (signal.clone(), signal.decode_raw(data)))
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueTable {
pub name: Option<String>,
pub message_id: Option<u32>,
pub signal: String,
pub entries: Vec<(i64, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttributeObject {
Database,
Node(String),
Message(u32),
Signal {
message_id: u32,
signal: String,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum AttributeValue {
Int(i64),
Float(f64),
Str(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
pub name: String,
pub object: AttributeObject,
pub value: AttributeValue,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtendedMux {
pub message_id: u32,
pub signal: String,
pub selector: String,
pub ranges: Vec<(i32, i32)>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Dbc {
pub version: Option<String>,
pub nodes: Vec<Node>,
pub messages: Vec<Message>,
pub value_tables: Vec<ValueTable>,
pub attributes: Vec<Attribute>,
pub extended_multiplexing: Vec<ExtendedMux>,
}
impl Dbc {
#[allow(clippy::should_implement_trait)] pub fn parse(input: &str) -> Result<Self, DbcError> {
crate::parser::parse(input)
}
}