use crate::error::CanError;
pub const SAMPLE_POINT_HIGH_SPEED: f64 = 0.750;
pub const SAMPLE_POINT_DEFAULT: f64 = 0.875;
const PROP_SEG_MAX: u16 = 8;
const PHASE_SEG1_MAX: u16 = 8;
const PHASE_SEG2_MIN: u16 = 2;
const PHASE_SEG2_MAX: u16 = 8;
const PHASE_SEG1_MIN: u16 = 2; const TOTAL_MAX: u16 = 1 + PROP_SEG_MAX + PHASE_SEG1_MAX + PHASE_SEG2_MAX; const SJW_MAX: u16 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitSegments {
pub prop_seg: u16,
pub phase_seg1: u16,
pub phase_seg2: u16,
pub sjw: u16,
}
impl BitSegments {
#[must_use]
pub const fn total_tq(&self) -> u16 {
1 + self.prop_seg + self.phase_seg1 + self.phase_seg2
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BitTiming {
pub baudrate: u32,
pub sample_point: f64,
pub prescaler: u32,
pub segments: BitSegments,
}
#[derive(Debug, Clone, Copy)]
pub struct BitTimingParams {
pub clock_hz: u32,
pub sample_point: Option<f64>,
pub max_prescaler: u32,
}
impl BitTimingParams {
#[must_use]
pub const fn new(clock_hz: u32) -> Self {
Self {
clock_hz,
sample_point: None,
max_prescaler: 1024,
}
}
}
#[must_use]
pub fn default_sample_point(baudrate: u32) -> f64 {
if baudrate >= 800_000 {
SAMPLE_POINT_HIGH_SPEED
} else {
SAMPLE_POINT_DEFAULT
}
}
impl BitTiming {
pub fn calculate(baudrate: u32, clock_hz: u32) -> Result<Self, CanError> {
Self::calculate_with(BitTimingParams::new(clock_hz), baudrate)
}
pub fn calculate_with(params: BitTimingParams, baudrate: u32) -> Result<Self, CanError> {
if baudrate == 0 {
return Err(CanError::InvalidTiming("baudrate must be non-zero"));
}
if params.clock_hz == 0 {
return Err(CanError::InvalidTiming("clock_hz must be non-zero"));
}
let target = params
.sample_point
.unwrap_or_else(|| default_sample_point(baudrate));
if !(target > 0.0 && target < 1.0) {
return Err(CanError::InvalidTiming("sample_point must lie in (0, 1)"));
}
if params.max_prescaler == 0 {
return Err(CanError::InvalidTiming("max_prescaler must be non-zero"));
}
let mut best: Option<(f64, u32, u16, u16)> = None; for brp in 1..=params.max_prescaler {
let scaled = u64::from(brp) * u64::from(baudrate);
if scaled > u64::from(params.clock_hz) {
break; }
#[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
let scaled = scaled as u32;
if params.clock_hz % scaled != 0 {
continue; }
let total = params.clock_hz / scaled;
if total > u32::from(TOTAL_MAX) {
continue; }
#[allow(clippy::cast_possible_truncation)]
let total = total as u16;
let tseg = total - 1;
for tseg2 in PHASE_SEG2_MIN..=PHASE_SEG2_MAX {
if tseg2 >= tseg {
break;
}
let tseg1_total = tseg - tseg2;
if !(PHASE_SEG1_MIN..=PHASE_SEG1_MAX + PROP_SEG_MAX).contains(&tseg1_total) {
continue;
}
let sample_point = f64::from(total - tseg2) / f64::from(total);
let error = (sample_point - target).abs();
let better = match best {
None => true,
Some((best_error, _, _, _)) => error < best_error,
};
if better {
best = Some((error, brp, tseg1_total, tseg2));
}
}
}
let Some((_, brp, tseg1_total, tseg2)) = best else {
return Err(CanError::InvalidTiming(
"no configuration achieves this baudrate under the Bosch segment limits",
));
};
let phase_seg1 = (tseg1_total / 2).min(PHASE_SEG1_MAX);
let prop_seg = tseg1_total - phase_seg1;
let segments = BitSegments {
prop_seg,
phase_seg1,
phase_seg2: tseg2,
sjw: tseg2.min(SJW_MAX),
};
let sample_point = f64::from(tseg1_total + 1) / f64::from(tseg1_total + 1 + tseg2);
Ok(Self {
baudrate,
sample_point,
prescaler: brp,
segments,
})
}
pub fn actual_baudrate(&self, clock_hz: u32) -> Result<u32, CanError> {
let tq = u32::from(self.segments.total_tq());
let dividend = u64::from(clock_hz);
let divisor = u64::from(self.prescaler) * u64::from(tq);
if divisor == 0 || dividend % divisor != 0 {
return Err(CanError::InvalidTiming(
"clock does not divide into an integer Tq count",
));
}
#[allow(clippy::cast_possible_truncation)]
Ok((dividend / divisor) as u32)
}
#[must_use]
pub fn btr(&self) -> Option<u16> {
if self.prescaler > 64 {
return None;
}
#[allow(clippy::cast_possible_truncation)]
let brp_field = (self.prescaler - 1) as u16;
let sjw_field = self.segments.sjw - 1;
let btr0 = (sjw_field << 6) | brp_field;
let tseg1_total = self.segments.prop_seg + self.segments.phase_seg1;
let btr1 = (self.segments.phase_seg2 - 1) | ((tseg1_total - 1) << 4);
Some((btr0 << 8) | btr1)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use super::*;
#[test]
fn cia_8mhz_classic_table() {
let t = BitTiming::calculate(125_000, 8_000_000).unwrap();
assert_eq!(t.prescaler, 4);
assert_eq!(t.segments.total_tq(), 16);
assert!((t.sample_point - 0.875).abs() < 1e-12);
assert_eq!(
t.segments,
BitSegments {
prop_seg: 7,
phase_seg1: 6,
phase_seg2: 2,
sjw: 2
}
);
assert_eq!(t.btr(), Some(0x43C1));
assert_eq!(t.actual_baudrate(8_000_000), Ok(125_000));
let t = BitTiming::calculate(250_000, 8_000_000).unwrap();
assert_eq!(t.prescaler, 2);
assert_eq!(t.btr(), Some(0x41C1));
let t = BitTiming::calculate(500_000, 8_000_000).unwrap();
assert_eq!(t.prescaler, 1);
assert_eq!(t.btr(), Some(0x40C1));
}
#[test]
fn high_speed_default_sample_point() {
assert!((default_sample_point(1_000_000) - 0.750).abs() < 1e-12);
assert!((default_sample_point(500_000) - 0.875).abs() < 1e-12);
let t = BitTiming::calculate(1_000_000, 8_000_000).unwrap();
assert_eq!(t.prescaler, 1);
assert_eq!(t.segments.total_tq(), 8);
assert!((t.sample_point - 0.750).abs() < 1e-12);
assert_eq!(
t.segments,
BitSegments {
prop_seg: 3,
phase_seg1: 2,
phase_seg2: 2,
sjw: 2
}
);
assert_eq!(t.btr(), Some(0x4041));
}
#[test]
fn explicit_sample_point() {
let t = BitTiming::calculate_with(
BitTimingParams {
clock_hz: 48_000_000,
sample_point: Some(0.875),
max_prescaler: 1024,
},
500_000,
)
.unwrap();
assert_eq!(t.segments.total_tq(), 16);
assert_eq!(t.prescaler, 6);
assert!((t.sample_point - 0.875).abs() < 1e-12);
assert_eq!(t.btr(), Some(0x45C1));
let t = BitTiming::calculate_with(
BitTimingParams {
clock_hz: 8_000_000,
sample_point: Some(0.5),
max_prescaler: 1024,
},
125_000,
)
.unwrap();
assert_eq!(t.segments.total_tq(), 16);
assert!((t.sample_point - 0.5).abs() < 1e-12);
assert_eq!(t.segments.phase_seg2, 8);
assert_eq!(t.segments.sjw, 4);
}
#[test]
fn parameter_errors() {
assert_eq!(
BitTiming::calculate(0, 8_000_000),
Err(CanError::InvalidTiming("baudrate must be non-zero"))
);
assert_eq!(
BitTiming::calculate(500_000, 0),
Err(CanError::InvalidTiming("clock_hz must be non-zero"))
);
assert_eq!(
BitTiming::calculate_with(
BitTimingParams {
clock_hz: 8_000_000,
sample_point: Some(1.0),
max_prescaler: 64
},
500_000
),
Err(CanError::InvalidTiming("sample_point must lie in (0, 1)"))
);
assert_eq!(
BitTiming::calculate_with(
BitTimingParams {
clock_hz: 8_000_000,
sample_point: Some(0.875),
max_prescaler: 0
},
500_000
),
Err(CanError::InvalidTiming("max_prescaler must be non-zero"))
);
assert!(BitTiming::calculate(333_333, 8_000_000).is_err());
}
#[test]
fn btr_overflow_is_none() {
let t = BitTiming::calculate(2_000, 8_000_000).unwrap();
assert!(t.prescaler > 64);
assert_eq!(t.btr(), None);
}
#[test]
fn actual_baudrate_error() {
let t = BitTiming::calculate(125_000, 8_000_000).unwrap();
assert!(t.actual_baudrate(7_000_001).is_err());
}
}