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
//! Serial-over-TCP transport: `tcp://host:port`.
//!
//! Talks raw bytes to a TCP serial bridge (ser2net in raw mode, ESP-Link, Moxa/USR
//! device servers, `socat TCP-LISTEN:… /dev/ttyUSB0`). Works on every platform,
//! including iOS, which has no local serial API. Line settings (baud, parity, …) and
//! modem lines are stored but not sent: a raw bridge has its own port settings.
//!
//! TCP keepalive is on with a short idle time, so a bridge that vanished without a FIN
//! (power cut, Wi-Fi drop) fails the next read within about
//! `KEEPALIVE_IDLE + KEEPALIVE_RETRIES * KEEPALIVE_INTERVAL` and the hub reports
//! `Disconnect`, instead of the port timing out quietly forever.
// ponytail: raw TCP only; add RFC 2217 (telnet COM-PORT-OPTION) if remote line
// control is needed.
#[cfg(target_os = "ios")]
use crate::serialport;

use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
use std::io::{self, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;

pub const TCP_SCHEME: &str = "tcp://";

/// `tcp://host:port` → `host:port`, or `None` for an ordinary device path.
pub fn tcp_address(path: &str) -> Option<&str> {
    path.strip_prefix(TCP_SCHEME)
}

pub struct TcpSerialPort {
    stream: TcpStream,
    path: String,
    baud_rate: u32,
    data_bits: DataBits,
    flow_control: FlowControl,
    parity: Parity,
    stop_bits: StopBits,
    timeout: Duration,
}

/// Idle time before the first keepalive probe.
const KEEPALIVE_IDLE: Duration = Duration::from_secs(10);
/// Time between unanswered probes (whole seconds: most stacks round down).
#[allow(dead_code)] // not settable on every stack
const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(5);
/// Unanswered probes before the stack drops the connection (not set on Windows,
/// where it stays at the system's 10).
#[allow(dead_code)] // not settable on every stack
const KEEPALIVE_RETRIES: u32 = 3;

// ponytail: keepalive only covers an idle link; a half-open link with unsent data
// waits for the TCP retransmit timeout (TCP_USER_TIMEOUT on Linux) if that matters.
fn enable_keepalive(stream: &TcpStream) -> io::Result<()> {
    let ka = socket2::TcpKeepalive::new().with_time(KEEPALIVE_IDLE);
    #[cfg(any(
        target_os = "android",
        target_os = "linux",
        target_os = "macos",
        target_os = "ios",
        target_os = "windows"
    ))]
    let ka = ka.with_interval(KEEPALIVE_INTERVAL);
    #[cfg(any(
        target_os = "android",
        target_os = "linux",
        target_os = "macos",
        target_os = "ios"
    ))]
    let ka = ka.with_retries(KEEPALIVE_RETRIES);
    socket2::SockRef::from(stream).set_tcp_keepalive(&ka)
}

/// Read errors as the hub expects them: a read timeout is `TimedOut` (benign), a
/// dead connection is a disconnect kind.
fn map_read_error(e: io::Error) -> io::Error {
    let kind = read_error_kind(e.kind(), e.raw_os_error(), cfg!(windows));
    if kind == e.kind() {
        e
    } else {
        io::Error::new(kind, e)
    }
}

/// WSAENETRESET: Windows reports failed keepalive probes with it.
const WSAENETRESET: i32 = 10052;

/// The kind [`map_read_error`] gives a socket read error (`windows`: the platform's
/// codes; a parameter so both mappings are tested on every host).
fn read_error_kind(kind: io::ErrorKind, os_code: Option<i32>, windows: bool) -> io::ErrorKind {
    match kind {
        // Unix reports a read timeout as WouldBlock; serial callers expect TimedOut.
        io::ErrorKind::WouldBlock => io::ErrorKind::TimedOut,
        // Unix: SO_RCVTIMEO gives EAGAIN, so ETIMEDOUT here is failed keepalive probes.
        // (Windows uses WSAETIMEDOUT for both; it reports a keepalive drop as
        // WSAENETRESET below.)
        io::ErrorKind::TimedOut if !windows => io::ErrorKind::ConnectionAborted,
        _ if windows && os_code == Some(WSAENETRESET) => io::ErrorKind::ConnectionReset,
        other => other,
    }
}

