serialplugin-core 0.2.1

Serial port core of tauri-plugin-serialplugin without Tauri: RX hub, watch streams with native parsers, AT exchange, CMUX, TCP and BLE transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Desktop poll-model RX hub.
#[cfg(target_os = "ios")]
use crate::serialport;

mod io_errors {
    /// Read timeout / would-block — hub may retry.
    pub(super) fn is_benign_read_error(err: &std::io::Error) -> bool {
        matches!(
            err.kind(),
            std::io::ErrorKind::TimedOut
                | std::io::ErrorKind::WouldBlock
                | std::io::ErrorKind::Interrupted
        )
    }

    /// Fatal disconnect — fail waiters and end the hub loop.
    pub(super) fn is_disconnect_read_error(err: &std::io::Error) -> bool {
        matches!(
            err.kind(),
            std::io::ErrorKind::BrokenPipe
                | std::io::ErrorKind::NotConnected
                | std::io::ErrorKind::ConnectionAborted
                | std::io::ErrorKind::ConnectionReset
                | std::io::ErrorKind::UnexpectedEof
        )
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        /// Windows reports an unplugged adapter as PermissionDenied, never BrokenPipe.
        #[cfg(not(target_os = "android"))]
        #[test]
        fn persistent_read_error_ends_in_disconnect_event() {
            use crate::events::SerialEvent;
            use crate::mock_serial::MockSerialPort;
            use std::sync::{Arc, Mutex};
            use std::time::Duration;

            let mut mock = MockSerialPort::new();
            mock.sticky_read_error = Some(std::io::ErrorKind::PermissionDenied);
            let port: Arc<Mutex<Box<dyn serialport::SerialPort>>> =
                Arc::new(Mutex::new(Box::new(mock)));
            let (tx, rx) = std::sync::mpsc::channel();
            let tx = Mutex::new(tx);
            let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
                if matches!(event, SerialEvent::Disconnect { .. }) {
                    let _ = tx.lock().unwrap().send(());
                }
                true
            });
            let hub = super::super::PortRxHub::start(port, "unplugged".into());
            hub.attach_watch_with(channel, 10, 64, false, None);
            rx.recv_timeout(Duration::from_secs(3))
                .expect("no Disconnect after persistent read errors");
            hub.stop();
        }

        #[test]
        fn eintr_is_benign() {
            let err = std::io::Error::new(std::io::ErrorKind::Interrupted, "EINTR");
            assert!(is_benign_read_error(&err));
        }

        #[test]
        fn read_timeout_is_benign_not_disconnect() {
            let err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
            assert!(is_benign_read_error(&err));
            assert!(!is_disconnect_read_error(&err));
        }

        #[test]
        fn broken_pipe_is_disconnect() {
            let err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "broken");
            assert!(!is_benign_read_error(&err));
            assert!(is_disconnect_read_error(&err));
        }

        #[test]
        fn permission_denied_is_neither_benign_nor_disconnect() {
            let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
            assert!(!is_benign_read_error(&err));
            assert!(!is_disconnect_read_error(&err));
        }
    }
}

use io_errors::{is_benign_read_error, is_disconnect_read_error};

use crate::cmux::CmuxSession;
use crate::events::SerialEvent;
use crate::hub::shared::{
    finish_drain, try_complete_drain, CoreWatchSlot, ExchangeWaiter, HubRoutingState, RxHubShared,
};
use serial_codec::framing::Framer;
use serialport::SerialPort;
use std::io::Read;
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

const POLL_TIMEOUT: Duration = Duration::from_millis(10);

/// One hub read.
enum PollRead {
    /// The hub was asked to stop.
    Stopped,
    /// Read timeout (or EINTR): no data yet.
    Idle,
    /// `Ok(n)`; `Data(0)` with a non-empty buffer is end of stream.
    Data(usize),
}

fn poll_read_port(
    port: &Arc<Mutex<Box<dyn SerialPort>>>,
    buf: &mut [u8],
    stop_rx: &Receiver<()>,
    timeout: Duration,
) -> std::io::Result<PollRead> {
    loop {
        if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
            return Ok(PollRead::Stopped);
        }
        let mut p = match port.try_lock() {
            Ok(g) => g,
            Err(_) => {
                thread::sleep(Duration::from_millis(1));
                continue;
            }
        };
        let _ = p.set_timeout(timeout);
        match p.read(buf) {
            Ok(n) => return Ok(PollRead::Data(n)),
            // Yield so hub_loop can complete drain idle/deadline and flush watch batches.
            Err(e) if is_benign_read_error(&e) => return Ok(PollRead::Idle),
            Err(e) => return Err(e),
        }
    }
}

