canlink-hal 0.3.0

Hardware abstraction layer for CAN bus interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! ISO-TP frame types and encoding/decoding.

use super::IsoTpError;

/// PCI type nibble values
const PCI_SINGLE_FRAME: u8 = 0x00;
const PCI_FIRST_FRAME: u8 = 0x10;
const PCI_CONSECUTIVE_FRAME: u8 = 0x20;
const PCI_FLOW_CONTROL: u8 = 0x30;

/// Flow Control status values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum FlowStatus {
    /// Continue To Send - receiver is ready
    ContinueToSend = 0x00,
    /// Wait - receiver needs more time
    Wait = 0x01,
    /// Overflow - receiver buffer overflow, abort transfer
    Overflow = 0x02,
}

impl FlowStatus {
    /// Decode from byte.
    ///
    /// # Errors
    ///
    /// Returns `IsoTpError::InvalidFrame` when the flow status nibble is invalid.
    pub fn from_byte(byte: u8) -> Result<Self, IsoTpError> {
        match byte & 0x0F {
            0x00 => Ok(FlowStatus::ContinueToSend),
            0x01 => Ok(FlowStatus::Wait),
            0x02 => Ok(FlowStatus::Overflow),
            _ => Err(IsoTpError::InvalidFrame {
                reason: format!("invalid flow status: 0x{byte:02X}"),
            }),
        }
    }

    /// Encode to byte.
    #[must_use]
    pub fn to_byte(self) -> u8 {
        self as u8
    }
}

/// `STmin` (Separation Time minimum) encoding.
///
/// Specifies the minimum time between consecutive frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StMin {
    /// Milliseconds (0-127ms)
    Milliseconds(u8),
    /// Microseconds (100-900渭s, in steps of 100)
    Microseconds(u16),
}

impl StMin {
    /// Decode from byte.
    #[must_use]
    pub fn from_byte(byte: u8) -> Self {
        match byte {
            0x00..=0x7F => StMin::Milliseconds(byte),
            0xF1..=0xF9 => StMin::Microseconds(u16::from(byte - 0xF0) * 100),
            // Reserved values treated as 127ms (max)
            _ => StMin::Milliseconds(127),
        }
    }

    /// Encode to byte.
    #[must_use]
    pub fn to_byte(self) -> u8 {
        match self {
            StMin::Milliseconds(ms) => {
                if ms > 127 {
                    127
                } else {
                    ms
                }
            }
            StMin::Microseconds(us) => {
                let hundreds = us / 100;
                if (1..=9).contains(&hundreds) {
                    let hundreds = u8::try_from(hundreds).unwrap_or(0);
                    0xF0 + hundreds
                } else {
                    // 0us => 0ms, >900us => round to 1ms
                    u8::from(hundreds != 0)
                }
            }
        }
    }

    /// Convert to Duration.
    #[must_use]
    pub fn to_duration(self) -> std::time::Duration {
        match self {
            StMin::Milliseconds(ms) => std::time::Duration::from_millis(u64::from(ms)),
            StMin::Microseconds(us) => std::time::Duration::from_micros(u64::from(us)),
        }
    }

    /// Create from Duration (chooses closest encoding).
    #[must_use]
    pub fn from_duration(duration: std::time::Duration) -> Self {
        let micros = duration.as_micros();
        if (100..=900).contains(&micros) {
            // Use microsecond encoding for 100-900渭s
            let rounded = u16::try_from((micros + 50) / 100 * 100).unwrap_or(u16::MAX);
            StMin::Microseconds(rounded.clamp(100, 900))
        } else {
            // Use millisecond encoding
            let millis = u8::try_from(duration.as_millis().min(127)).unwrap_or(127);
            StMin::Milliseconds(millis)
        }
    }
}

impl Default for StMin {
    fn default() -> Self {
        StMin::Milliseconds(10)
    }
}

/// ISO-TP frame types.
#[derive(Debug, Clone, PartialEq)]
pub enum IsoTpFrame {
    /// Single Frame - complete message in one frame
    SingleFrame {
        /// Data length (1-7 for CAN 2.0, 1-62 for CAN-FD)
        data_length: u8,
        /// Payload data
        data: Vec<u8>,
    },

    /// First Frame - start of multi-frame message
    FirstFrame {
        /// Total message length (8-4095)
        total_length: u16,
        /// First chunk of data (6 bytes for CAN 2.0, up to 62 for CAN-FD)
        data: Vec<u8>,
    },

    /// Consecutive Frame - continuation of multi-frame message
    ConsecutiveFrame {
        /// Sequence number (0-15, wraps around)
        sequence_number: u8,
        /// Data chunk (7 bytes for CAN 2.0, up to 63 for CAN-FD)
        data: Vec<u8>,
    },

