1use std::fmt;
4use std::io;
5
6#[derive(Debug)]
8pub enum Error {
9 Io(io::Error),
11 Timeout(String),
13 Protocol(String),
15 At {
17 command: String,
19 lines: Vec<String>,
21 },
22 Parse(String),
24 InvalidArgument(String),
26 Device(String),
28 Busy(String),
31}
32
33pub type Result<T> = std::result::Result<T, Error>;
35
36impl fmt::Display for Error {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Error::Io(e) => write!(f, "I/O error: {e}"),
40 Error::Timeout(s) => write!(f, "timeout: {s}"),
41 Error::Protocol(s) => write!(f, "protocol error: {s}"),
42 Error::At { command, lines } => {
43 write!(f, "{command} -> ERROR")?;
44 if !lines.is_empty() {
45 write!(f, " ({})", lines.join(" | "))?;
46 }
47 Ok(())
48 }
49 Error::Parse(s) => write!(f, "cannot parse the answer: {s}"),
50 Error::InvalidArgument(s) => write!(f, "invalid argument: {s}"),
51 Error::Device(s) => write!(f, "device error: {s}"),
52 Error::Busy(s) => write!(f, "busy: {s}"),
53 }
54 }
55}
56
57impl std::error::Error for Error {
58 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59 match self {
60 Error::Io(e) => Some(e),
61 _ => None,
62 }
63 }
64}
65
66impl From<io::Error> for Error {
67 fn from(e: io::Error) -> Self {
68 Error::Io(e)
69 }
70}
71
72#[cfg(feature = "serial")]
73impl From<serialport::Error> for Error {
74 fn from(e: serialport::Error) -> Self {
75 Error::Io(io::Error::new(io::ErrorKind::Other, e.to_string()))
76 }
77}