seekdas/
error.rs

1//! 错误类型。
2
3use std::fmt;
4use std::io;
5
6/// SDK 所有接口共用的错误类型。
7#[derive(Debug)]
8pub enum Error {
9    /// 套接字或串口的 I/O 错误。
10    Io(io::Error),
11    /// 设备在规定时间内没有应答。字符串说明是哪一步超时。
12    Timeout(String),
13    /// 收到的数据不符合协议(长度、魔数、序号不连续等)。
14    Protocol(String),
15    /// 设备对 AT 指令回答了 `ERROR`。`lines` 是 `ERROR` 之前收到的行。
16    At {
17        /// 发出的指令。
18        command: String,
19        /// `ERROR` 之前设备输出的行。
20        lines: Vec<String>,
21    },
22    /// AT 指令的应答无法解析(固件版本与 SDK 不一致时可能出现)。
23    Parse(String),
24    /// 调用参数超出设备允许的范围。
25    InvalidArgument(String),
26    /// 设备报告了错误状态(丢点、ID 不符等)。
27    Device(String),
28    /// 设备正在采集(触发运行中):此时不能启动新的采集,也不能修改采集配置。
29    /// 等它结束([`Device::trigger_state`](crate::Device::trigger_state)),或先 [`Device::stop`](crate::Device::stop)。
30    Busy(String),
31}
32
33/// `Result<T, seekdas::Error>` 的简写。
34pub 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}