1#[cfg(target_os = "ios")]
3use crate::serialport;
4
5mod io_errors {
6 pub(super) fn is_benign_read_error(err: &std::io::Error) -> bool {
8 matches!(
9 err.kind(),
10 std::io::ErrorKind::TimedOut
11 | std::io::ErrorKind::WouldBlock
12 | std::io::ErrorKind::Interrupted
13 )
14 }
15
16 pub(super) fn is_disconnect_read_error(err: &std::io::Error) -> bool {
18 matches!(
19 err.kind(),
20 std::io::ErrorKind::BrokenPipe
21 | std::io::ErrorKind::NotConnected
22 | std::io::ErrorKind::ConnectionAborted
23 | std::io::ErrorKind::ConnectionReset
24 | std::io::ErrorKind::UnexpectedEof
25 )
26 }
27
28 #[cfg(test)]
29 mod tests {
30 use super::*;
31
32 #[cfg(not(target_os = "android"))]
34 #[test]
35 fn persistent_read_error_ends_in_disconnect_event() {
36 use crate::events::SerialEvent;
37 use crate::mock_serial::MockSerialPort;
38 use std::sync::{Arc, Mutex};
39 use std::time::Duration;
40
41 let mut mock = MockSerialPort::new();
42 mock.sticky_read_error = Some(std::io::ErrorKind::PermissionDenied);
43 let port: Arc<Mutex<Box<dyn serialport::SerialPort>>> =
44 Arc::new(Mutex::new(Box::new(mock)));
45 let (tx, rx) = std::sync::mpsc::channel();
46 let tx = Mutex::new(tx);
47 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
48 if matches!(event, SerialEvent::Disconnect { .. }) {
49 let _ = tx.lock().unwrap().send(());
50 }
51 true
52 });
53 let hub = super::super::PortRxHub::start(port, "unplugged".into());
54 hub.attach_watch_with(channel, 10, 64, false, None);
55 rx.recv_timeout(Duration::from_secs(3))
56 .expect("no Disconnect after persistent read errors");
57 hub.stop();
58 }
59
60 #[test]
61 fn eintr_is_benign() {
62 let err = std::io::Error::new(std::io::ErrorKind::Interrupted, "EINTR");
63 assert!(is_benign_read_error(&err));
64 }
65
66 #[test]
67 fn read_timeout_is_benign_not_disconnect() {
68 let err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
69 assert!(is_benign_read_error(&err));
70 assert!(!is_disconnect_read_error(&err));
71 }
72
73 #[test]
74 fn broken_pipe_is_disconnect() {
75 let err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "broken");
76 assert!(!is_benign_read_error(&err));
77 assert!(is_disconnect_read_error(&err));
78 }
79
80 #[test]
81 fn permission_denied_is_neither_benign_nor_disconnect() {
82 let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
83 assert!(!is_benign_read_error(&err));
84 assert!(!is_disconnect_read_error(&err));
85 }
86 }
87}
88
89use io_errors::{is_benign_read_error, is_disconnect_read_error};
90
91use crate::cmux::CmuxSession;
92use crate::events::SerialEvent;
93use crate::hub::shared::{
94 finish_drain, try_complete_drain, ExchangeWaiter, HubRoutingState, RxHubShared,
95};
96use serial_codec::framing::Framer;
97use serialport::SerialPort;
98use std::io::Read;
99use std::sync::atomic::AtomicBool;
100use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
101use std::sync::{Arc, Mutex};
102use std::thread::{self, JoinHandle};
103use std::time::{Duration, Instant};
104
105const POLL_TIMEOUT: Duration = Duration::from_millis(10);
106
107fn poll_read_port(
109 port: &Arc<Mutex<Box<dyn SerialPort>>>,
110 buf: &mut [u8],
111 stop_rx: &Receiver<()>,
112 timeout: Duration,
113) -> std::io::Result<Option<usize>> {
114 loop {
115 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
116 return Ok(None);
117 }
118 let mut p = match port.try_lock() {
119 Ok(g) => g,
120 Err(_) => {
121 thread::sleep(Duration::from_millis(1));
122 continue;
123 }
124 };
125 let _ = p.set_timeout(timeout);
126 match p.read(buf) {
127 Ok(n) => return Ok(Some(n)),
128 Err(e) if is_benign_read_error(&e) => {
129 drop(p);
130 return Ok(Some(0));
132 }
133 Err(e) => return Err(e),
134 }
135 }
136}
137
138const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;
142
143fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
144 shared.fail_all_waiters("port closed");
145 shared.finish_watch_stream(routing);
146 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
147}
148
149pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;
152
153pub struct PortRxHub {
155 shared: Arc<RxHubShared>,
156 stop_tx: Sender<()>,
157 thread: Option<JoinHandle<()>>,
158}
159
160impl PortRxHub {
161 pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
162 Self::start_with(port, path, None)
163 }
164
165 pub(crate) fn start_with(
167 port: Arc<Mutex<Box<dyn SerialPort>>>,
168 path: String,
169 on_disconnect: Option<DisconnectHook>,
170 ) -> Self {
171 let shared = Arc::new(RxHubShared::for_path(path.clone()));
172 let (stop_tx, stop_rx) = mpsc::channel();
173 let shared_clone = shared.clone();
174 let thread =
175 thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx, on_disconnect));
176 Self {
177 shared,
178 stop_tx,
179 thread: Some(thread),
180 }
181 }
182
183 pub fn shared(&self) -> Arc<RxHubShared> {
184 self.shared.clone()
185 }
186
187 pub fn is_finished(&self) -> bool {
188 self.thread
189 .as_ref()
190 .map(JoinHandle::is_finished)
191 .unwrap_or(true)
192 }
193
194 #[cfg(feature = "tauri")]
196 pub fn attach_watch(
197 &self,
198 channel: tauri::ipc::Channel<SerialEvent>,
199 batch_timeout_ms: u64,
200 read_size: usize,
201 route_urc: bool,
202 ) {
203 self.shared
204 .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
205 }
206
207 pub fn attach_watch_with(
208 &self,
209 channel: crate::events::EventSink,
210 batch_timeout_ms: u64,
211 read_size: usize,
212 route_urc: bool,
213 framer: Option<Box<dyn Framer>>,
214 ) {
215 self.shared
216 .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
217 }
218
219 pub fn detach_watch(&self) {
220 self.shared.detach_watch();
221 }
222
223 pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
224 self.shared.set_exchange_waiter(waiter);
225 }
226
227 pub fn clear_exchange_waiter(&self) {
228 self.shared.clear_exchange_waiter();
229 }
230
231 pub fn cancel_active_exchange(&self) {
232 self.shared.cancel_active_exchange();
233 }
234
235 pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
236 self.shared.attach_cmux(session);
237 }
238
239 pub fn detach_cmux(&self) {
240 self.shared.detach_cmux();
241 }
242
243 pub fn drain(
245 &self,
246 idle_ms: u64,
247 max_ms: u64,
248 cancel: Arc<AtomicBool>,
249 solicited_prefixes: Vec<String>,
250 ) -> Result<Vec<u8>, String> {
251 self.shared
252 .drain(idle_ms, max_ms, cancel, solicited_prefixes)
253 }
254
255 pub fn request_stop(&self) {
256 let _ = self.stop_tx.send(());
257 }
258
259 pub fn stop(mut self) {
262 let _ = self.stop_tx.send(());
263 if let Some(h) = self.thread.take() {
264 if h.thread().id() != thread::current().id() {
265 let _ = h.join();
266 }
267 }
268 }
269}
270
271impl crate::hub::handle::RxHubHandle for PortRxHub {
272 fn shared(&self) -> Arc<RxHubShared> {
273 self.shared()
274 }
275 fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
276 self.set_exchange_waiter(waiter);
277 }
278 fn clear_exchange_waiter(&self) {
279 self.clear_exchange_waiter();
280 }
281 fn cancel_active_exchange(&self) {
282 self.cancel_active_exchange();
283 }
284 fn attach_watch_with(
285 &self,
286 channel: crate::events::EventSink,
287 batch_timeout_ms: u64,
288 read_size: usize,
289 route_urc: bool,
290 framer: Option<Box<dyn Framer>>,
291 ) {
292 self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
293 }
294 fn detach_watch(&self) {
295 self.detach_watch();
296 }
297 fn attach_cmux(&self, session: Arc<CmuxSession>) {
298 self.attach_cmux(session);
299 }
300 fn detach_cmux(&self) {
301 self.detach_cmux();
302 }
303 fn shutdown_hub(&self) {
304 self.request_stop();
305 }
306}
307
308fn hub_loop(
309 port: Arc<Mutex<Box<dyn SerialPort>>>,
310 path: String,
311 shared: Arc<RxHubShared>,
312 stop_rx: Receiver<()>,
313 mut on_disconnect: Option<DisconnectHook>,
314) {
315 let mut routing = HubRoutingState::new(path.clone());
316 let mut read_size = 1024usize;
317 let mut last_error_emit = Instant::now() - Duration::from_secs(1);
318 let mut consecutive_errors = 0u32;
319
320 loop {
321 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
322 shutdown_hub_state(&shared, &mut routing);
323 break;
324 }
325
326 if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
327 try_complete_drain(&shared);
328 if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
329 continue;
330 }
331
332 let mut buf = vec![0u8; 1024];
333 let n = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
334 Ok(Some(n)) => n,
335 Ok(None) => {
336 shutdown_hub_state(&shared, &mut routing);
337 break;
338 }
339 Err(e) => {
340 finish_drain(&shared, Err(format!("drain read failed: {}", e)));
341 continue;
342 }
343 };
344
345 if n > 0 {
346 shared.feed_bytes(&buf[..n], &mut routing);
349 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
350 }
351 shared.tick(&path, &mut routing);
354 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
355 continue;
356 }
357
358 let mut timeout = POLL_TIMEOUT;
361 if let Some(size) = shared.read_size() {
362 read_size = size;
363 }
364 if let Some(d) = shared.next_framer_deadline() {
365 timeout = d
366 .saturating_duration_since(Instant::now())
367 .clamp(Duration::from_millis(1), POLL_TIMEOUT);
368 }
369
370 let mut buf = vec![0u8; read_size];
371 let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);
372
373 if read_result.is_ok() {
374 consecutive_errors = 0;
375 }
376 match read_result {
377 Ok(None) => {
378 shutdown_hub_state(&shared, &mut routing);
379 break;
380 }
381 Ok(Some(n)) if n > 0 => {
382 shared.feed_bytes(&buf[..n], &mut routing);
383 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
384 }
385 Ok(Some(_)) => {
386 thread::sleep(Duration::from_millis(1));
387 }
388 Err(e) => {
389 consecutive_errors += 1;
390 shared.flush_watch_now(&mut routing);
391 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
392 if shared.is_closing() {
393 shutdown_hub_state(&shared, &mut routing);
395 break;
396 }
397 if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
398 {
399 let reason = format!("Serial port disconnected: {}", e);
400 shared.fail_all_waiters(&reason);
401 shared.emit_disconnect(&path, &reason);
402 #[cfg(target_os = "android")]
405 {
406 crate::android::registry::on_usb_error(&path, &reason);
407 let _ = crate::android::driver_host::global_host().close(Some(&path));
408 }
409 if let Some(hook) = on_disconnect.take() {
410 hook(&reason);
411 }
412 break;
413 }
414 if last_error_emit.elapsed() >= Duration::from_secs(1) {
415 last_error_emit = Instant::now();
416 shared.emit(SerialEvent::Error {
417 path: path.clone(),
418 message: format!("Serial read error: {}", e),
419 });
420 }
421 thread::sleep(Duration::from_millis(50));
422 }
423 }
424
425 shared.tick(&path, &mut routing);
426 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
427 }
428}
429
430#[cfg(all(test, unix, not(any(target_os = "android", target_os = "ios"))))]
431mod tests {
432 use super::*;
433 use std::io::Write;
434
435 #[test]
438 fn parser_timer_fires_during_drain() {
439 let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
440 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
441 let hub = PortRxHub::start(port, "pty".into());
442 let (tx, rx) = mpsc::channel();
443 let tx = Mutex::new(tx);
444 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
445 if let SerialEvent::Data { data, .. } = event {
446 let _ = tx.lock().unwrap().send(data);
447 }
448 true
449 });
450 let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(
451 serde_json::json!({"type": "interByteTimeout", "interval": 150}),
452 )
453 .unwrap();
454 hub.attach_watch_with(channel, 10_000, 64, false, Some(cfg.build().unwrap()));
455 master.write_all(&[1, 2]).unwrap();
456 thread::sleep(Duration::from_millis(50)); let shared = hub.shared();
458 let drainer = thread::spawn(move || {
459 shared.drain(2_000, 3_000, Arc::new(AtomicBool::new(false)), vec![])
460 });
461 let frame = rx
462 .recv_timeout(Duration::from_millis(1_000))
463 .expect("parser frame held back by the drain");
464 assert_eq!(frame, vec![1, 2]);
465 assert!(!drainer.is_finished(), "drain should still be running");
466 let _ = drainer.join();
467 hub.stop();
468 }
469}