Skip to main content

can_core/
timing.rs

1//! CAN bit-timing — the standard Bosch calculation from baudrate and clock.
2//!
3//! A bit time is divided into time quanta (Tq): one **synchronisation
4//! segment** (always 1 Tq), a **propagation segment**, **phase segment 1**
5//! (the sample point falls at the end of phase segment 1), and **phase
6//! segment 2**. With a prescaler (BRP) dividing the input clock, the bit
7//! time is
8//!
9//! ```text
10//! Tq_per_bit = clock_hz / (prescaler × baudrate)
11//!            = 1 (sync) + prop_seg + phase_seg1 + phase_seg2
12//! ```
13//!
14//! [`BitTiming::calculate`] searches prescalers and segment splits for the
15//! configuration whose sample point lands closest to the target — the
16//! canonical algorithm Linux (`can_update_spt`) and every Bosch-spec-derived
17//! tool uses — under the Bosch segment limits (prop 1–8, phase1 1–8, phase2
18//! 2–8, SJW 1–4, giving 4–25 Tq per bit). Ties prefer the smaller phase
19//! segment 2 (the higher sample point) and the smaller prescaler.
20//!
21//! [`BitTiming::btr`] renders the result as an SJA1000-style BTR register
22//! pair: `BTR0 = (SJW−1) << 6 | (BRP−1)`, `BTR1 = (PHASE_SEG2−1) |
23//! ((PROP_SEG+PHASE_SEG1−1) << 4)`.
24
25use crate::error::CanError;
26
27/// Default sample point for bit rates ≥ 800 kbit/s (`CiA` recommendation).
28pub const SAMPLE_POINT_HIGH_SPEED: f64 = 0.750;
29/// Default sample point below 800 kbit/s (`CiA` recommendation — 87.5 %).
30pub const SAMPLE_POINT_DEFAULT: f64 = 0.875;
31
32/// Bosch CAN 2.0 segment limits.
33const PROP_SEG_MAX: u16 = 8;
34const PHASE_SEG1_MAX: u16 = 8;
35const PHASE_SEG2_MIN: u16 = 2;
36const PHASE_SEG2_MAX: u16 = 8;
37const PHASE_SEG1_MIN: u16 = 2; // prop + phase1 ≥ 2
38const TOTAL_MAX: u16 = 1 + PROP_SEG_MAX + PHASE_SEG1_MAX + PHASE_SEG2_MAX; // 25
39const SJW_MAX: u16 = 4;
40
41/// The four programmable bit-timing segments, in time quanta.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct BitSegments {
44    /// Propagation segment (1–8 Tq).
45    pub prop_seg: u16,
46    /// Phase segment 1 (1–8 Tq); the sample point sits at its end.
47    pub phase_seg1: u16,
48    /// Phase segment 2 (2–8 Tq).
49    pub phase_seg2: u16,
50    /// Synchronisation jump width (1–4 Tq).
51    pub sjw: u16,
52}
53
54impl BitSegments {
55    /// Total bit time in Tq: sync (1) + all segments.
56    #[must_use]
57    pub const fn total_tq(&self) -> u16 {
58        1 + self.prop_seg + self.phase_seg1 + self.phase_seg2
59    }
60}
61
62/// A solved bit-timing configuration for one baudrate/clock pair.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct BitTiming {
65    /// The achieved bit rate in bit/s.
66    pub baudrate: u32,
67    /// Sample point as a fraction of the bit time, `0.0..=1.0`.
68    pub sample_point: f64,
69    /// The prescaler (BRP) applied to the input clock.
70    pub prescaler: u32,
71    /// The segment values, in time quanta.
72    pub segments: BitSegments,
73}
74
75/// Parameters for [`BitTiming::calculate_with`].
76#[derive(Debug, Clone, Copy)]
77pub struct BitTimingParams {
78    /// CAN controller input clock, in Hz.
79    pub clock_hz: u32,
80    /// Target sample point (`Some` to override, `None` for the `CiA` default:
81    /// 87.5 % below 800 kbit/s, 75 % at or above).
82    pub sample_point: Option<f64>,
83    /// Largest prescaler to consider (hardware BRP width; default 1024).
84    pub max_prescaler: u32,
85}
86
87impl BitTimingParams {
88    /// Parameters for `clock_hz` with the default sample point and prescaler
89    /// limit.
90    #[must_use]
91    pub const fn new(clock_hz: u32) -> Self {
92        Self {
93            clock_hz,
94            sample_point: None,
95            max_prescaler: 1024,
96        }
97    }
98}
99
100/// CiA-recommended default sample point for a bit rate.
101#[must_use]
102pub fn default_sample_point(baudrate: u32) -> f64 {
103    if baudrate >= 800_000 {
104        SAMPLE_POINT_HIGH_SPEED
105    } else {
106        SAMPLE_POINT_DEFAULT
107    }
108}
109
110impl BitTiming {
111    /// Solves the standard bit-timing algorithm for `baudrate` driven by
112    /// `clock_hz`, using the `CiA` default sample point.
113    ///
114    /// # Errors
115    ///
116    /// [`CanError::InvalidTiming`] for a zero baudrate/clock or when no
117    /// configuration under the Bosch segment limits can achieve the
118    /// baudrate.
119    pub fn calculate(baudrate: u32, clock_hz: u32) -> Result<Self, CanError> {
120        Self::calculate_with(BitTimingParams::new(clock_hz), baudrate)
121    }
122
123    /// Solves the bit-timing algorithm with explicit parameters.
124    ///
125    /// # Errors
126    ///
127    /// [`CanError::InvalidTiming`] for a zero baudrate/clock, a sample point
128    /// outside `(0, 1)`, or no achievable configuration.
129    pub fn calculate_with(params: BitTimingParams, baudrate: u32) -> Result<Self, CanError> {
130        if baudrate == 0 {
131            return Err(CanError::InvalidTiming("baudrate must be non-zero"));
132        }
133        if params.clock_hz == 0 {
134            return Err(CanError::InvalidTiming("clock_hz must be non-zero"));
135        }
136        let target = params
137            .sample_point
138            .unwrap_or_else(|| default_sample_point(baudrate));
139        if !(target > 0.0 && target < 1.0) {
140            return Err(CanError::InvalidTiming("sample_point must lie in (0, 1)"));
141        }
142        if params.max_prescaler == 0 {
143            return Err(CanError::InvalidTiming("max_prescaler must be non-zero"));
144        }
145
146        let mut best: Option<(f64, u32, u16, u16)> = None; // (error, brp, tseg1_total, tseg2)
147        for brp in 1..=params.max_prescaler {
148            let scaled = u64::from(brp) * u64::from(baudrate);
149            if scaled > u64::from(params.clock_hz) {
150                break; // larger brp only makes it worse
151            }
152            // scaled ≤ clock by the break above — no truncation.
153            #[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
154            let scaled = scaled as u32;
155            if params.clock_hz % scaled != 0 {
156                continue; // not an integer number of Tq — unusable
157            }
158            let total = params.clock_hz / scaled;
159            if total > u32::from(TOTAL_MAX) {
160                continue; // bit time too long even at this prescaler
161            }
162            // ≤ TOTAL_MAX ≤ 25 by the check above — no truncation.
163            #[allow(clippy::cast_possible_truncation)]
164            let total = total as u16;
165            // tseg = tseg1_total + tseg2 (sync segment excluded).
166            let tseg = total - 1;
167            for tseg2 in PHASE_SEG2_MIN..=PHASE_SEG2_MAX {
168                if tseg2 >= tseg {
169                    break;
170                }
171                let tseg1_total = tseg - tseg2;
172                if !(PHASE_SEG1_MIN..=PHASE_SEG1_MAX + PROP_SEG_MAX).contains(&tseg1_total) {
173                    continue;
174                }
175                let sample_point = f64::from(total - tseg2) / f64::from(total);
176                let error = (sample_point - target).abs();
177                let better = match best {
178                    None => true,
179                    // Strict `<` keeps the first winner: smaller tseg2 (higher
180                    // sample point) on ties, and the smallest brp (outer loop).
181                    Some((best_error, _, _, _)) => error < best_error,
182                };
183                if better {
184                    best = Some((error, brp, tseg1_total, tseg2));
185                }
186            }
187        }
188
189        let Some((_, brp, tseg1_total, tseg2)) = best else {
190            return Err(CanError::InvalidTiming(
191                "no configuration achieves this baudrate under the Bosch segment limits",
192            ));
193        };
194
195        // Split tseg1 between propagation and phase 1: phase 1 takes half,
196        // clamped to the Bosch 8-Tq cap (prop then carries the remainder;
197        // both stay ≥ 1 for tseg1_total ∈ 2..=16).
198        let phase_seg1 = (tseg1_total / 2).min(PHASE_SEG1_MAX);
199        let prop_seg = tseg1_total - phase_seg1;
200        let segments = BitSegments {
201            prop_seg,
202            phase_seg1,
203            phase_seg2: tseg2,
204            sjw: tseg2.min(SJW_MAX),
205        };
206        let sample_point = f64::from(tseg1_total + 1) / f64::from(tseg1_total + 1 + tseg2);
207        Ok(Self {
208            baudrate,
209            sample_point,
210            prescaler: brp,
211            segments,
212        })
213    }
214
215    /// The achieved bit rate implied by the configuration — sanity check
216    /// that `prescaler × baudrate` divides the clock exactly.
217    ///
218    /// # Errors
219    ///
220    /// [`CanError::InvalidTiming`] when the clock passed here cannot produce
221    /// an integer number of Tq for this configuration.
222    pub fn actual_baudrate(&self, clock_hz: u32) -> Result<u32, CanError> {
223        let tq = u32::from(self.segments.total_tq());
224        let dividend = u64::from(clock_hz);
225        let divisor = u64::from(self.prescaler) * u64::from(tq);
226        if divisor == 0 || dividend % divisor != 0 {
227            return Err(CanError::InvalidTiming(
228                "clock does not divide into an integer Tq count",
229            ));
230        }
231        // Quotient ≤ dividend ≤ u32::MAX — no truncation.
232        #[allow(clippy::cast_possible_truncation)]
233        Ok((dividend / divisor) as u32)
234    }
235
236    /// The SJA1000-style BTR register pair, `BTR0 << 8 | BTR1`:
237    /// `BTR0 = (SJW−1) << 6 | (BRP−1)`, `BTR1 = (PHASE_SEG2−1) |
238    /// ((PROP_SEG+PHASE_SEG1−1) << 4)` with SAM = 0.
239    ///
240    /// `None` when the prescaler exceeds the 6-bit BTR0 field (BRP > 64) —
241    /// the segment fields can never overflow under the Bosch limits.
242    #[must_use]
243    pub fn btr(&self) -> Option<u16> {
244        if self.prescaler > 64 {
245            return None;
246        }
247        // ≤ 64 by the check above — no truncation.
248        #[allow(clippy::cast_possible_truncation)]
249        let brp_field = (self.prescaler - 1) as u16;
250        let sjw_field = self.segments.sjw - 1;
251        let btr0 = (sjw_field << 6) | brp_field;
252        let tseg1_total = self.segments.prop_seg + self.segments.phase_seg1;
253        let btr1 = (self.segments.phase_seg2 - 1) | ((tseg1_total - 1) << 4);
254        Some((btr0 << 8) | btr1)
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    // Tests exercise edge values and index fixed-size buffers directly:
261    // unwrap/expect/indexing are lifted at test scope by design.
262    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
263    use super::*;
264
265    /// Canonical `CANopen` (`CiA`) table values at an 8 MHz clock: 125/250/500
266    /// kbit/s all land on 16 Tq with an exact 87.5 % sample point.
267    #[test]
268    fn cia_8mhz_classic_table() {
269        // 125 kbit/s: BRP 4, 16 Tq, SP 14/16 = 87.5 %.
270        let t = BitTiming::calculate(125_000, 8_000_000).unwrap();
271        assert_eq!(t.prescaler, 4);
272        assert_eq!(t.segments.total_tq(), 16);
273        assert!((t.sample_point - 0.875).abs() < 1e-12);
274        assert_eq!(
275            t.segments,
276            BitSegments {
277                prop_seg: 7,
278                phase_seg1: 6,
279                phase_seg2: 2,
280                sjw: 2
281            }
282        );
283        assert_eq!(t.btr(), Some(0x43C1));
284        assert_eq!(t.actual_baudrate(8_000_000), Ok(125_000));
285
286        // 250 kbit/s: BRP 2 — same segments otherwise.
287        let t = BitTiming::calculate(250_000, 8_000_000).unwrap();
288        assert_eq!(t.prescaler, 2);
289        assert_eq!(t.btr(), Some(0x41C1));
290
291        // 500 kbit/s: BRP 1.
292        let t = BitTiming::calculate(500_000, 8_000_000).unwrap();
293        assert_eq!(t.prescaler, 1);
294        assert_eq!(t.btr(), Some(0x40C1));
295    }
296
297    /// 1 Mbit/s at 8 MHz takes the high-speed 75 % default: 8 Tq, BRP 1,
298    /// exact sample point.
299    #[test]
300    fn high_speed_default_sample_point() {
301        assert!((default_sample_point(1_000_000) - 0.750).abs() < 1e-12);
302        assert!((default_sample_point(500_000) - 0.875).abs() < 1e-12);
303
304        let t = BitTiming::calculate(1_000_000, 8_000_000).unwrap();
305        assert_eq!(t.prescaler, 1);
306        assert_eq!(t.segments.total_tq(), 8);
307        assert!((t.sample_point - 0.750).abs() < 1e-12);
308        assert_eq!(
309            t.segments,
310            BitSegments {
311                prop_seg: 3,
312                phase_seg1: 2,
313                phase_seg2: 2,
314                sjw: 2
315            }
316        );
317        assert_eq!(t.btr(), Some(0x4041));
318    }
319
320    /// An explicit sample-point target overrides the default, and the search
321    /// lands on the closest achievable point.
322    #[test]
323    fn explicit_sample_point() {
324        // 500 kbit/s at 48 MHz: 96 Tq raw. The closest sample point to the
325        // 87.5 % target is exact — 16 Tq at prescaler 6, tseg2 = 2.
326        let t = BitTiming::calculate_with(
327            BitTimingParams {
328                clock_hz: 48_000_000,
329                sample_point: Some(0.875),
330                max_prescaler: 1024,
331            },
332            500_000,
333        )
334        .unwrap();
335        assert_eq!(t.segments.total_tq(), 16);
336        assert_eq!(t.prescaler, 6);
337        assert!((t.sample_point - 0.875).abs() < 1e-12);
338        assert_eq!(t.btr(), Some(0x45C1));
339
340        // An unreachable-tight sample point still resolves to the closest
341        // option: at 16 Tq the lowest achievable point is exactly 8/16.
342        let t = BitTiming::calculate_with(
343            BitTimingParams {
344                clock_hz: 8_000_000,
345                sample_point: Some(0.5),
346                max_prescaler: 1024,
347            },
348            125_000,
349        )
350        .unwrap();
351        assert_eq!(t.segments.total_tq(), 16);
352        assert!((t.sample_point - 0.5).abs() < 1e-12);
353        assert_eq!(t.segments.phase_seg2, 8);
354        assert_eq!(t.segments.sjw, 4);
355    }
356
357    #[test]
358    fn parameter_errors() {
359        assert_eq!(
360            BitTiming::calculate(0, 8_000_000),
361            Err(CanError::InvalidTiming("baudrate must be non-zero"))
362        );
363        assert_eq!(
364            BitTiming::calculate(500_000, 0),
365            Err(CanError::InvalidTiming("clock_hz must be non-zero"))
366        );
367        assert_eq!(
368            BitTiming::calculate_with(
369                BitTimingParams {
370                    clock_hz: 8_000_000,
371                    sample_point: Some(1.0),
372                    max_prescaler: 64
373                },
374                500_000
375            ),
376            Err(CanError::InvalidTiming("sample_point must lie in (0, 1)"))
377        );
378        assert_eq!(
379            BitTiming::calculate_with(
380                BitTimingParams {
381                    clock_hz: 8_000_000,
382                    sample_point: Some(0.875),
383                    max_prescaler: 0
384                },
385                500_000
386            ),
387            Err(CanError::InvalidTiming("max_prescaler must be non-zero"))
388        );
389        // No integer Tq count can produce this rate under the segment limits:
390        assert!(BitTiming::calculate(333_333, 8_000_000).is_err());
391    }
392
393    /// Prescalers past the 6-bit BTR0 field are reported, not wrapped.
394    #[test]
395    fn btr_overflow_is_none() {
396        // 2 kbit/s at 8 MHz needs 4000 Tq / brp ≤ 25 → prescaler ≥ 160,
397        // far past the 6-bit BTR0 field.
398        let t = BitTiming::calculate(2_000, 8_000_000).unwrap();
399        assert!(t.prescaler > 64);
400        assert_eq!(t.btr(), None);
401    }
402
403    #[test]
404    fn actual_baudrate_error() {
405        let t = BitTiming::calculate(125_000, 8_000_000).unwrap();
406        // 7 000 001 Hz does not divide into an integer Tq count (÷64).
407        assert!(t.actual_baudrate(7_000_001).is_err());
408    }
409}