/// `Ok(0)` reads in a row before the port is treated as gone. serialport reports a
/// read timeout as `TimedOut` and POLLHUP as `BrokenPipe`, so `Ok(0)` means poll said
/// "readable" and there was nothing: end of stream (a tty after hang-up / unplug).
/// TCP turns its first `Ok(0)` into `UnexpectedEof` itself (a closed socket).
const MAX_CONSECUTIVE_EOF_READS: u32 = 3;

/// The Android USB adapter returns `Ok(0)` on a read timeout, so `Ok(0)` is no EOF
/// signal there.
const EOF_MEANS_DISCONNECT: bool = !cfg!(target_os = "android");

/// Track one read for EOF: `true` once enough `Ok(0)` reads came in a row. An `Ok(0)`
/// that does not end the port waits like a read timeout (never spin on a dead fd).
fn note_eof(read: &PollRead, buf_len: usize, eof_reads: &mut u32) -> bool {
    match read {
        PollRead::Data(0) if buf_len > 0 && EOF_MEANS_DISCONNECT => {
            *eof_reads += 1;
            if *eof_reads >= MAX_CONSECUTIVE_EOF_READS {
                return true;
            }
            thread::sleep(POLL_TIMEOUT);
        }
        PollRead::Data(0) => thread::sleep(Duration::from_millis(1)),
        _ => *eof_reads = 0,
    }
    false
}

/// A real disconnect (not a close): fail waiters, send `Disconnect` once, run the hook.
fn report_disconnect(
    shared: &RxHubShared,
    path: &str,
    reason: &str,
    on_disconnect: &mut Option<DisconnectHook>,
) {
    shared.fail_all_waiters(reason);
    shared.emit_disconnect(path, reason);
    // Android: clear mobile registry + USB adapter (harness expects
    // inject_bulk_read_error → on_usb_error → registry drop).
    #[cfg(target_os = "android")]
    {
        crate::android::registry::on_usb_error(path, reason);
        let _ = crate::android::driver_host::global_host().close(Some(path));
    }
    if let Some(hook) = on_disconnect.take() {
        hook(reason);
    }
}

const EOF_REASON: &str = "Serial port disconnected: EOF";

/// Non-benign read errors in a row before the port is treated as gone. Windows reports
/// an unplugged adapter as PermissionDenied / Other, Unix sometimes as EIO, never as
/// BrokenPipe, so a persistent error is the only portable unplug signal.
const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;

fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
    shared.fail_all_waiters("port closed");
    shared.finish_watch_stream(routing);
    shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
}

/// Called once on the hub thread after a real disconnect (not on close), with the
/// reason sent in `Disconnect`. It must not join the hub.
pub(crate) type DisconnectHook = Box<dyn FnOnce(&str) + Send>;

/// Single RX consumer on the main serial fd (desktop).
pub struct PortRxHub {
    shared: Arc<RxHubShared>,
    stop_tx: Sender<()>,
    thread: Option<JoinHandle<()>>,
}

