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
29use io_errors::{is_benign_read_error, is_disconnect_read_error};
30
31use crate::cmux::CmuxSession;
32use crate::events::SerialEvent;
33use crate::hub::shared::{
34    finish_drain, try_complete_drain, CoreWatchSlot, ExchangeWaiter, HubRoutingState, RxHubShared,
35    PORT_CLOSED,
36};
37use crate::hub::stream::in_sink;
38use serial_codec::framing::Framer;
39use serialport::SerialPort;
40use std::io::Read;
41use std::sync::atomic::AtomicBool;
42use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
43use std::sync::{Arc, Mutex};
44use std::thread::{self, JoinHandle};
45use std::time::{Duration, Instant};
46
47const POLL_TIMEOUT: Duration = Duration::from_millis(10);
48
49/// One hub read.
50enum PollRead {
51    /// The hub was asked to stop.
52    Stopped,
53    /// Read timeout (or EINTR): no data yet.
54    Idle,
55    /// `Ok(n)`; `Data(0)` with a non-empty buffer is end of stream.
56    Data(usize),
57}
58
59fn poll_read_port(
60    port: &Arc<Mutex<Box<dyn SerialPort>>>,
61    buf: &mut [u8],
62    stop_rx: &Receiver<()>,
63    timeout: Duration,
64) -> std::io::Result<PollRead> {
65    loop {
66        if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
67            return Ok(PollRead::Stopped);
68        }
69        let mut p = match port.try_lock() {
70            Ok(g) => g,
71            Err(_) => {
72                thread::sleep(Duration::from_millis(1));
73                continue;
74            }
75        };
76        let _ = p.set_timeout(timeout);
77        match p.read(buf) {
78            Ok(n) => return Ok(PollRead::Data(n)),
79            // Yield so hub_loop can complete drain idle/deadline and flush watch batches.
80            Err(e) if is_benign_read_error(&e) => return Ok(PollRead::Idle),
81            Err(e) => return Err(e),
82        }
83    }
84}
85
86/// `Ok(0)` reads in a row before the port is treated as gone. serialport reports a
87/// read timeout as `TimedOut` and POLLHUP as `BrokenPipe`, so `Ok(0)` means poll said
88/// "readable" and there was nothing: end of stream (a tty after hang-up / unplug).
89/// TCP turns its first `Ok(0)` into `UnexpectedEof` itself (a closed socket).
90const MAX_CONSECUTIVE_EOF_READS: u32 = 3;
91
92/// The Android USB adapter returns `Ok(0)` on a read timeout, so `Ok(0)` is no EOF
93/// signal there.
94const EOF_MEANS_DISCONNECT: bool = !cfg!(target_os = "android");
95
96/// Track one read for EOF: `true` once enough `Ok(0)` reads came in a row. An `Ok(0)`
97/// that does not end the port waits like a read timeout (never spin on a dead fd).
98fn note_eof(read: &PollRead, eof_reads: &mut u32) -> bool {
99    match read {
100        PollRead::Data(0) if EOF_MEANS_DISCONNECT => {
101            *eof_reads += 1;
102            if *eof_reads >= MAX_CONSECUTIVE_EOF_READS {
103                return true;
104            }
105            thread::sleep(POLL_TIMEOUT);
106        }
107        PollRead::Data(0) => thread::sleep(Duration::from_millis(1)),
108        _ => *eof_reads = 0,
109    }
110    false
111}
112
113/// A real disconnect (not a close): fail waiters, send `Disconnect` once, run the hook. No
114/// sink runs before everything that waits on the port or its CMUX channels has failed.
115fn report_disconnect(
116    shared: &RxHubShared,
117    path: &str,
118    reason: &str,
119    on_disconnect: &mut Option<DisconnectHook>,
120) {
121    shared.fail_waiters(reason);
122    shared.emit_disconnect(path, reason);
123    // Android: clear mobile registry + USB adapter (harness expects
124    // inject_bulk_read_error → on_usb_error → registry drop).
125    #[cfg(target_os = "android")]
126    {
127        crate::android::registry::on_usb_error(path, reason);
128        let _ = crate::android::driver_host::global_host().close(Some(path));
129    }
130    if let Some(hook) = on_disconnect.take() {
131        hook(reason);
132    }
133}
134
135const EOF_REASON: &str = "Serial port disconnected: EOF";
136
137/// Non-benign read errors in a row before the port is treated as gone. Windows reports
138/// an unplugged adapter as PermissionDenied / Other, Unix sometimes as EIO, never as
139/// BrokenPipe, so a persistent error is the only portable unplug signal.
140const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;
141
142fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
143    shared.fail_waiters(PORT_CLOSED);
144    shared.finish_watch_stream(routing);
145    shared.deliver_queued();
146}
147
148/// Called once on the hub thread after a real disconnect (not on close), with the
149/// reason sent in `Disconnect`. It must not join the hub.
150pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;
151
152/// Single RX consumer on the main serial fd (desktop).
153pub struct PortRxHub {
154    shared: Arc<RxHubShared>,
155    stop_tx: Sender<()>,
156    thread: Mutex<Option<JoinHandle<()>>>,
157}
158
159impl PortRxHub {
160    pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
161        Self::start_with(port, path, None, None)
162    }
163
164    /// [`Self::start`] with a hook the hub thread runs after a real disconnect.
165    /// `first_watch` is attached before the first read, so it gets every byte and event.
166    pub(crate) fn start_with(
167        port: Arc<Mutex<Box<dyn SerialPort>>>,
168        path: String,
169        on_disconnect: Option<DisconnectHook>,
170        first_watch: Option<CoreWatchSlot>,
171    ) -> Self {
172        let shared = Arc::new(RxHubShared::for_path(path.clone()));
173        if let Some(slot) = first_watch {
174            shared.attach_core_watch(slot);
175        }
176        let (stop_tx, stop_rx) = mpsc::channel();
177        let shared_clone = shared.clone();
178        let thread =
179            thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx, on_disconnect));
180        Self {
181            shared,
182            stop_tx,
183            thread: Mutex::new(Some(thread)),
184        }
185    }
186
187    pub fn shared(&self) -> Arc<RxHubShared> {
188        self.shared.clone()
189    }
190
191    pub fn is_finished(&self) -> bool {
192        crate::sync_util::lock_or_recover(&self.thread)
193            .as_ref()
194            .is_none_or(JoinHandle::is_finished)
195    }
196
197    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
198    #[cfg(feature = "tauri")]
199    pub fn attach_watch(
200        &self,
201        channel: tauri::ipc::Channel<SerialEvent>,
202        batch_timeout_ms: u64,
203        read_size: usize,
204        route_urc: bool,
205    ) {
206        self.shared
207            .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
208    }
209
210    pub fn attach_watch_with(
211        &self,
212        channel: crate::events::EventSink,
213        batch_timeout_ms: u64,
214        read_size: usize,
215        route_urc: bool,
216        framer: Option<Box<dyn Framer>>,
217    ) {
218        self.shared
219            .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
220    }
221
222    pub fn detach_watch(&self) {
223        self.shared.detach_watch();
224    }
225
226    pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
227        self.shared.set_exchange_waiter(waiter);
228    }
229
230    pub fn clear_exchange_waiter(&self) {
231        self.shared.clear_exchange_waiter();
232    }
233
234    pub fn cancel_active_exchange(&self) {
235        self.shared.cancel_active_exchange();
236    }
237
238    pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
239        self.shared.attach_cmux(session);
240    }
241
242    pub fn detach_cmux(&self) {
243        self.shared.detach_cmux();
244    }
245
246    /// Soft-drain via the hub thread (single reader); URC lines are emitted on the watch channel.
247    pub fn drain(
248        &self,
249        idle_ms: u64,
250        max_ms: u64,
251        cancel: Arc<AtomicBool>,
252        solicited_prefixes: Vec<String>,
253    ) -> Result<Vec<u8>, String> {
254        self.shared
255            .drain(idle_ms, max_ms, cancel, solicited_prefixes)
256    }
257
258    pub fn request_stop(&self) {
259        let _ = self.stop_tx.send(());
260    }
261
262    /// Stop and join the hub thread (not when called from a sink, e.g. one closing its own
263    /// port: then it only asks it to stop).
264    pub fn stop(self) {
265        self.stop_and_join();
266    }
267
268    /// [`Self::stop`] for a shared hub (an exchange in flight holds it too). No event
269    /// reaches a sink after this returns (unless a sink calls it: it must not wait for
270    /// another thread, which may be waiting for it).
271    pub(crate) fn stop_and_join(&self) {
272        let _ = self.stop_tx.send(());
273        let thread = crate::sync_util::lock_or_recover(&self.thread).take();
274        if let Some(h) = thread {
275            if !in_sink() && h.thread().id() != thread::current().id() {
276                let _ = h.join();
277            }
278        }
279        self.shared.settle_events();
280    }
281}
282
283impl crate::hub::handle::RxHubHandle for PortRxHub {
284    fn shared(&self) -> Arc<RxHubShared> {
285        self.shared()
286    }
287    fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
288        self.set_exchange_waiter(waiter);
289    }
290    fn clear_exchange_waiter(&self) {
291        self.clear_exchange_waiter();
292    }
293    fn cancel_active_exchange(&self) {
294        self.cancel_active_exchange();
295    }
296    fn attach_watch_with(
297        &self,
298        channel: crate::events::EventSink,
299        batch_timeout_ms: u64,
300        read_size: usize,
301        route_urc: bool,
302        framer: Option<Box<dyn Framer>>,
303    ) {
304        self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
305    }
306    fn detach_watch(&self) {
307        self.detach_watch();
308    }
309    fn attach_cmux(&self, session: Arc<CmuxSession>) {
310        self.attach_cmux(session);
311    }
312    fn detach_cmux(&self) {
313        self.detach_cmux();
314    }
315    fn shutdown_hub(&self) {
316        self.request_stop();
317    }
318}
319
320fn hub_loop(
321    port: Arc<Mutex<Box<dyn SerialPort>>>,
322    path: String,
323    shared: Arc<RxHubShared>,
324    stop_rx: Receiver<()>,
325    mut on_disconnect: Option<DisconnectHook>,
326) {
327    let mut routing = HubRoutingState::new(path.clone());
328    let mut read_size = 1024usize;
329    let mut last_error_emit = Instant::now() - Duration::from_secs(1);
330    let mut consecutive_errors = 0u32;
331    let mut eof_reads = 0u32;
332
333    loop {
334        if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
335            shutdown_hub_state(&shared, &mut routing);
336            break;
337        }
338
339        if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
340            try_complete_drain(&shared);
341            if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
342                continue;
343            }
344
345            let mut buf = vec![0u8; 1024];
346            let read = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
347                Ok(PollRead::Stopped) => {
348                    shutdown_hub_state(&shared, &mut routing);
349                    break;
350                }
351                Ok(read) => read,
352                Err(e) => {
353                    finish_drain(&shared, Err(format!("drain read failed: {}", e)));
354                    shared.deliver_queued();
355                    continue;
356                }
357            };
358            if note_eof(&read, &mut eof_reads) {
359                if shared.is_closing() {
360                    shutdown_hub_state(&shared, &mut routing);
361                } else {
362                    report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
363                }
364                break;
365            }
366            let n = match read {
367                PollRead::Data(n) => n,
368                _ => 0,
369            };
370
371            if n > 0 {
372                // feed_bytes retries drain then falls through to exchange/watch/idle
373                // if reclaim won during poll_read_port — never drop the chunk.
374                shared.feed_bytes(&buf[..n], &mut routing);
375                shared.deliver_queued();
376            }
377            // Full tick (drain completion, read deadline, watch batch and parser timers):
378            // a time-based parser frame must not wait for the drain to end.
379            shared.tick(&path, &mut routing);
380            shared.deliver_queued();
381            continue;
382        }
383
384        // The read timeout doubles as the parser timer: wake by the framer deadline
385        // (inter-byte timeout) so `tick` polls it on time, never spinning.
386        let mut timeout = POLL_TIMEOUT;
387        if let Some(size) = shared.read_size() {
388            read_size = size.max(1); // 0 would never read again
389        }
390        if let Some(d) = shared.next_framer_deadline() {
391            timeout = d
392                .saturating_duration_since(Instant::now())
393                .clamp(Duration::from_millis(1), POLL_TIMEOUT);
394        }
395
396        let mut buf = vec![0u8; read_size];
397        let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);
398
399        if read_result.is_ok() {
400            consecutive_errors = 0;
401        }
402        if let Ok(read) = &read_result {
403            if note_eof(read, &mut eof_reads) {
404                if shared.is_closing() {
405                    // Intentional close racing the EOF: no `Disconnect`.
406                    shutdown_hub_state(&shared, &mut routing);
407                } else {
408                    report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
409                }
410                break;
411            }
412        }
413        match read_result {
414            Ok(PollRead::Stopped) => {
415                shutdown_hub_state(&shared, &mut routing);
416                break;
417            }
418            Ok(PollRead::Data(n)) if n > 0 => {
419                shared.feed_bytes(&buf[..n], &mut routing);
420                shared.deliver_queued();
421            }
422            // `Data(0)` that did not end the port: nothing to route.
423            Ok(PollRead::Data(_)) => {}
424            Ok(PollRead::Idle) => {
425                thread::sleep(Duration::from_millis(1));
426            }
427            Err(e) => {
428                consecutive_errors += 1;
429                if shared.is_closing() {
430                    // Intentional close racing a read error: no `Disconnect`.
431                    shutdown_hub_state(&shared, &mut routing);
432                    break;
433                }
434                if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
435                {
436                    let reason = format!("Serial port disconnected: {}", e);
437                    report_disconnect(&shared, &path, &reason, &mut on_disconnect);
438                    break;
439                }
440                shared.flush_watch_now(&mut routing);
441                shared.deliver_queued();
442                if last_error_emit.elapsed() >= Duration::from_secs(1) {
443                    last_error_emit = Instant::now();
444                    shared.emit(SerialEvent::Error {
445                        path: path.clone(),
446                        message: format!("Serial read error: {}", e),
447                    });
448                }
449                thread::sleep(Duration::from_millis(50));
450            }
451        }
452
453        shared.tick(&path, &mut routing);
454        shared.deliver_queued();
455    }
456}