/// Socket timeouts must be non-zero.
fn socket_timeout(t: Duration) -> Option<Duration> {
    Some(t.max(Duration::from_millis(1)))
}

impl TcpSerialPort {
    pub fn connect(
        path: &str,
        baud_rate: u32,
        data_bits: DataBits,
        flow_control: FlowControl,
        parity: Parity,
        stop_bits: StopBits,
        timeout: Duration,
    ) -> io::Result<Self> {
        let addr = tcp_address(path)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a tcp:// path"))?;
        let mut last_err = io::Error::new(io::ErrorKind::NotFound, format!("{addr}: no address"));
        // Connecting is not bounded by the (short) read timeout: allow a few seconds.
        let connect_timeout = timeout.max(Duration::from_secs(3));
        for sock in addr.to_socket_addrs()? {
            match TcpStream::connect_timeout(&sock, connect_timeout) {
                Ok(stream) => {
                    stream.set_nodelay(true)?;
                    // Best effort: a stack that rejects an option still connects.
                    if let Err(e) = enable_keepalive(&stream) {
                        crate::log_warn!("{path}: TCP keepalive not set: {e}");
                    }
                    stream.set_read_timeout(socket_timeout(timeout))?;
                    stream.set_write_timeout(socket_timeout(timeout))?;
                    return Ok(Self {
                        stream,
                        path: path.to_string(),
                        baud_rate,
                        data_bits,
                        flow_control,
                        parity,
                        stop_bits,
                        timeout,
                    });
                }
                Err(e) => last_err = e,
            }
        }
        Err(last_err)
    }
}

impl Read for TcpSerialPort {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        // Windows' recv into an empty buffer waits for data (or the timeout); unix returns 0.
        if buf.is_empty() {
            return Ok(0);
        }
        // A recv that times out on Windows may take bytes with it (about one in 100 000
        // timeouts with plain std, and the hub's reads time out all the time). A peek takes
        // none, and after it the read has its bytes.
        #[cfg(windows)]
        self.stream.peek(&mut [0]).map_err(map_read_error)?;
        match self.stream.read(buf) {
            // A closed socket is an unplugged device, not an empty read.
            Ok(0) => Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "TCP serial bridge closed the connection",
            )),
            Err(e) => Err(map_read_error(e)),
            ok => ok,
        }
    }
}

