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 let _ = tx.lock().unwrap().send(event);
49 true
50 });
51 let slot = crate::hub::shared::CoreWatchSlot::new(
53 1,
54 channel,
55 Arc::new(std::sync::atomic::AtomicBool::new(true)),
56 10,
57 64,
58 false,
59 None,
60 );
61 let hub =
62 super::super::PortRxHub::start_with(port, "unplugged".into(), None, Some(slot));
63 let kinds: Vec<&str> = (0..2)
67 .map(|_| {
68 match rx
69 .recv_timeout(Duration::from_secs(2))
70 .expect("no Disconnect after persistent read errors")
71 {
72 SerialEvent::Error { .. } => "error",
73 SerialEvent::Disconnect { .. } => "disconnect",
74 _ => "other",
75 }
76 })
77 .collect();
78 assert_eq!(kinds, ["error", "disconnect"]);
79 hub.stop();
80 }
81
82 #[test]
83 fn eintr_is_benign() {
84 let err = std::io::Error::new(std::io::ErrorKind::Interrupted, "EINTR");
85 assert!(is_benign_read_error(&err));
86 }
87
88 #[test]
89 fn read_timeout_is_benign_not_disconnect() {
90 let err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
91 assert!(is_benign_read_error(&err));
92 assert!(!is_disconnect_read_error(&err));
93 }
94
95 #[test]
96 fn broken_pipe_is_disconnect() {
97 let err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "broken");
98 assert!(!is_benign_read_error(&err));
99 assert!(is_disconnect_read_error(&err));
100 }
101
102 #[test]
103 fn permission_denied_is_neither_benign_nor_disconnect() {
104 let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
105 assert!(!is_benign_read_error(&err));
106 assert!(!is_disconnect_read_error(&err));
107 }
108 }
109}
110
111use io_errors::{is_benign_read_error, is_disconnect_read_error};
112
113use crate::cmux::CmuxSession;
114use crate::events::SerialEvent;
115use crate::hub::shared::{
116 finish_drain, try_complete_drain, CoreWatchSlot, ExchangeWaiter, HubRoutingState, RxHubShared,
117};
118use serial_codec::framing::Framer;
119use serialport::SerialPort;
120use std::io::Read;
121use std::sync::atomic::AtomicBool;
122use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
123use std::sync::{Arc, Mutex};
124use std::thread::{self, JoinHandle};
125use std::time::{Duration, Instant};
126
127const POLL_TIMEOUT: Duration = Duration::from_millis(10);
128
129enum PollRead {
131 Stopped,
133 Idle,
135 Data(usize),
137}
138
139fn poll_read_port(
140 port: &Arc<Mutex<Box<dyn SerialPort>>>,
141 buf: &mut [u8],
142 stop_rx: &Receiver<()>,
143 timeout: Duration,
144) -> std::io::Result<PollRead> {
145 loop {
146 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
147 return Ok(PollRead::Stopped);
148 }
149 let mut p = match port.try_lock() {
150 Ok(g) => g,
151 Err(_) => {
152 thread::sleep(Duration::from_millis(1));
153 continue;
154 }
155 };
156 let _ = p.set_timeout(timeout);
157 match p.read(buf) {
158 Ok(n) => return Ok(PollRead::Data(n)),
159 Err(e) if is_benign_read_error(&e) => return Ok(PollRead::Idle),
161 Err(e) => return Err(e),
162 }
163 }
164}
165
166const MAX_CONSECUTIVE_EOF_READS: u32 = 3;
171
172const EOF_MEANS_DISCONNECT: bool = !cfg!(target_os = "android");
175
176fn note_eof(read: &PollRead, buf_len: usize, eof_reads: &mut u32) -> bool {
179 match read {
180 PollRead::Data(0) if buf_len > 0 && EOF_MEANS_DISCONNECT => {
181 *eof_reads += 1;
182 if *eof_reads >= MAX_CONSECUTIVE_EOF_READS {
183 return true;
184 }
185 thread::sleep(POLL_TIMEOUT);
186 }
187 PollRead::Data(0) => thread::sleep(Duration::from_millis(1)),
188 _ => *eof_reads = 0,
189 }
190 false
191}
192
193fn report_disconnect(
195 shared: &RxHubShared,
196 path: &str,
197 reason: &str,
198 on_disconnect: &mut Option<DisconnectHook>,
199) {
200 shared.fail_all_waiters(reason);
201 shared.emit_disconnect(path, reason);
202 #[cfg(target_os = "android")]
205 {
206 crate::android::registry::on_usb_error(path, reason);
207 let _ = crate::android::driver_host::global_host().close(Some(path));
208 }
209 if let Some(hook) = on_disconnect.take() {
210 hook(reason);
211 }
212}
213
214const EOF_REASON: &str = "Serial port disconnected: EOF";
215
216const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;
220
221fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
222 shared.fail_all_waiters("port closed");
223 shared.finish_watch_stream(routing);
224 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
225}
226
227pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;
230
231pub struct PortRxHub {
233 shared: Arc<RxHubShared>,
234 stop_tx: Sender<()>,
235 thread: Option<JoinHandle<()>>,
236}
237
238impl PortRxHub {
239 pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
240 Self::start_with(port, path, None, None)
241 }
242
243 pub(crate) fn start_with(
246 port: Arc<Mutex<Box<dyn SerialPort>>>,
247 path: String,
248 on_disconnect: Option<DisconnectHook>,
249 first_watch: Option<CoreWatchSlot>,
250 ) -> Self {
251 let shared = Arc::new(RxHubShared::for_path(path.clone()));
252 if let Some(slot) = first_watch {
253 shared.attach_core_watch(slot);
254 }
255 let (stop_tx, stop_rx) = mpsc::channel();
256 let shared_clone = shared.clone();
257 let thread =
258 thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx, on_disconnect));
259 Self {
260 shared,
261 stop_tx,
262 thread: Some(thread),
263 }
264 }
265
266 pub fn shared(&self) -> Arc<RxHubShared> {
267 self.shared.clone()
268 }
269
270 pub fn is_finished(&self) -> bool {
271 self.thread
272 .as_ref()
273 .map(JoinHandle::is_finished)
274 .unwrap_or(true)
275 }
276
277 #[cfg(feature = "tauri")]
279 pub fn attach_watch(
280 &self,
281 channel: tauri::ipc::Channel<SerialEvent>,
282 batch_timeout_ms: u64,
283 read_size: usize,
284 route_urc: bool,
285 ) {
286 self.shared
287 .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
288 }
289
290 pub fn attach_watch_with(
291 &self,
292 channel: crate::events::EventSink,
293 batch_timeout_ms: u64,
294 read_size: usize,
295 route_urc: bool,
296 framer: Option<Box<dyn Framer>>,
297 ) {
298 self.shared
299 .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
300 }
301
302 pub fn detach_watch(&self) {
303 self.shared.detach_watch();
304 }
305
306 pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
307 self.shared.set_exchange_waiter(waiter);
308 }
309
310 pub fn clear_exchange_waiter(&self) {
311 self.shared.clear_exchange_waiter();
312 }
313
314 pub fn cancel_active_exchange(&self) {
315 self.shared.cancel_active_exchange();
316 }
317
318 pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
319 self.shared.attach_cmux(session);
320 }
321
322 pub fn detach_cmux(&self) {
323 self.shared.detach_cmux();
324 }
325
326 pub fn drain(
328 &self,
329 idle_ms: u64,
330 max_ms: u64,
331 cancel: Arc<AtomicBool>,
332 solicited_prefixes: Vec<String>,
333 ) -> Result<Vec<u8>, String> {
334 self.shared
335 .drain(idle_ms, max_ms, cancel, solicited_prefixes)
336 }
337
338 pub fn request_stop(&self) {
339 let _ = self.stop_tx.send(());
340 }
341
342 pub fn stop(mut self) {
345 let _ = self.stop_tx.send(());
346 if let Some(h) = self.thread.take() {
347 if h.thread().id() != thread::current().id() {
348 let _ = h.join();
349 }
350 }
351 }
352}
353
354impl crate::hub::handle::RxHubHandle for PortRxHub {
355 fn shared(&self) -> Arc<RxHubShared> {
356 self.shared()
357 }
358 fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
359 self.set_exchange_waiter(waiter);
360 }
361 fn clear_exchange_waiter(&self) {
362 self.clear_exchange_waiter();
363 }
364 fn cancel_active_exchange(&self) {
365 self.cancel_active_exchange();
366 }
367 fn attach_watch_with(
368 &self,
369 channel: crate::events::EventSink,
370 batch_timeout_ms: u64,
371 read_size: usize,
372 route_urc: bool,
373 framer: Option<Box<dyn Framer>>,
374 ) {
375 self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
376 }
377 fn detach_watch(&self) {
378 self.detach_watch();
379 }
380 fn attach_cmux(&self, session: Arc<CmuxSession>) {
381 self.attach_cmux(session);
382 }
383 fn detach_cmux(&self) {
384 self.detach_cmux();
385 }
386 fn shutdown_hub(&self) {
387 self.request_stop();
388 }
389}
390
391fn hub_loop(
392 port: Arc<Mutex<Box<dyn SerialPort>>>,
393 path: String,
394 shared: Arc<RxHubShared>,
395 stop_rx: Receiver<()>,
396 mut on_disconnect: Option<DisconnectHook>,
397) {
398 let mut routing = HubRoutingState::new(path.clone());
399 let mut read_size = 1024usize;
400 let mut last_error_emit = Instant::now() - Duration::from_secs(1);
401 let mut consecutive_errors = 0u32;
402 let mut eof_reads = 0u32;
403
404 loop {
405 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
406 shutdown_hub_state(&shared, &mut routing);
407 break;
408 }
409
410 if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
411 try_complete_drain(&shared);
412 if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
413 continue;
414 }
415
416 let mut buf = vec![0u8; 1024];
417 let read = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
418 Ok(PollRead::Stopped) => {
419 shutdown_hub_state(&shared, &mut routing);
420 break;
421 }
422 Ok(read) => read,
423 Err(e) => {
424 finish_drain(&shared, Err(format!("drain read failed: {}", e)));
425 continue;
426 }
427 };
428 if note_eof(&read, buf.len(), &mut eof_reads) {
429 if shared.is_closing() {
430 shutdown_hub_state(&shared, &mut routing);
431 } else {
432 shared.flush_watch_now(&mut routing);
433 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
434 report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
435 }
436 break;
437 }
438 let n = match read {
439 PollRead::Data(n) => n,
440 _ => 0,
441 };
442
443 if n > 0 {
444 shared.feed_bytes(&buf[..n], &mut routing);
447 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
448 }
449 shared.tick(&path, &mut routing);
452 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
453 continue;
454 }
455
456 let mut timeout = POLL_TIMEOUT;
459 if let Some(size) = shared.read_size() {
460 read_size = size;
461 }
462 if let Some(d) = shared.next_framer_deadline() {
463 timeout = d
464 .saturating_duration_since(Instant::now())
465 .clamp(Duration::from_millis(1), POLL_TIMEOUT);
466 }
467
468 let mut buf = vec![0u8; read_size];
469 let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);
470
471 if read_result.is_ok() {
472 consecutive_errors = 0;
473 }
474 if let Ok(read) = &read_result {
475 if note_eof(read, buf.len(), &mut eof_reads) {
476 shared.flush_watch_now(&mut routing);
477 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
478 if shared.is_closing() {
479 shutdown_hub_state(&shared, &mut routing);
481 } else {
482 report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
483 }
484 break;
485 }
486 }
487 match read_result {
488 Ok(PollRead::Stopped) => {
489 shutdown_hub_state(&shared, &mut routing);
490 break;
491 }
492 Ok(PollRead::Data(n)) if n > 0 => {
493 shared.feed_bytes(&buf[..n], &mut routing);
494 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
495 }
496 Ok(PollRead::Data(_)) => {}
498 Ok(PollRead::Idle) => {
499 thread::sleep(Duration::from_millis(1));
500 }
501 Err(e) => {
502 consecutive_errors += 1;
503 shared.flush_watch_now(&mut routing);
504 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
505 if shared.is_closing() {
506 shutdown_hub_state(&shared, &mut routing);
508 break;
509 }
510 if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
511 {
512 let reason = format!("Serial port disconnected: {}", e);
513 report_disconnect(&shared, &path, &reason, &mut on_disconnect);
514 break;
515 }
516 if last_error_emit.elapsed() >= Duration::from_secs(1) {
517 last_error_emit = Instant::now();
518 shared.emit(SerialEvent::Error {
519 path: path.clone(),
520 message: format!("Serial read error: {}", e),
521 });
522 }
523 thread::sleep(Duration::from_millis(50));
524 }
525 }
526
527 shared.tick(&path, &mut routing);
528 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
529 }
530}
531
532#[cfg(test)]
533#[cfg(all(unix, not(any(target_os = "android", target_os = "ios"))))]
534mod tests {
535 use super::*;
536 use crate::hub::handle::RxHubHandle;
537 use crate::mock_serial::MockSerialPort;
538 use std::io::Write;
539
540 fn mock_hub() -> PortRxHub {
541 let port: Arc<Mutex<Box<dyn SerialPort>>> =
542 Arc::new(Mutex::new(Box::new(MockSerialPort::new())));
543 PortRxHub::start(port, "mock".into())
544 }
545
546 fn wait_finished(hub: &PortRxHub) {
547 let t = Instant::now();
548 while !hub.is_finished() {
549 assert!(t.elapsed() < Duration::from_secs(2), "hub still running");
550 thread::sleep(Duration::from_millis(2));
551 }
552 }
553
554 #[test]
555 fn eof_reads_count_only_with_a_read_buffer() {
556 let mut eof = 2;
557 assert!(!note_eof(&PollRead::Data(0), 0, &mut eof));
559 assert_eq!(eof, 2);
560 assert!(
561 note_eof(&PollRead::Data(0), 8, &mut eof),
562 "third EOF in a row"
563 );
564 let mut eof = 0;
565 assert!(!note_eof(&PollRead::Data(0), 8, &mut eof));
566 assert_eq!(eof, 1);
567 assert!(!note_eof(&PollRead::Data(3), 8, &mut eof));
568 assert_eq!(eof, 0, "data resets the count");
569 }
570
571 #[test]
572 fn stop_requests_end_the_hub_thread() {
573 let hub = mock_hub();
574 assert!(!hub.is_finished());
575 hub.request_stop();
576 wait_finished(&hub);
577 let hub = mock_hub();
578 RxHubHandle::shutdown_hub(&hub);
579 wait_finished(&hub);
580 }
581
582 #[test]
583 fn hub_and_handle_calls_reach_the_shared_state() {
584 let hub = mock_hub();
585 let shared = hub.shared();
586 let sink: crate::events::EventSink = Arc::new(|_| true);
587 RxHubHandle::attach_watch_with(&hub, sink.clone(), 10, 64, false, None);
588 assert!(shared.has_watch());
589 RxHubHandle::detach_watch(&hub);
590 assert!(!shared.has_watch());
591 hub.attach_watch_with(sink, 10, 64, false, None);
592 hub.detach_watch();
593 assert!(!shared.has_watch());
594
595 let session = CmuxSession::new(
596 "mock".into(),
597 Arc::new(crate::cmux::SerialPortIo(Arc::new(Mutex::new(
598 Box::new(MockSerialPort::new()) as Box<dyn SerialPort>,
599 )))),
600 );
601 RxHubHandle::attach_cmux(&hub, session);
602 assert!(shared.cmux.lock().unwrap().is_some());
603 RxHubHandle::detach_cmux(&hub);
604 assert!(shared.cmux.lock().unwrap().is_none());
605
606 let options = crate::events::ExchangeOptions::default().resolve();
607 for via_handle in [false, true] {
608 let waiter = ExchangeWaiter::new(options.clone(), Arc::new(AtomicBool::new(false)));
609 if via_handle {
610 RxHubHandle::set_exchange_waiter(&hub, waiter);
611 } else {
612 hub.set_exchange_waiter(waiter);
613 }
614 assert!(shared.exchange_waiter.lock().unwrap().is_some());
615 if via_handle {
616 RxHubHandle::clear_exchange_waiter(&hub);
617 } else {
618 hub.clear_exchange_waiter();
619 }
620 assert!(shared.exchange_waiter.lock().unwrap().is_none());
621 }
622 for via_handle in [false, true] {
623 let waiter = ExchangeWaiter::new(options.clone(), Arc::new(AtomicBool::new(false)));
624 shared.set_exchange_waiter(waiter.clone());
625 if via_handle {
626 RxHubHandle::cancel_active_exchange(&hub);
627 } else {
628 hub.cancel_active_exchange();
629 }
630 assert_eq!(waiter.wait(2_000).unwrap_err(), "exchange cancelled");
631 }
632 hub.stop();
633 }
634
635 #[test]
637 fn drain_returns_the_bytes_read_during_it() {
638 let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
639 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
640 let hub = Arc::new(PortRxHub::start(port, "pty".into()));
641 let bg = hub.clone();
642 let drainer =
643 thread::spawn(move || bg.drain(150, 2_000, Arc::new(AtomicBool::new(false)), vec![]));
644 thread::sleep(Duration::from_millis(30));
645 master.write_all(b"abc").unwrap();
646 assert_eq!(drainer.join().unwrap().unwrap(), b"abc");
647 match Arc::try_unwrap(hub) {
648 Ok(hub) => hub.stop(),
649 Err(_) => panic!("hub still shared"),
650 }
651 }
652
653 #[test]
656 fn parser_timer_fires_during_drain() {
657 let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
658 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
659 let hub = PortRxHub::start(port, "pty".into());
660 let (tx, rx) = mpsc::channel();
661 let tx = Mutex::new(tx);
662 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
663 if let SerialEvent::Data { data, .. } = event {
664 let _ = tx.lock().unwrap().send(data);
665 }
666 true
667 });
668 let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(
669 serde_json::json!({"type": "interByteTimeout", "interval": 150}),
670 )
671 .unwrap();
672 hub.attach_watch_with(channel, 10_000, 64, false, Some(cfg.build().unwrap()));
673 master.write_all(&[1, 2]).unwrap();
674 thread::sleep(Duration::from_millis(50)); let shared = hub.shared();
676 let cancel = Arc::new(AtomicBool::new(false));
677 let drain_cancel = cancel.clone();
678 let drainer = thread::spawn(move || shared.drain(2_000, 3_000, drain_cancel, vec![]));
679 let frame = rx
680 .recv_timeout(Duration::from_millis(1_000))
681 .expect("parser frame held back by the drain");
682 assert_eq!(frame, vec![1, 2]);
683 assert!(!drainer.is_finished(), "drain should still be running");
684 cancel.store(true, std::sync::atomic::Ordering::SeqCst);
685 let _ = drainer.join();
686 hub.stop();
687 }
688}