Skip to main content

serialplugin_core/port/
tcp.rs

1//! Serial-over-TCP transport: `tcp://host:port`.
2//!
3//! Talks raw bytes to a TCP serial bridge (ser2net in raw mode, ESP-Link, Moxa/USR
4//! device servers, `socat TCP-LISTEN:… /dev/ttyUSB0`). Works on every platform,
5//! including iOS, which has no local serial API. Line settings (baud, parity, …) and
6//! modem lines are stored but not sent: a raw bridge has its own port settings.
7// ponytail: raw TCP only; add RFC 2217 (telnet COM-PORT-OPTION) if remote line
8// control is needed.
9#[cfg(target_os = "ios")]
10use crate::serialport;
11
12use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
13use std::io::{self, Read, Write};
14use std::net::{TcpStream, ToSocketAddrs};
15use std::time::Duration;
16
17pub const TCP_SCHEME: &str = "tcp://";
18
19/// `tcp://host:port` → `host:port`, or `None` for an ordinary device path.
20pub fn tcp_address(path: &str) -> Option<&str> {
21    path.strip_prefix(TCP_SCHEME)
22}
23
24pub struct TcpSerialPort {
25    stream: TcpStream,
26    path: String,
27    baud_rate: u32,
28    data_bits: DataBits,
29    flow_control: FlowControl,
30    parity: Parity,
31    stop_bits: StopBits,
32    timeout: Duration,
33}
34
35/// Socket timeouts must be non-zero.
36fn socket_timeout(t: Duration) -> Option<Duration> {
37    Some(t.max(Duration::from_millis(1)))
38}
39
40impl TcpSerialPort {
41    pub fn connect(
42        path: &str,
43        baud_rate: u32,
44        data_bits: DataBits,
45        flow_control: FlowControl,
46        parity: Parity,
47        stop_bits: StopBits,
48        timeout: Duration,
49    ) -> io::Result<Self> {
50        let addr = tcp_address(path)
51            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a tcp:// path"))?;
52        let mut last_err = io::Error::new(io::ErrorKind::NotFound, format!("{addr}: no address"));
53        // Connecting is not bounded by the (short) read timeout: allow a few seconds.
54        let connect_timeout = timeout.max(Duration::from_secs(3));
55        for sock in addr.to_socket_addrs()? {
56            match TcpStream::connect_timeout(&sock, connect_timeout) {
57                Ok(stream) => {
58                    stream.set_nodelay(true)?;
59                    stream.set_read_timeout(socket_timeout(timeout))?;
60                    stream.set_write_timeout(socket_timeout(timeout))?;
61                    return Ok(Self {
62                        stream,
63                        path: path.to_string(),
64                        baud_rate,
65                        data_bits,
66                        flow_control,
67                        parity,
68                        stop_bits,
69                        timeout,
70                    });
71                }
72                Err(e) => last_err = e,
73            }
74        }
75        Err(last_err)
76    }
77}
78
79impl Read for TcpSerialPort {
80    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
81        match self.stream.read(buf) {
82            // A closed socket is an unplugged device, not an empty read.
83            Ok(0) if !buf.is_empty() => Err(io::Error::new(
84                io::ErrorKind::UnexpectedEof,
85                "TCP serial bridge closed the connection",
86            )),
87            // Unix reports a read timeout as WouldBlock; serial callers expect TimedOut.
88            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
89                Err(io::Error::new(io::ErrorKind::TimedOut, e))
90            }
91            other => other,
92        }
93    }
94}
95
96impl Write for TcpSerialPort {
97    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
98        self.stream.write(buf)
99    }
100
101    fn flush(&mut self) -> io::Result<()> {
102        self.stream.flush()
103    }
104}
105
106impl SerialPort for TcpSerialPort {
107    fn name(&self) -> Option<String> {
108        Some(self.path.clone())
109    }
110
111    fn baud_rate(&self) -> serialport::Result<u32> {
112        Ok(self.baud_rate)
113    }
114
115    fn data_bits(&self) -> serialport::Result<DataBits> {
116        Ok(self.data_bits)
117    }
118
119    fn flow_control(&self) -> serialport::Result<FlowControl> {
120        Ok(self.flow_control)
121    }
122
123    fn parity(&self) -> serialport::Result<Parity> {
124        Ok(self.parity)
125    }
126
127    fn stop_bits(&self) -> serialport::Result<StopBits> {
128        Ok(self.stop_bits)
129    }
130
131    fn timeout(&self) -> Duration {
132        self.timeout
133    }
134
135    fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
136        self.baud_rate = baud_rate;
137        Ok(())
138    }
139
140    fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
141        self.data_bits = data_bits;
142        Ok(())
143    }
144
145    fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
146        self.flow_control = flow_control;
147        Ok(())
148    }
149
150    fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
151        self.parity = parity;
152        Ok(())
153    }
154
155    fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
156        self.stop_bits = stop_bits;
157        Ok(())
158    }
159
160    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
161        self.stream.set_read_timeout(socket_timeout(timeout))?;
162        self.stream.set_write_timeout(socket_timeout(timeout))?;
163        self.timeout = timeout;
164        Ok(())
165    }
166
167    fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
168        Ok(())
169    }
170
171    fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
172        Ok(())
173    }
174
175    // A connected raw bridge behaves like a cable with the lines asserted.
176    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
177        Ok(true)
178    }
179
180    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
181        Ok(true)
182    }
183
184    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
185        Ok(false)
186    }
187
188    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
189        Ok(true)
190    }
191
192    fn bytes_to_read(&self) -> serialport::Result<u32> {
193        self.stream.set_nonblocking(true)?;
194        let mut buf = [0u8; 4096];
195        let pending = match self.stream.peek(&mut buf) {
196            Ok(n) => n as u32,
197            Err(e) if e.kind() == io::ErrorKind::WouldBlock => 0,
198            Err(e) => {
199                let _ = self.stream.set_nonblocking(false);
200                return Err(e.into());
201            }
202        };
203        self.stream.set_nonblocking(false)?;
204        Ok(pending)
205    }
206
207    fn bytes_to_write(&self) -> serialport::Result<u32> {
208        Ok(0)
209    }
210
211    fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
212        if matches!(buffer_to_clear, ClearBuffer::Output) {
213            return Ok(());
214        }
215        // Drop whatever already arrived, without waiting for more.
216        self.stream.set_nonblocking(true)?;
217        let mut buf = [0u8; 4096];
218        let result = loop {
219            match (&self.stream).read(&mut buf) {
220                Ok(0) => break Ok(()),
221                Ok(_) => continue,
222                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break Ok(()),
223                Err(e) => break Err(e.into()),
224            }
225        };
226        self.stream.set_nonblocking(false)?;
227        result
228    }
229
230    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
231        Ok(Box::new(Self {
232            stream: self.stream.try_clone()?,
233            path: self.path.clone(),
234            baud_rate: self.baud_rate,
235            data_bits: self.data_bits,
236            flow_control: self.flow_control,
237            parity: self.parity,
238            stop_bits: self.stop_bits,
239            timeout: self.timeout,
240        }))
241    }
242
243    fn set_break(&self) -> serialport::Result<()> {
244        Ok(())
245    }
246
247    fn clear_break(&self) -> serialport::Result<()> {
248        Ok(())
249    }
250}