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, CoreWatchSlot, 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
107enum PollRead {
109 Stopped,
111 Idle,
113 Data(usize),
115}
116
117fn poll_read_port(
118 port: &Arc<Mutex<Box<dyn SerialPort>>>,
119 buf: &mut [u8],
120 stop_rx: &Receiver<()>,
121 timeout: Duration,
122) -> std::io::Result<PollRead> {
123 loop {
124 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
125 return Ok(PollRead::Stopped);
126 }
127 let mut p = match port.try_lock() {
128 Ok(g) => g,
129 Err(_) => {
130 thread::sleep(Duration::from_millis(1));
131 continue;
132 }
133 };
134 let _ = p.set_timeout(timeout);
135 match p.read(buf) {
136 Ok(n) => return Ok(PollRead::Data(n)),
137 Err(e) if is_benign_read_error(&e) => return Ok(PollRead::Idle),
139 Err(e) => return Err(e),
140 }
141 }
142}
143
144const MAX_CONSECUTIVE_EOF_READS: u32 = 3;
149
150const EOF_MEANS_DISCONNECT: bool = !cfg!(target_os = "android");
153
154fn note_eof(read: &PollRead, buf_len: usize, eof_reads: &mut u32) -> bool {
157 match read {
158 PollRead::Data(0) if buf_len > 0 && EOF_MEANS_DISCONNECT => {
159 *eof_reads += 1;
160 if *eof_reads >= MAX_CONSECUTIVE_EOF_READS {
161 return true;
162 }
163 thread::sleep(POLL_TIMEOUT);
164 }
165 PollRead::Data(0) => thread::sleep(Duration::from_millis(1)),
166 _ => *eof_reads = 0,
167 }
168 false
169}
170
171fn report_disconnect(
173 shared: &RxHubShared,
174 path: &str,
175 reason: &str,
176 on_disconnect: &mut Option<DisconnectHook>,
177) {
178 shared.fail_all_waiters(reason);
179 shared.emit_disconnect(path, reason);
180 #[cfg(target_os = "android")]
183 {
184 crate::android::registry::on_usb_error(path, reason);
185 let _ = crate::android::driver_host::global_host().close(Some(path));
186 }
187 if let Some(hook) = on_disconnect.take() {
188 hook(reason);
189 }
190}
191
192const EOF_REASON: &str = "Serial port disconnected: EOF";
193
194const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;
198
199fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
200 shared.fail_all_waiters("port closed");
201 shared.finish_watch_stream(routing);
202 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
203}
204
205pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;
208
209pub struct PortRxHub {
211 shared: Arc<RxHubShared>,
212 stop_tx: Sender<()>,
213 thread: Option<JoinHandle<()>>,
214}
215
216impl PortRxHub {
217 pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
218 Self::start_with(port, path, None, None)
219 }
220
221 pub(crate) fn start_with(
224 port: Arc<Mutex<Box<dyn SerialPort>>>,
225 path: String,
226 on_disconnect: Option<DisconnectHook>,
227 first_watch: Option<CoreWatchSlot>,
228 ) -> Self {
229 let shared = Arc::new(RxHubShared::for_path(path.clone()));
230 if let Some(slot) = first_watch {
231 shared.attach_core_watch(slot);
232 }
233 let (stop_tx, stop_rx) = mpsc::channel();
234 let shared_clone = shared.clone();
235 let thread =
236 thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx, on_disconnect));
237 Self {
238 shared,
239 stop_tx,
240 thread: Some(thread),
241 }
242 }
243
244 pub fn shared(&self) -> Arc<RxHubShared> {
245 self.shared.clone()
246 }
247
248 pub fn is_finished(&self) -> bool {
249 self.thread
250 .as_ref()
251 .map(JoinHandle::is_finished)
252 .unwrap_or(true)
253 }
254
255 #[cfg(feature = "tauri")]
257 pub fn attach_watch(
258 &self,
259 channel: tauri::ipc::Channel<SerialEvent>,
260 batch_timeout_ms: u64,
261 read_size: usize,
262 route_urc: bool,
263 ) {
264 self.shared
265 .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
266 }
267
268 pub fn attach_watch_with(
269 &self,
270 channel: crate::events::EventSink,
271 batch_timeout_ms: u64,
272 read_size: usize,
273 route_urc: bool,
274 framer: Option<Box<dyn Framer>>,
275 ) {
276 self.shared
277 .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
278 }
279
280 pub fn detach_watch(&self) {
281 self.shared.detach_watch();
282 }
283
284 pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
285 self.shared.set_exchange_waiter(waiter);
286 }
287
288 pub fn clear_exchange_waiter(&self) {
289 self.shared.clear_exchange_waiter();
290 }
291
292 pub fn cancel_active_exchange(&self) {
293 self.shared.cancel_active_exchange();
294 }
295
296 pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
297 self.shared.attach_cmux(session);
298 }
299
300 pub fn detach_cmux(&self) {
301 self.shared.detach_cmux();
302 }
303
304 pub fn drain(
306 &self,
307 idle_ms: u64,
308 max_ms: u64,
309 cancel: Arc<AtomicBool>,
310 solicited_prefixes: Vec<String>,
311 ) -> Result<Vec<u8>, String> {
312 self.shared
313 .drain(idle_ms, max_ms, cancel, solicited_prefixes)
314 }
315
316 pub fn request_stop(&self) {
317 let _ = self.stop_tx.send(());
318 }
319
320 pub fn stop(mut self) {
323 let _ = self.stop_tx.send(());
324 if let Some(h) = self.thread.take() {
325 if h.thread().id() != thread::current().id() {
326 let _ = h.join();
327 }
328 }
329 }
330}
331
332impl crate::hub::handle::RxHubHandle for PortRxHub {
333 fn shared(&self) -> Arc<RxHubShared> {
334 self.shared()
335 }
336 fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
337 self.set_exchange_waiter(waiter);
338 }
339 fn clear_exchange_waiter(&self) {
340 self.clear_exchange_waiter();
341 }
342 fn cancel_active_exchange(&self) {
343 self.cancel_active_exchange();
344 }
345 fn attach_watch_with(
346 &self,
347 channel: crate::events::EventSink,
348 batch_timeout_ms: u64,
349 read_size: usize,
350 route_urc: bool,
351 framer: Option<Box<dyn Framer>>,
352 ) {
353 self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
354 }
355 fn detach_watch(&self) {
356 self.detach_watch();
357 }
358 fn attach_cmux(&self, session: Arc<CmuxSession>) {
359 self.attach_cmux(session);
360 }
361 fn detach_cmux(&self) {
362 self.detach_cmux();
363 }
364 fn shutdown_hub(&self) {
365 self.request_stop();
366 }
367}
368
369fn hub_loop(
370 port: Arc<Mutex<Box<dyn SerialPort>>>,
371 path: String,
372 shared: Arc<RxHubShared>,
373 stop_rx: Receiver<()>,
374 mut on_disconnect: Option<DisconnectHook>,
375) {
376 let mut routing = HubRoutingState::new(path.clone());
377 let mut read_size = 1024usize;
378 let mut last_error_emit = Instant::now() - Duration::from_secs(1);
379 let mut consecutive_errors = 0u32;
380 let mut eof_reads = 0u32;
381
382 loop {
383 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
384 shutdown_hub_state(&shared, &mut routing);
385 break;
386 }
387
388 if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
389 try_complete_drain(&shared);
390 if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
391 continue;
392 }
393
394 let mut buf = vec![0u8; 1024];
395 let read = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
396 Ok(PollRead::Stopped) => {
397 shutdown_hub_state(&shared, &mut routing);
398 break;
399 }
400 Ok(read) => read,
401 Err(e) => {
402 finish_drain(&shared, Err(format!("drain read failed: {}", e)));
403 continue;
404 }
405 };
406 if note_eof(&read, buf.len(), &mut eof_reads) {
407 if shared.is_closing() {
408 shutdown_hub_state(&shared, &mut routing);
409 } else {
410 shared.flush_watch_now(&mut routing);
411 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
412 report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
413 }
414 break;
415 }
416 let n = match read {
417 PollRead::Data(n) => n,
418 _ => 0,
419 };
420
421 if n > 0 {
422 shared.feed_bytes(&buf[..n], &mut routing);
425 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
426 }
427 shared.tick(&path, &mut routing);
430 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
431 continue;
432 }
433
434 let mut timeout = POLL_TIMEOUT;
437 if let Some(size) = shared.read_size() {
438 read_size = size;
439 }
440 if let Some(d) = shared.next_framer_deadline() {
441 timeout = d
442 .saturating_duration_since(Instant::now())
443 .clamp(Duration::from_millis(1), POLL_TIMEOUT);
444 }
445
446 let mut buf = vec![0u8; read_size];
447 let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);
448
449 if read_result.is_ok() {
450 consecutive_errors = 0;
451 }
452 if let Ok(read) = &read_result {
453 if note_eof(read, buf.len(), &mut eof_reads) {
454 shared.flush_watch_now(&mut routing);
455 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
456 if shared.is_closing() {
457 shutdown_hub_state(&shared, &mut routing);
459 } else {
460 report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
461 }
462 break;
463 }
464 }
465 match read_result {
466 Ok(PollRead::Stopped) => {
467 shutdown_hub_state(&shared, &mut routing);
468 break;
469 }
470 Ok(PollRead::Data(n)) if n > 0 => {
471 shared.feed_bytes(&buf[..n], &mut routing);
472 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
473 }
474 Ok(PollRead::Data(_)) => {}
475 Ok(PollRead::Idle) => {
476 thread::sleep(Duration::from_millis(1));
477 }
478 Err(e) => {
479 consecutive_errors += 1;
480 shared.flush_watch_now(&mut routing);
481 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
482 if shared.is_closing() {
483 shutdown_hub_state(&shared, &mut routing);
485 break;
486 }
487 if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
488 {
489 let reason = format!("Serial port disconnected: {}", e);
490 report_disconnect(&shared, &path, &reason, &mut on_disconnect);
491 break;
492 }
493 if last_error_emit.elapsed() >= Duration::from_secs(1) {
494 last_error_emit = Instant::now();
495 shared.emit(SerialEvent::Error {
496 path: path.clone(),
497 message: format!("Serial read error: {}", e),
498 });
499 }
500 thread::sleep(Duration::from_millis(50));
501 }
502 }
503
504 shared.tick(&path, &mut routing);
505 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
506 }
507}
508
509#[cfg(all(test, unix, not(any(target_os = "android", target_os = "ios"))))]
510mod tests {
511 use super::*;
512 use std::io::Write;
513
514 #[test]
517 fn parser_timer_fires_during_drain() {
518 let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
519 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
520 let hub = PortRxHub::start(port, "pty".into());
521 let (tx, rx) = mpsc::channel();
522 let tx = Mutex::new(tx);
523 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
524 if let SerialEvent::Data { data, .. } = event {
525 let _ = tx.lock().unwrap().send(data);
526 }
527 true
528 });
529 let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(
530 serde_json::json!({"type": "interByteTimeout", "interval": 150}),
531 )
532 .unwrap();
533 hub.attach_watch_with(channel, 10_000, 64, false, Some(cfg.build().unwrap()));
534 master.write_all(&[1, 2]).unwrap();
535 thread::sleep(Duration::from_millis(50)); let shared = hub.shared();
537 let drainer = thread::spawn(move || {
538 shared.drain(2_000, 3_000, Arc::new(AtomicBool::new(false)), vec![])
539 });
540 let frame = rx
541 .recv_timeout(Duration::from_millis(1_000))
542 .expect("parser frame held back by the drain");
543 assert_eq!(frame, vec![1, 2]);
544 assert!(!drainer.is_finished(), "drain should still be running");
545 let _ = drainer.join();
546 hub.stop();
547 }
548}