impl PortRxHub {
    pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
        Self::start_with(port, path, None, None)
    }

    /// [`Self::start`] with a hook the hub thread runs after a real disconnect.
    /// `first_watch` is attached before the first read, so it gets every byte and event.
    pub(crate) fn start_with(
        port: Arc<Mutex<Box<dyn SerialPort>>>,
        path: String,
        on_disconnect: Option<DisconnectHook>,
        first_watch: Option<CoreWatchSlot>,
    ) -> Self {
        let shared = Arc::new(RxHubShared::for_path(path.clone()));
        if let Some(slot) = first_watch {
            shared.attach_core_watch(slot);
        }
        let (stop_tx, stop_rx) = mpsc::channel();
        let shared_clone = shared.clone();
        let thread =
            thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx, on_disconnect));
        Self {
            shared,
            stop_tx,
            thread: Some(thread),
        }
    }

    pub fn shared(&self) -> Arc<RxHubShared> {
        self.shared.clone()
    }

    pub fn is_finished(&self) -> bool {
        self.thread
            .as_ref()
            .map(JoinHandle::is_finished)
            .unwrap_or(true)
    }

    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
    #[cfg(feature = "tauri")]
    pub fn attach_watch(
        &self,
        channel: tauri::ipc::Channel<SerialEvent>,
        batch_timeout_ms: u64,
        read_size: usize,
        route_urc: bool,
    ) {
        self.shared
            .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
    }

    pub fn attach_watch_with(
        &self,
        channel: crate::events::EventSink,
        batch_timeout_ms: u64,
        read_size: usize,
        route_urc: bool,
        framer: Option<Box<dyn Framer>>,
    ) {
        self.shared
            .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
    }

    pub fn detach_watch(&self) {
        self.shared.detach_watch();
    }

    pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
        self.shared.set_exchange_waiter(waiter);
    }

    pub fn clear_exchange_waiter(&self) {
        self.shared.clear_exchange_waiter();
    }

    pub fn cancel_active_exchange(&self) {
        self.shared.cancel_active_exchange();
    }

    pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
        self.shared.attach_cmux(session);
    }

    pub fn detach_cmux(&self) {
        self.shared.detach_cmux();
    }

    /// Soft-drain via the hub thread (single reader); URC lines are emitted on the watch channel.
    pub fn drain(
        &self,
        idle_ms: u64,
        max_ms: u64,
        cancel: Arc<AtomicBool>,
        solicited_prefixes: Vec<String>,
    ) -> Result<Vec<u8>, String> {
        self.shared
            .drain(idle_ms, max_ms, cancel, solicited_prefixes)
    }

    pub fn request_stop(&self) {
        let _ = self.stop_tx.send(());
    }

    /// Stop and join the hub thread (not when called from it, e.g. a watch sink
    /// closing its own port: then it only asks it to stop).
    pub fn stop(mut self) {
        let _ = self.stop_tx.send(());
        if let Some(h) = self.thread.take() {
            if h.thread().id() != thread::current().id() {
                let _ = h.join();
            }
        }
    }
}

impl crate::hub::handle::RxHubHandle for PortRxHub {
    fn shared(&self) -> Arc<RxHubShared> {
        self.shared()
    }
    fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
        self.set_exchange_waiter(waiter);
    }
    fn clear_exchange_waiter(&self) {
        self.clear_exchange_waiter();
    }
    fn cancel_active_exchange(&self) {
        self.cancel_active_exchange();
    }
    fn attach_watch_with(
        &self,
        channel: crate::events::EventSink,
        batch_timeout_ms: u64,
        read_size: usize,
        route_urc: bool,
        framer: Option<Box<dyn Framer>>,
    ) {
        self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
    }
    fn detach_watch(&self) {
        self.detach_watch();
    }
    fn attach_cmux(&self, session: Arc<CmuxSession>) {
        self.attach_cmux(session);
    }
    fn detach_cmux(&self) {
        self.detach_cmux();
    }
    fn shutdown_hub(&self) {
        self.request_stop();
    }
}

