Skip to main content

serialplugin_core/
error.rs

1#[cfg(target_os = "ios")]
2use crate::serialport;
3use serde::{Serialize, Serializer};
4use std::io;
5
6/// An error type for serial port operations
7#[derive(Debug)]
8pub enum Error {
9    /// IO Error (stored as string to allow cloning)
10    Io(String),
11    /// String error message
12    String(String),
13    /// Serial port error
14    SerialPort(String),
15}
16
17impl Clone for Error {
18    fn clone(&self) -> Self {
19        match self {
20            Error::Io(s) => Error::Io(s.clone()),
21            Error::String(s) => Error::String(s.clone()),
22            Error::SerialPort(s) => Error::SerialPort(s.clone()),
23        }
24    }
25}
26
27impl Error {
28    pub fn new(msg: impl Into<String>) -> Self {
29        Error::String(msg.into())
30    }
31}
32
33impl std::fmt::Display for Error {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Error::Io(err) => write!(f, "IO error: {}", err),
37            Error::String(s) => write!(f, "{}", s),
38            Error::SerialPort(err) => write!(f, "Serial port error: {}", err),
39        }
40    }
41}
42
43impl std::error::Error for Error {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        match self {
46            Error::Io(_) => None,
47            Error::SerialPort(_) => None,
48            Error::String(_) => None,
49        }
50    }
51}
52
53impl From<io::Error> for Error {
54    fn from(err: io::Error) -> Self {
55        Error::Io(err.to_string())
56    }
57}
58
59impl From<serialport::Error> for Error {
60    fn from(err: serialport::Error) -> Self {
61        Error::SerialPort(err.to_string())
62    }
63}
64
65impl From<&str> for Error {
66    fn from(err: &str) -> Self {
67        Error::String(err.to_string())
68    }
69}
70
71impl From<String> for Error {
72    fn from(err: String) -> Self {
73        Error::String(err)
74    }
75}
76
77/// 4.0.0 API on Android (feature `tauri`, enabled by the plugin).
78#[cfg(all(target_os = "android", feature = "tauri"))]
79impl From<tauri::plugin::mobile::PluginInvokeError> for Error {
80    fn from(error: tauri::plugin::mobile::PluginInvokeError) -> Self {
81        Error::String(error.to_string())
82    }
83}
84
85impl From<Error> for io::Error {
86    fn from(error: Error) -> io::Error {
87        match error {
88            Error::Io(e) => io::Error::other(e),
89            Error::String(s) => io::Error::other(s),
90            Error::SerialPort(e) => io::Error::other(e),
91        }
92    }
93}
94
95impl Serialize for Error {
96    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
97    where
98        S: Serializer,
99    {
100        serializer.serialize_str(&self.to_string())
101    }
102}
103
104/// What went wrong, for code that has to react (retry, reopen, give up). See [`CoreError`].
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106#[non_exhaustive]
107pub enum ErrorKind {
108    /// No such port, device or watch (also: the port is not open).
109    NotFound,
110    PermissionDenied,
111    /// The port or a slot is taken (opened elsewhere, a read / drain / open in progress).
112    Busy,
113    /// The device went away (unplug, EOF, broken pipe).
114    Disconnected,
115    Timeout,
116    Cancelled,
117    Other,
118}
119
120impl ErrorKind {
121    pub fn from_io(kind: io::ErrorKind) -> Self {
122        use io::ErrorKind as K;
123        match kind {
124            K::NotFound => Self::NotFound,
125            K::PermissionDenied => Self::PermissionDenied,
126            K::TimedOut | K::WouldBlock => Self::Timeout,
127            K::BrokenPipe
128            | K::NotConnected
129            | K::ConnectionAborted
130            | K::ConnectionReset
131            | K::UnexpectedEof => Self::Disconnected,
132            K::AddrInUse | K::ResourceBusy => Self::Busy,
133            K::Interrupted => Self::Cancelled,
134            _ => Self::Other,
135        }
136    }
137
138    pub fn from_serialport(err: &serialport::Error) -> Self {
139        match err.kind() {
140            // serialport reports a port in use as NoDevice too: EBUSY, its flock
141            // ("Unable to acquire exclusive lock") and Windows ERROR_ACCESS_DENIED.
142            serialport::ErrorKind::NoDevice
143                if ["busy", "exclusive lock", "access is denied"]
144                    .iter()
145                    .any(|n| err.to_string().to_lowercase().contains(n)) =>
146            {
147                Self::Busy
148            }
149            serialport::ErrorKind::NoDevice => Self::NotFound,
150            serialport::ErrorKind::Io(kind) => Self::from_io(kind),
151            _ => Self::Other,
152        }
153    }
154
155    /// Classify one of the core's own 4.x messages.
156    // ponytail: text matching over the core's own message strings; carry the kind
157    // through every internal call if a new message ever slips past it.
158    pub fn from_message(message: &str) -> Self {
159        let m = message.to_lowercase();
160        let has = |needles: &[&str]| needles.iter().any(|n| m.contains(n));
161        if has(&["cancel", "port closed"]) {
162            Self::Cancelled
163        } else if has(&["in progress", "already", "busy", "lock timeout"]) {
164            Self::Busy
165        } else if has(&[
166            "disconnect",
167            "broken pipe",
168            "not connected",
169            "connection reset",
170            "connection aborted",
171            "unexpected eof",
172        ]) {
173            Self::Disconnected
174        } else if has(&["timed out", "timeout"]) {
175            Self::Timeout
176        } else if has(&["permission denied", "access is denied", "access denied"]) {
177            Self::PermissionDenied
178        } else if has(&[
179            "not found",
180            "no such file",
181            "not open",
182            "port is closed",
183            "no active watch",
184            "not enabled",
185        ]) {
186            Self::NotFound
187        } else {
188            Self::Other
189        }
190    }
191}
192
193/// Error of the core's new (4.2) methods (`open_core`, `write_core`, `watch_core`, …):
194/// a [`kind`](Self::kind), the message (exactly the 4.x [`Error`] text) and the
195/// underlying error as [`source`](std::error::Error::source). Converts into the old
196/// [`Error`] with the same variant and text.
197#[derive(Debug, Clone)]
198pub struct CoreError {
199    kind: ErrorKind,
200    legacy: Error,
201    source: Option<std::sync::Arc<dyn std::error::Error + Send + Sync>>,
202}
203
204impl CoreError {
205    pub fn new(kind: ErrorKind, error: impl Into<Error>) -> Self {
206        Self {
207            kind,
208            legacy: error.into(),
209            source: None,
210        }
211    }
212
213    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
214        self.source = Some(std::sync::Arc::new(source));
215        self
216    }
217
218    pub fn kind(&self) -> ErrorKind {
219        self.kind
220    }
221
222    /// The same error with another kind.
223    #[cfg(not(any(target_os = "android", target_os = "ios")))]
224    pub(crate) fn with_kind(mut self, kind: ErrorKind) -> Self {
225        self.kind = kind;
226        self
227    }
228
229    pub fn message(&self) -> String {
230        self.legacy.to_string()
231    }
232
233    /// From an I/O failure: kind from `err`, message `context: err`.
234    pub(crate) fn io(context: String, err: io::Error) -> Self {
235        Self::new(
236            ErrorKind::from_io(err.kind()),
237            Error::String(format!("{context}: {err}")),
238        )
239        .with_source(err)
240    }
241
242    /// From a serialport failure: kind from `err`, message `context: err`.
243    #[cfg(not(any(target_os = "android", target_os = "ios")))]
244    pub(crate) fn serialport(context: String, err: serialport::Error) -> Self {
245        Self::new(
246            ErrorKind::from_serialport(&err),
247            Error::String(format!("{context}: {err}")),
248        )
249        .with_source(err)
250    }
251}
252
253impl std::fmt::Display for CoreError {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        self.legacy.fmt(f)
256    }
257}
258
259impl std::error::Error for CoreError {
260    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
261        self.source
262            .as_deref()
263            .map(|s| s as &(dyn std::error::Error + 'static))
264    }
265}
266
267impl From<CoreError> for Error {
268    fn from(error: CoreError) -> Self {
269        error.legacy
270    }
271}
272
273impl From<Error> for CoreError {
274    fn from(error: Error) -> Self {
275        let kind = ErrorKind::from_message(&error.to_string());
276        Self::new(kind, error)
277    }
278}
279
280impl Serialize for CoreError {
281    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
282        serializer.serialize_str(&self.to_string())
283    }
284}