impl Write for TcpSerialPort {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.stream.write(buf)
    }

    // A TcpStream has no user-space write buffer (its `flush` does nothing).
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl SerialPort for TcpSerialPort {
    fn name(&self) -> Option<String> {
        Some(self.path.clone())
    }

    fn baud_rate(&self) -> serialport::Result<u32> {
        Ok(self.baud_rate)
    }

    fn data_bits(&self) -> serialport::Result<DataBits> {
        Ok(self.data_bits)
    }

    fn flow_control(&self) -> serialport::Result<FlowControl> {
        Ok(self.flow_control)
    }

    fn parity(&self) -> serialport::Result<Parity> {
        Ok(self.parity)
    }

    fn stop_bits(&self) -> serialport::Result<StopBits> {
        Ok(self.stop_bits)
    }

    fn timeout(&self) -> Duration {
        self.timeout
    }

    fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
        self.baud_rate = baud_rate;
        Ok(())
    }

    fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
        self.data_bits = data_bits;
        Ok(())
    }

    fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
        self.flow_control = flow_control;
        Ok(())
    }

    fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
        self.parity = parity;
        Ok(())
    }

    fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
        self.stop_bits = stop_bits;
        Ok(())
    }

    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
        self.stream.set_read_timeout(socket_timeout(timeout))?;
        self.stream.set_write_timeout(socket_timeout(timeout))?;
        self.timeout = timeout;
        Ok(())
    }

    fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
        Ok(())
    }

    fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
        Ok(())
    }

    // A connected raw bridge behaves like a cable with the lines asserted.
    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
        Ok(false)
    }

    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn bytes_to_read(&self) -> serialport::Result<u32> {
        self.stream.set_nonblocking(true)?;
        let mut buf = [0u8; 4096];
        let pending = match self.stream.peek(&mut buf) {
            Ok(n) => n as u32,
            Err(e) => match e.kind() {
                io::ErrorKind::WouldBlock => 0,
                _ => {
                    let _ = self.stream.set_nonblocking(false);
                    return Err(e.into());
                }
            },
        };
        self.stream.set_nonblocking(false)?;
        Ok(pending)
    }

    fn bytes_to_write(&self) -> serialport::Result<u32> {
        Ok(0)
    }

    fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
        if matches!(buffer_to_clear, ClearBuffer::Output) {
            return Ok(());
        }
        // Drop whatever already arrived, without waiting for more.
        self.stream.set_nonblocking(true)?;
        let mut buf = [0u8; 4096];
        let result = loop {
            match (&self.stream).read(&mut buf) {
                Ok(0) => break Ok(()),
                Ok(_) => continue,
                Err(e) => match e.kind() {
                    io::ErrorKind::WouldBlock => break Ok(()),
                    _ => break Err(e.into()),
                },
            }
        };
        self.stream.set_nonblocking(false)?;
        result
    }

    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
        Ok(Box::new(Self {
            stream: self.stream.try_clone()?,
            path: self.path.clone(),
            baud_rate: self.baud_rate,
            data_bits: self.data_bits,
            flow_control: self.flow_control,
            parity: self.parity,
            stop_bits: self.stop_bits,
            timeout: self.timeout,
        }))
    }

    fn set_break(&self) -> serialport::Result<()> {
        Ok(())
    }

    fn clear_break(&self) -> serialport::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    //! In `src/`: the socket is private, and a dead link takes the keepalive minutes.
    use super::*;
    use std::net::TcpListener;

    fn connect(listener: &TcpListener) -> TcpSerialPort {
        let path = format!("tcp://{}", listener.local_addr().unwrap());
        TcpSerialPort::connect(
            &path,
            115_200,
            DataBits::Eight,
            FlowControl::None,
            Parity::None,
            StopBits::One,
            Duration::from_millis(50),
        )
        .unwrap()
    }

    #[test]
    fn keepalive_is_on_with_a_short_idle() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = connect(&listener);
        assert_eq!(
            port.name(),
            Some(format!("tcp://{}", listener.local_addr().unwrap()))
        );
        let sock = socket2::SockRef::from(&port.stream);
        assert!(sock.keepalive().unwrap());
        #[cfg(unix)]
        {
            assert_eq!(sock.tcp_keepalive_time().unwrap(), KEEPALIVE_IDLE);
            #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
            assert_eq!(sock.tcp_keepalive_interval().unwrap(), KEEPALIVE_INTERVAL);
        }
        // A clone shares the socket, so it keeps the options.
        let clone = port.try_clone().unwrap();
        drop(clone);
    }

    /// Unix reports a read timeout as WouldBlock; a dead keepalive is ETIMEDOUT there
    /// and WSAENETRESET on Windows.
    #[test]
    fn keepalive_timeout_reads_as_a_disconnect() {
        use io::ErrorKind::*;
        let timeout = map_read_error(io::Error::from(WouldBlock));
        assert_eq!(timeout.kind(), TimedOut);
        assert_eq!(
            timeout.into_inner().unwrap().to_string(),
            io::Error::from(WouldBlock).to_string()
        );
        #[cfg(unix)]
        {
            let dead = map_read_error(io::Error::from(TimedOut));
            assert_eq!(dead.kind(), ConnectionAborted);
        }
        let reset = map_read_error(io::Error::from(ConnectionReset));
        assert_eq!(reset.kind(), ConnectionReset);
        assert!(
            reset.get_ref().is_none(),
            "an unmapped error is passed through as is"
        );
        for windows in [false, true] {
            assert_eq!(read_error_kind(WouldBlock, None, windows), TimedOut);
            assert_eq!(read_error_kind(Other, Some(WSAENETRESET), false), Other);
        }
        assert_eq!(read_error_kind(TimedOut, None, false), ConnectionAborted);
        assert_eq!(read_error_kind(TimedOut, None, true), TimedOut);
        assert_eq!(
            read_error_kind(Other, Some(WSAENETRESET), true),
            ConnectionReset
        );
        assert_eq!(read_error_kind(Other, Some(10053), true), Other);
        assert_eq!(read_error_kind(Other, None, true), Other);
    }
}