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