    /// Flow Control - receiver feedback to sender
    FlowControl {
        /// Flow status
        flow_status: FlowStatus,
        /// Block size (0 = no limit)
        block_size: u8,
        /// Minimum separation time
        st_min: StMin,
    },
}

impl IsoTpFrame {
    /// Decode from CAN message data.
    ///
    /// # Errors
    ///
    /// Returns `IsoTpError::InvalidFrame` when data is malformed or incomplete.
    pub fn decode(data: &[u8]) -> Result<Self, IsoTpError> {
        if data.is_empty() {
            return Err(IsoTpError::InvalidFrame {
                reason: "empty data".to_string(),
            });
        }

        let pci = data[0] & 0xF0;

        match pci {
            PCI_SINGLE_FRAME => Self::decode_single_frame(data),
            PCI_FIRST_FRAME => Self::decode_first_frame(data),
            PCI_CONSECUTIVE_FRAME => Ok(Self::decode_consecutive_frame(data)),
            PCI_FLOW_CONTROL => Self::decode_flow_control(data),
            _ => Err(IsoTpError::InvalidPci { pci: data[0] }),
        }
    }

    fn decode_single_frame(data: &[u8]) -> Result<Self, IsoTpError> {
        let data_length = data[0] & 0x0F;

        if data_length == 0 {
            return Err(IsoTpError::InvalidFrame {
                reason: "SF data length is 0".to_string(),
            });
        }

        let payload_start = 1;
        let payload_end = payload_start + data_length as usize;

        if data.len() < payload_end {
            return Err(IsoTpError::InvalidFrame {
                reason: format!(
                    "SF too short: need {} bytes, got {}",
                    payload_end,
                    data.len()
                ),
            });
        }

        Ok(IsoTpFrame::SingleFrame {
            data_length,
            data: data[payload_start..payload_end].to_vec(),
        })
    }

    fn decode_first_frame(data: &[u8]) -> Result<Self, IsoTpError> {
        if data.len() < 2 {
            return Err(IsoTpError::InvalidFrame {
                reason: "FF too short".to_string(),
            });
        }

        let total_length = (u16::from(data[0] & 0x0F) << 8) | u16::from(data[1]);

        if total_length < 8 {
            return Err(IsoTpError::InvalidFrame {
                reason: format!("FF total length too small: {total_length}"),
            });
        }

        // First frame data starts at byte 2
        let payload = data[2..].to_vec();

        Ok(IsoTpFrame::FirstFrame {
            total_length,
            data: payload,
        })
    }

    fn decode_consecutive_frame(data: &[u8]) -> Self {
        let sequence_number = data[0] & 0x0F;

        // CF data starts at byte 1
        let payload = data[1..].to_vec();

        IsoTpFrame::ConsecutiveFrame {
            sequence_number,
            data: payload,
        }
    }

    fn decode_flow_control(data: &[u8]) -> Result<Self, IsoTpError> {
        if data.len() < 3 {
            return Err(IsoTpError::InvalidFrame {
                reason: format!("FC too short: need 3 bytes, got {}", data.len()),
            });
        }

        let flow_status = FlowStatus::from_byte(data[0])?;
        let block_size = data[1];
        let st_min = StMin::from_byte(data[2]);

        Ok(IsoTpFrame::FlowControl {
            flow_status,
            block_size,
            st_min,
        })
    }

    /// Encode to CAN message data.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        match self {
            IsoTpFrame::SingleFrame { data_length, data } => {
                let mut result = vec![PCI_SINGLE_FRAME | (*data_length & 0x0F)];
                result.extend_from_slice(data);
                result
            }

            IsoTpFrame::FirstFrame { total_length, data } => {
                let high = u8::try_from((*total_length >> 8) & 0x0F).unwrap_or(0);
                let low = u8::try_from(*total_length & 0xFF).unwrap_or(0);
                let mut result = vec![PCI_FIRST_FRAME | high, low];
                result.extend_from_slice(data);
                result
            }

            IsoTpFrame::ConsecutiveFrame {
                sequence_number,
                data,
            } => {
                let mut result = vec![PCI_CONSECUTIVE_FRAME | (*sequence_number & 0x0F)];
                result.extend_from_slice(data);
                result
            }

