serialplugin-core 0.2.4

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
//! 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
        )
    }
}

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,
    PORT_CLOSED,
};
use crate::hub::stream::in_sink;
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, eof_reads: &mut u32) -> bool {
    match read {
        PollRead::Data(0) if 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. No
/// sink runs before everything that waits on the port or its CMUX channels has failed.
fn report_disconnect(
    shared: &RxHubShared,
    path: &str,
    reason: &str,
    on_disconnect: &mut Option<DisconnectHook>,
) {
    shared.fail_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_waiters(PORT_CLOSED);
    shared.finish_watch_stream(routing);
    shared.deliver_queued();
}

/// 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: Mutex<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: Mutex::new(Some(thread)),
        }
    }

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

    pub fn is_finished(&self) -> bool {
        crate::sync_util::lock_or_recover(&self.thread)
            .as_ref()
            .is_none_or(JoinHandle::is_finished)
    }

    /// 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 a sink, e.g. one closing its own
    /// port: then it only asks it to stop).
    pub fn stop(self) {
        self.stop_and_join();
    }

    /// [`Self::stop`] for a shared hub (an exchange in flight holds it too). No event
    /// reaches a sink after this returns (unless a sink calls it: it must not wait for
    /// another thread, which may be waiting for it).
    pub(crate) fn stop_and_join(&self) {
        let _ = self.stop_tx.send(());
        let thread = crate::sync_util::lock_or_recover(&self.thread).take();
        if let Some(h) = thread {
            if !in_sink() && h.thread().id() != thread::current().id() {
                let _ = h.join();
            }
        }
        self.shared.settle_events();
    }
}

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)));
                    shared.deliver_queued();
                    continue;
                }
            };
            if note_eof(&read, &mut eof_reads) {
                if shared.is_closing() {
                    shutdown_hub_state(&shared, &mut routing);
                } else {
                    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.deliver_queued();
            }
            // 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.deliver_queued();
            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.max(1); // 0 would never read again
        }
        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, &mut eof_reads) {
                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.deliver_queued();
            }
            // `Data(0)` that did not end the port: nothing to route.
            Ok(PollRead::Data(_)) => {}
            Ok(PollRead::Idle) => {
                thread::sleep(Duration::from_millis(1));
            }
            Err(e) => {
                consecutive_errors += 1;
                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;
                }
                shared.flush_watch_now(&mut routing);
                shared.deliver_queued();
                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.deliver_queued();
    }
}