1use crate::error::CanError;
26
27pub const SAMPLE_POINT_HIGH_SPEED: f64 = 0.750;
29pub const SAMPLE_POINT_DEFAULT: f64 = 0.875;
31
32const 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; const TOTAL_MAX: u16 = 1 + PROP_SEG_MAX + PHASE_SEG1_MAX + PHASE_SEG2_MAX; const SJW_MAX: u16 = 4;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct BitSegments {
44 pub prop_seg: u16,
46 pub phase_seg1: u16,
48 pub phase_seg2: u16,
50 pub sjw: u16,
52}
53
54impl BitSegments {
55 #[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#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct BitTiming {
65 pub baudrate: u32,
67 pub sample_point: f64,
69 pub prescaler: u32,
71 pub segments: BitSegments,
73}
74
75#[derive(Debug, Clone, Copy)]
77pub struct BitTimingParams {
78 pub clock_hz: u32,
80 pub sample_point: Option<f64>,
83 pub max_prescaler: u32,
85}
86
87impl BitTimingParams {
88 #[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#[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 pub fn calculate(baudrate: u32, clock_hz: u32) -> Result<Self, CanError> {
120 Self::calculate_with(BitTimingParams::new(clock_hz), baudrate)
121 }
122
123 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; 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; }
152 #[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
154 let scaled = scaled as u32;
155 if params.clock_hz % scaled != 0 {
156 continue; }
158 let total = params.clock_hz / scaled;
159 if total > u32::from(TOTAL_MAX) {
160 continue; }
162 #[allow(clippy::cast_possible_truncation)]
164 let total = total as u16;
165 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 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 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 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 #[allow(clippy::cast_possible_truncation)]
233 Ok((dividend / divisor) as u32)
234 }
235
236 #[must_use]
243 pub fn btr(&self) -> Option<u16> {
244 if self.prescaler > 64 {
245 return None;
246 }
247 #[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 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
263 use super::*;
264
265 #[test]
268 fn cia_8mhz_classic_table() {
269 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 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 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 #[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 #[test]
323 fn explicit_sample_point() {
324 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 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 assert!(BitTiming::calculate(333_333, 8_000_000).is_err());
391 }
392
393 #[test]
395 fn btr_overflow_is_none() {
396 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 assert!(t.actual_baudrate(7_000_001).is_err());
408 }
409}