oze_canopen/
error.rs

1use crate::{canopen::RxMessage, transmitter::TxPacket};
2use tokio::{
3    sync::{broadcast, mpsc},
4    time::error::Elapsed,
5};
6
7/// Custom error type for CANopen operations.
8#[derive(Debug)]
9pub enum CoError {
10    /// I/O error.
11    Io(std::io::Error),
12    /// Timeout error.
13    Timeout(Elapsed),
14    /// SDO retry error with retry count.
15    SdoRetryError(usize),
16    /// Error from binrw crate.
17    Binrw(binrw::Error),
18    /// SDO received an unexpected answer.
19    SdoWrongAnswer(String),
20    /// Incorrect ID error.
21    WrongId(String),
22    /// Transmit packet timeout.
23    TxPackerTimeout,
24    /// Receive packet timeout.
25    RxPackerTimeout,
26    /// Error from the socketcan crate.
27    SocketCan(socketcan::Error),
28    /// Frame error with a detailed message.
29    FrameError(String),
30    /// Interface error with a detailed message.
31    InterfaceError(String),
32    /// Error indicating closure.
33    Close,
34}
35
36impl From<binrw::Error> for CoError {
37    fn from(error: binrw::Error) -> Self {
38        CoError::Binrw(error)
39    }
40}
41
42impl From<Elapsed> for CoError {
43    fn from(error: Elapsed) -> Self {
44        CoError::Timeout(error)
45    }
46}
47
48impl From<mpsc::error::SendTimeoutError<TxPacket>> for CoError {
49    fn from(_error: mpsc::error::SendTimeoutError<TxPacket>) -> Self {
50        CoError::TxPackerTimeout
51    }
52}
53
54impl From<broadcast::error::SendError<RxMessage>> for CoError {
55    fn from(_error: broadcast::error::SendError<RxMessage>) -> Self {
56        CoError::TxPackerTimeout
57    }
58}
59
60impl From<std::io::Error> for CoError {
61    fn from(error: std::io::Error) -> Self {
62        CoError::Io(error)
63    }
64}
65
66impl From<socketcan::Error> for CoError {
67    fn from(error: socketcan::Error) -> Self {
68        CoError::SocketCan(error)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn test_coerror_conversions() {
78        use std::io;
79
80        let io_error: CoError = io::Error::new(io::ErrorKind::Other, "io error").into();
81        assert!(matches!(io_error, CoError::Io(_)));
82    }
83}