fn hub_loop(
    port: Arc<Mutex<Box<dyn SerialPort>>>,
    path: String,
    shared: Arc<RxHubShared>,
    stop_rx: Receiver<()>,
    mut on_disconnect: Option<DisconnectHook>,
) {
    let mut routing = HubRoutingState::new(path.clone());
    let mut read_size = 1024usize;
    let mut last_error_emit = Instant::now() - Duration::from_secs(1);
    let mut consecutive_errors = 0u32;
    let mut eof_reads = 0u32;

    loop {
        if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
            shutdown_hub_state(&shared, &mut routing);
            break;
        }

        if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
            try_complete_drain(&shared);
            if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
                continue;
            }

            let mut buf = vec![0u8; 1024];
            let read = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
                Ok(PollRead::Stopped) => {
                    shutdown_hub_state(&shared, &mut routing);
                    break;
                }
                Ok(read) => read,
                Err(e) => {
                    finish_drain(&shared, Err(format!("drain read failed: {}", e)));
                    continue;
                }
            };
            if note_eof(&read, buf.len(), &mut eof_reads) {
                if shared.is_closing() {
                    shutdown_hub_state(&shared, &mut routing);
                } else {
                    shared.flush_watch_now(&mut routing);
                    shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
                    report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
                }
                break;
            }
            let n = match read {
                PollRead::Data(n) => n,
                _ => 0,
            };

            if n > 0 {
                // feed_bytes retries drain then falls through to exchange/watch/idle
                // if reclaim won during poll_read_port — never drop the chunk.
                shared.feed_bytes(&buf[..n], &mut routing);
                shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
            }
            // Full tick (drain completion, read deadline, watch batch and parser timers):
            // a time-based parser frame must not wait for the drain to end.
            shared.tick(&path, &mut routing);
            shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
            continue;
        }

        // The read timeout doubles as the parser timer: wake by the framer deadline
        // (inter-byte timeout) so `tick` polls it on time, never spinning.
        let mut timeout = POLL_TIMEOUT;
        if let Some(size) = shared.read_size() {
            read_size = size;
        }
        if let Some(d) = shared.next_framer_deadline() {
            timeout = d
                .saturating_duration_since(Instant::now())
                .clamp(Duration::from_millis(1), POLL_TIMEOUT);
        }

        let mut buf = vec![0u8; read_size];
        let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);

        if read_result.is_ok() {
            consecutive_errors = 0;
        }
        if let Ok(read) = &read_result {
            if note_eof(read, buf.len(), &mut eof_reads) {
                shared.flush_watch_now(&mut routing);
                shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
                if shared.is_closing() {
                    // Intentional close racing the EOF: no `Disconnect`.
                    shutdown_hub_state(&shared, &mut routing);
                } else {
                    report_disconnect(&shared, &path, EOF_REASON, &mut on_disconnect);
                }
                break;
            }
        }
        match read_result {
            Ok(PollRead::Stopped) => {
                shutdown_hub_state(&shared, &mut routing);
                break;
            }
            Ok(PollRead::Data(n)) if n > 0 => {
                shared.feed_bytes(&buf[..n], &mut routing);
                shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
            }
            Ok(PollRead::Data(_)) => {}
            Ok(PollRead::Idle) => {
                thread::sleep(Duration::from_millis(1));
            }
            Err(e) => {
                consecutive_errors += 1;
                shared.flush_watch_now(&mut routing);
                shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
                if shared.is_closing() {
                    // Intentional close racing a read error: no `Disconnect`.
                    shutdown_hub_state(&shared, &mut routing);
                    break;
                }
                if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
                {
                    let reason = format!("Serial port disconnected: {}", e);
                    report_disconnect(&shared, &path, &reason, &mut on_disconnect);
                    break;
                }
                if last_error_emit.elapsed() >= Duration::from_secs(1) {
                    last_error_emit = Instant::now();
                    shared.emit(SerialEvent::Error {
                        path: path.clone(),
                        message: format!("Serial read error: {}", e),
                    });
                }
                thread::sleep(Duration::from_millis(50));
            }
        }

        shared.tick(&path, &mut routing);
        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
    }
}

#[cfg(all(test, unix, not(any(target_os = "android", target_os = "ios"))))]
mod tests {
    use super::*;
    use std::io::Write;

    /// The hub skipped `tick` while a drain was active, so an inter-byte-timeout frame
    /// waited for the whole drain window.
    #[test]
    fn parser_timer_fires_during_drain() {
        let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
        let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
        let hub = PortRxHub::start(port, "pty".into());
        let (tx, rx) = mpsc::channel();
        let tx = Mutex::new(tx);
        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
            if let SerialEvent::Data { data, .. } = event {
                let _ = tx.lock().unwrap().send(data);
            }
            true
        });
        let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(
            serde_json::json!({"type": "interByteTimeout", "interval": 150}),
        )
        .unwrap();
        hub.attach_watch_with(channel, 10_000, 64, false, Some(cfg.build().unwrap()));
        master.write_all(&[1, 2]).unwrap();
        thread::sleep(Duration::from_millis(50)); // bytes reach the parser
        let shared = hub.shared();
        let drainer = thread::spawn(move || {
            shared.drain(2_000, 3_000, Arc::new(AtomicBool::new(false)), vec![])
        });
        let frame = rx
            .recv_timeout(Duration::from_millis(1_000))
            .expect("parser frame held back by the drain");
        assert_eq!(frame, vec![1, 2]);
        assert!(!drainer.is_finished(), "drain should still be running");
        let _ = drainer.join();
        hub.stop();
    }
}