1#[cfg(target_os = "ios")]
2use crate::serialport;
3use serde::{Serialize, Serializer};
4use std::io;
5
6#[derive(Debug)]
8pub enum Error {
9 Io(String),
11 String(String),
13 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 {}
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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99#[non_exhaustive]
100pub enum ErrorKind {
101 NotFound,
103 PermissionDenied,
104 Busy,
106 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::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 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#[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 #[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 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 #[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}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 #[test]
284 fn io_kinds_map_to_core_kinds() {
285 use io::ErrorKind as K;
286 for (io_kind, kind) in [
287 (K::NotFound, ErrorKind::NotFound),
288 (K::PermissionDenied, ErrorKind::PermissionDenied),
289 (K::TimedOut, ErrorKind::Timeout),
290 (K::WouldBlock, ErrorKind::Timeout),
291 (K::BrokenPipe, ErrorKind::Disconnected),
292 (K::UnexpectedEof, ErrorKind::Disconnected),
293 (K::AddrInUse, ErrorKind::Busy),
294 (K::ResourceBusy, ErrorKind::Busy),
295 (K::Interrupted, ErrorKind::Cancelled),
296 (K::InvalidData, ErrorKind::Other),
297 ] {
298 assert_eq!(ErrorKind::from_io(io_kind), kind, "{io_kind:?}");
299 }
300 }
301
302 #[test]
303 fn core_error_message_is_the_legacy_text() {
304 let e = CoreError::new(ErrorKind::Busy, Error::String("port busy".into()));
305 assert_eq!(e.message(), "port busy");
306 let io = CoreError::io("Failed to write".into(), io::Error::other("gone"));
307 assert_eq!(io.message(), "Failed to write: gone");
308 assert!(std::error::Error::source(&io).is_some());
309 assert!(std::error::Error::source(&Error::Io("x".into())).is_none());
310 }
311}