            IsoTpFrame::FlowControl {
                flow_status,
                block_size,
                st_min,
            } => {
                vec![
                    PCI_FLOW_CONTROL | flow_status.to_byte(),
                    *block_size,
                    st_min.to_byte(),
                ]
            }
        }
    }

    /// Get the PCI type nibble.
    #[must_use]
    pub fn pci_type(&self) -> u8 {
        match self {
            IsoTpFrame::SingleFrame { .. } => PCI_SINGLE_FRAME,
            IsoTpFrame::FirstFrame { .. } => PCI_FIRST_FRAME,
            IsoTpFrame::ConsecutiveFrame { .. } => PCI_CONSECUTIVE_FRAME,
            IsoTpFrame::FlowControl { .. } => PCI_FLOW_CONTROL,
        }
    }

    /// Check if this is a Single Frame.
    #[must_use]
    pub fn is_single_frame(&self) -> bool {
        matches!(self, IsoTpFrame::SingleFrame { .. })
    }

    /// Check if this is a First Frame.
    #[must_use]
    pub fn is_first_frame(&self) -> bool {
        matches!(self, IsoTpFrame::FirstFrame { .. })
    }

    /// Check if this is a Consecutive Frame.
    #[must_use]
    pub fn is_consecutive_frame(&self) -> bool {
        matches!(self, IsoTpFrame::ConsecutiveFrame { .. })
    }

    /// Check if this is a Flow Control frame.
    #[must_use]
    pub fn is_flow_control(&self) -> bool {
        matches!(self, IsoTpFrame::FlowControl { .. })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_flow_status_roundtrip() {
        assert_eq!(
            FlowStatus::from_byte(0x00).unwrap(),
            FlowStatus::ContinueToSend
        );
        assert_eq!(FlowStatus::from_byte(0x01).unwrap(), FlowStatus::Wait);
        assert_eq!(FlowStatus::from_byte(0x02).unwrap(), FlowStatus::Overflow);

        assert_eq!(FlowStatus::ContinueToSend.to_byte(), 0x00);
        assert_eq!(FlowStatus::Wait.to_byte(), 0x01);
        assert_eq!(FlowStatus::Overflow.to_byte(), 0x02);
    }

    #[test]
    fn test_flow_status_invalid() {
        assert!(FlowStatus::from_byte(0x03).is_err());
        assert!(FlowStatus::from_byte(0x0F).is_err());
    }

    #[test]
    fn test_stmin_milliseconds() {
        assert_eq!(StMin::from_byte(0x00), StMin::Milliseconds(0));
        assert_eq!(StMin::from_byte(0x7F), StMin::Milliseconds(127));
        assert_eq!(StMin::from_byte(0x50), StMin::Milliseconds(80));

        assert_eq!(StMin::Milliseconds(0).to_byte(), 0x00);
        assert_eq!(StMin::Milliseconds(127).to_byte(), 0x7F);
        assert_eq!(StMin::Milliseconds(200).to_byte(), 127); // Clamped
    }

    #[test]
    fn test_stmin_microseconds() {
        assert_eq!(StMin::from_byte(0xF1), StMin::Microseconds(100));
        assert_eq!(StMin::from_byte(0xF5), StMin::Microseconds(500));
        assert_eq!(StMin::from_byte(0xF9), StMin::Microseconds(900));

        assert_eq!(StMin::Microseconds(100).to_byte(), 0xF1);
        assert_eq!(StMin::Microseconds(500).to_byte(), 0xF5);
        assert_eq!(StMin::Microseconds(900).to_byte(), 0xF9);
    }

    #[test]
    fn test_stmin_reserved() {
        // Reserved values should be treated as 127ms
        assert_eq!(StMin::from_byte(0x80), StMin::Milliseconds(127));
        assert_eq!(StMin::from_byte(0xF0), StMin::Milliseconds(127));
        assert_eq!(StMin::from_byte(0xFF), StMin::Milliseconds(127));
    }

    #[test]
    fn test_stmin_duration() {
        use std::time::Duration;

        assert_eq!(
            StMin::Milliseconds(10).to_duration(),
            Duration::from_millis(10)
        );
        assert_eq!(
            StMin::Microseconds(500).to_duration(),
            Duration::from_micros(500)
        );

        assert_eq!(
            StMin::from_duration(Duration::from_millis(50)),
            StMin::Milliseconds(50)
        );
        assert_eq!(
            StMin::from_duration(Duration::from_micros(500)),
            StMin::Microseconds(500)
        );
    }

    #[test]
    fn test_single_frame_decode() {
        let data = [0x03, 0x01, 0x02, 0x03];
        let frame = IsoTpFrame::decode(&data).unwrap();

        match frame {
            IsoTpFrame::SingleFrame { data_length, data } => {
                assert_eq!(data_length, 3);
                assert_eq!(data, vec![0x01, 0x02, 0x03]);
            }
            _ => panic!("Expected SingleFrame"),
        }
    }

    #[test]
    fn test_single_frame_encode() {
        let frame = IsoTpFrame::SingleFrame {
            data_length: 3,
            data: vec![0x01, 0x02, 0x03],
        };
        let encoded = frame.encode();
        assert_eq!(encoded, vec![0x03, 0x01, 0x02, 0x03]);
    }

    #[test]
    fn test_first_frame_decode() {
        let data = [0x10, 0x14, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
        let frame = IsoTpFrame::decode(&data).unwrap();

        match frame {
            IsoTpFrame::FirstFrame { total_length, data } => {
                assert_eq!(total_length, 20);
                assert_eq!(data, vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
            }
            _ => panic!("Expected FirstFrame"),
        }
    }

    #[test]
    fn test_first_frame_encode() {
        let frame = IsoTpFrame::FirstFrame {
            total_length: 20,
            data: vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
        };
        let encoded = frame.encode();
        assert_eq!(
            encoded,
            vec![0x10, 0x14, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]
        );
    }

    #[test]
    fn test_consecutive_frame_decode() {
        let data = [0x21, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D];
        let frame = IsoTpFrame::decode(&data).unwrap();

        match frame {
            IsoTpFrame::ConsecutiveFrame {
                sequence_number,
                data,
            } => {
                assert_eq!(sequence_number, 1);
                assert_eq!(data, vec![0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D]);
            }
            _ => panic!("Expected ConsecutiveFrame"),
        }
    }

    #[test]
    fn test_consecutive_frame_encode() {
        let frame = IsoTpFrame::ConsecutiveFrame {
            sequence_number: 5,
            data: vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
        };
        let encoded = frame.encode();
        assert_eq!(
            encoded,
            vec![0x25, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
        );
    }

    #[test]
    fn test_flow_control_decode() {
        let data = [0x30, 0x08, 0x14]; // CTS, BS=8, STmin=20ms
        let frame = IsoTpFrame::decode(&data).unwrap();

        match frame {
            IsoTpFrame::FlowControl {
                flow_status,
                block_size,
                st_min,
            } => {
                assert_eq!(flow_status, FlowStatus::ContinueToSend);
                assert_eq!(block_size, 8);
                assert_eq!(st_min, StMin::Milliseconds(20));
            }
            _ => panic!("Expected FlowControl"),
        }
    }

    #[test]
    fn test_flow_control_encode() {
        let frame = IsoTpFrame::FlowControl {
            flow_status: FlowStatus::Wait,
            block_size: 0,
            st_min: StMin::Microseconds(500),
        };
        let encoded = frame.encode();
        assert_eq!(encoded, vec![0x31, 0x00, 0xF5]);
    }

    #[test]
    fn test_frame_type_checks() {
        let sf = IsoTpFrame::SingleFrame {
            data_length: 1,
            data: vec![0x00],
        };
        assert!(sf.is_single_frame());
        assert!(!sf.is_first_frame());
        assert!(!sf.is_consecutive_frame());
        assert!(!sf.is_flow_control());

        let ff = IsoTpFrame::FirstFrame {
            total_length: 20,
            data: vec![],
        };
        assert!(ff.is_first_frame());

        let cf = IsoTpFrame::ConsecutiveFrame {
            sequence_number: 0,
            data: vec![],
        };
        assert!(cf.is_consecutive_frame());

        let fc = IsoTpFrame::FlowControl {
            flow_status: FlowStatus::ContinueToSend,
            block_size: 0,
            st_min: StMin::default(),
        };
        assert!(fc.is_flow_control());
    }

    #[test]
    fn test_invalid_pci() {
        let data = [0x40, 0x00, 0x00]; // Invalid PCI type
        let result = IsoTpFrame::decode(&data);
        assert!(matches!(result, Err(IsoTpError::InvalidPci { pci: 0x40 })));
    }

    #[test]
    fn test_empty_data() {
        let result = IsoTpFrame::decode(&[]);
        assert!(matches!(result, Err(IsoTpError::InvalidFrame { .. })));
    }

    #[test]
    fn test_sf_zero_length() {
        let data = [0x00]; // SF with length 0
        let result = IsoTpFrame::decode(&data);
        assert!(matches!(result, Err(IsoTpError::InvalidFrame { .. })));
    }

    #[test]
    fn test_roundtrip() {
        let frames = vec![
            IsoTpFrame::SingleFrame {
                data_length: 5,
                data: vec![0x01, 0x02, 0x03, 0x04, 0x05],
            },
            IsoTpFrame::FirstFrame {
                total_length: 100,
                data: vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
            },
            IsoTpFrame::ConsecutiveFrame {
                sequence_number: 15,
                data: vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
            },
            IsoTpFrame::FlowControl {
                flow_status: FlowStatus::ContinueToSend,
                block_size: 16,
                st_min: StMin::Milliseconds(25),
            },
        ];

        for frame in frames {
            let encoded = frame.encode();
            let decoded = IsoTpFrame::decode(&encoded).unwrap();
            assert_eq!(frame, decoded);
        }
    }
}