ydlidar_rust_driver/
error.rs1use core::fmt;
2
3#[derive(Debug)]
5pub enum LidarError {
6 #[cfg(feature = "std")]
8 SerialPort(serialport::Error),
9 #[cfg(feature = "std")]
11 Io(std::io::Error),
12 Timeout,
14 NotFound,
16 InvalidResponse,
18 CommandFailed,
20 BufferOverflow,
22}
23
24impl fmt::Display for LidarError {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 #[cfg(feature = "std")]
28 LidarError::SerialPort(e) => write!(f, "Serial port error: {}", e),
29 #[cfg(feature = "std")]
30 LidarError::Io(e) => write!(f, "IO error: {}", e),
31 LidarError::Timeout => write!(f, "Command timeout"),
32 LidarError::NotFound => write!(f, "Device not found"),
33 LidarError::InvalidResponse => write!(f, "Invalid response from LIDAR"),
34 LidarError::CommandFailed => write!(f, "Command execution failed"),
35 LidarError::BufferOverflow => write!(f, "Scan buffer overflow"),
36 }
37 }
38}
39
40#[cfg(feature = "std")]
41impl std::error::Error for LidarError {
42 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
43 match self {
44 LidarError::SerialPort(e) => Some(e),
45 LidarError::Io(e) => Some(e),
46 _ => None,
47 }
48 }
49}
50
51#[cfg(feature = "std")]
52impl From<serialport::Error> for LidarError {
53 fn from(e: serialport::Error) -> Self {
54 LidarError::SerialPort(e)
55 }
56}
57
58#[cfg(feature = "std")]
59impl From<std::io::Error> for LidarError {
60 fn from(e: std::io::Error) -> Self {
61 LidarError::Io(e)
62 }
63}
64
65impl embedded_io::Error for LidarError {
66 fn kind(&self) -> embedded_io::ErrorKind {
67 match self {
68 #[cfg(feature = "std")]
69 LidarError::SerialPort(_) => embedded_io::ErrorKind::Other,
70 #[cfg(feature = "std")]
71 LidarError::Io(_) => embedded_io::ErrorKind::Other,
72 LidarError::NotFound => embedded_io::ErrorKind::NotFound,
73 LidarError::Timeout => embedded_io::ErrorKind::TimedOut,
74 LidarError::InvalidResponse => embedded_io::ErrorKind::InvalidData,
75 LidarError::CommandFailed => embedded_io::ErrorKind::Other,
76 LidarError::BufferOverflow => embedded_io::ErrorKind::OutOfMemory,
77 }
78 }
79}
80
81pub type Result<T> = core::result::Result<T, LidarError>;
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn test_error_display() {
90 let err = LidarError::Timeout;
91 assert_eq!(format!("{}", err), "Command timeout");
92
93 let err = LidarError::InvalidResponse;
94 assert_eq!(format!("{}", err), "Invalid response from LIDAR");
95 }
96
97 #[test]
98 fn test_embedded_io_error_kind() {
99 use embedded_io::Error;
100
101 let err = LidarError::Timeout;
102 assert_eq!(err.kind(), embedded_io::ErrorKind::TimedOut);
103
104 let err = LidarError::InvalidResponse;
105 assert_eq!(err.kind(), embedded_io::ErrorKind::InvalidData);
106 }
107}