Skip to main content

serialplugin_core/hub/
desktop.rs

1//! Desktop poll-model RX hub.
2#[cfg(target_os = "ios")]
3use crate::serialport;
4
5mod io_errors {
6    /// Read timeout / would-block — hub may retry.
7    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    /// Fatal disconnect — fail waiters and end the hub loop.
17    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        /// Windows reports an unplugged adapter as PermissionDenied, never BrokenPipe.
33        #[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
107/// One hub read.
108enum PollRead {
109    /// The hub was asked to stop.
110    Stopped,
111    /// Read timeout (or EINTR): no data yet.
112    Idle,
113    /// `Ok(n)`; `Data(0)` with a non-empty buffer is end of stream.
114    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            // Yield so hub_loop can complete drain idle/deadline and flush watch batches.
138            Err(e) if is_benign_read_error(&e) => return Ok(PollRead::Idle),
139            Err(e) => return Err(e),
140        }
141    }
142}
143
144/// `Ok(0)` reads in a row before the port is treated as gone. serialport reports a
145/// read timeout as `TimedOut` and POLLHUP as `BrokenPipe`, so `Ok(0)` means poll said
146/// "readable" and there was nothing: end of stream (a tty after hang-up / unplug).
147/// TCP turns its first `Ok(0)` into `UnexpectedEof` itself (a closed socket).
148const MAX_CONSECUTIVE_EOF_READS: u32 = 3;
149
150/// The Android USB adapter returns `Ok(0)` on a read timeout, so `Ok(0)` is no EOF
151/// signal there.
152const EOF_MEANS_DISCONNECT: bool = !cfg!(target_os = "android");
153
154/// Track one read for EOF: `true` once enough `Ok(0)` reads came in a row. An `Ok(0)`
155/// that does not end the port waits like a read timeout (never spin on a dead fd).
156fn 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
171/// A real disconnect (not a close): fail waiters, send `Disconnect` once, run the hook.
172fn 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    // Android: clear mobile registry + USB adapter (harness expects
181    // inject_bulk_read_error → on_usb_error → registry drop).
182    #[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
194/// Non-benign read errors in a row before the port is treated as gone. Windows reports
195/// an unplugged adapter as PermissionDenied / Other, Unix sometimes as EIO, never as
196/// BrokenPipe, so a persistent error is the only portable unplug signal.
197const 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
205/// Called once on the hub thread after a real disconnect (not on close), with the
206/// reason sent in `Disconnect`. It must not join the hub.
207pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;
208
209/// Single RX consumer on the main serial fd (desktop).
210pub 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    /// [`Self::start`] with a hook the hub thread runs after a real disconnect.
222    /// `first_watch` is attached before the first read, so it gets every byte and event.
223    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    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
256    #[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    /// Soft-drain via the hub thread (single reader); URC lines are emitted on the watch channel.
305    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    /// Stop and join the hub thread (not when called from it, e.g. a watch sink
321    /// closing its own port: then it only asks it to stop).
322    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                // feed_bytes retries drain then falls through to exchange/watch/idle
423                // if reclaim won during poll_read_port — never drop the chunk.
424                shared.feed_bytes(&buf[..n], &mut routing);
425                shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
426            }
427            // Full tick (drain completion, read deadline, watch batch and parser timers):
428            // a time-based parser frame must not wait for the drain to end.
429            shared.tick(&path, &mut routing);
430            shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
431            continue;
432        }
433
434        // The read timeout doubles as the parser timer: wake by the framer deadline
435        // (inter-byte timeout) so `tick` polls it on time, never spinning.
436        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                    // Intentional close racing the EOF: no `Disconnect`.
458                    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                    // Intentional close racing a read error: no `Disconnect`.
484                    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    /// The hub skipped `tick` while a drain was active, so an inter-byte-timeout frame
515    /// waited for the whole drain window.
516    #[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)); // bytes reach the parser
536        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}