1#[cfg(target_os = "ios")]
15use crate::serialport;
16
17use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
18use std::io::{self, Read, Write};
19use std::net::{TcpStream, ToSocketAddrs};
20use std::time::Duration;
21
22pub const TCP_SCHEME: &str = "tcp://";
23
24pub fn tcp_address(path: &str) -> Option<&str> {
26 path.strip_prefix(TCP_SCHEME)
27}
28
29pub struct TcpSerialPort {
30 stream: TcpStream,
31 path: String,
32 baud_rate: u32,
33 data_bits: DataBits,
34 flow_control: FlowControl,
35 parity: Parity,
36 stop_bits: StopBits,
37 timeout: Duration,
38}
39
40const KEEPALIVE_IDLE: Duration = Duration::from_secs(10);
42#[allow(dead_code)] const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(5);
45#[allow(dead_code)] const KEEPALIVE_RETRIES: u32 = 3;
49
50fn enable_keepalive(stream: &TcpStream) -> io::Result<()> {
53 let ka = socket2::TcpKeepalive::new().with_time(KEEPALIVE_IDLE);
54 #[cfg(any(
55 target_os = "android",
56 target_os = "linux",
57 target_os = "macos",
58 target_os = "ios",
59 target_os = "windows"
60 ))]
61 let ka = ka.with_interval(KEEPALIVE_INTERVAL);
62 #[cfg(any(
63 target_os = "android",
64 target_os = "linux",
65 target_os = "macos",
66 target_os = "ios"
67 ))]
68 let ka = ka.with_retries(KEEPALIVE_RETRIES);
69 socket2::SockRef::from(stream).set_tcp_keepalive(&ka)
70}
71
72fn map_read_error(e: io::Error) -> io::Error {
75 let kind = read_error_kind(e.kind(), e.raw_os_error(), cfg!(windows));
76 if kind == e.kind() {
77 e
78 } else {
79 io::Error::new(kind, e)
80 }
81}
82
83const WSAENETRESET: i32 = 10052;
85
86fn read_error_kind(kind: io::ErrorKind, os_code: Option<i32>, windows: bool) -> io::ErrorKind {
89 match kind {
90 io::ErrorKind::WouldBlock => io::ErrorKind::TimedOut,
92 io::ErrorKind::TimedOut if !windows => io::ErrorKind::ConnectionAborted,
96 _ if windows && os_code == Some(WSAENETRESET) => io::ErrorKind::ConnectionReset,
97 other => other,
98 }
99}
100
101fn socket_timeout(t: Duration) -> Option<Duration> {
103 Some(t.max(Duration::from_millis(1)))
104}
105
106impl TcpSerialPort {
107 pub fn connect(
108 path: &str,
109 baud_rate: u32,
110 data_bits: DataBits,
111 flow_control: FlowControl,
112 parity: Parity,
113 stop_bits: StopBits,
114 timeout: Duration,
115 ) -> io::Result<Self> {
116 let addr = tcp_address(path)
117 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a tcp:// path"))?;
118 let mut last_err = io::Error::new(io::ErrorKind::NotFound, format!("{addr}: no address"));
119 let connect_timeout = timeout.max(Duration::from_secs(3));
121 for sock in addr.to_socket_addrs()? {
122 match TcpStream::connect_timeout(&sock, connect_timeout) {
123 Ok(stream) => {
124 stream.set_nodelay(true)?;
125 if let Err(e) = enable_keepalive(&stream) {
127 crate::log_warn!("{path}: TCP keepalive not set: {e}");
128 }
129 stream.set_read_timeout(socket_timeout(timeout))?;
130 stream.set_write_timeout(socket_timeout(timeout))?;
131 return Ok(Self {
132 stream,
133 path: path.to_string(),
134 baud_rate,
135 data_bits,
136 flow_control,
137 parity,
138 stop_bits,
139 timeout,
140 });
141 }
142 Err(e) => last_err = e,
143 }
144 }
145 Err(last_err)
146 }
147}
148
149impl Read for TcpSerialPort {
150 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
151 if buf.is_empty() {
153 return Ok(0);
154 }
155 #[cfg(windows)]
159 self.stream.peek(&mut [0]).map_err(map_read_error)?;
160 match self.stream.read(buf) {
161 Ok(0) => Err(io::Error::new(
163 io::ErrorKind::UnexpectedEof,
164 "TCP serial bridge closed the connection",
165 )),
166 Err(e) => Err(map_read_error(e)),
167 ok => ok,
168 }
169 }
170}
171
172impl Write for TcpSerialPort {
173 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
174 self.stream.write(buf)
175 }
176
177 fn flush(&mut self) -> io::Result<()> {
179 Ok(())
180 }
181}
182
183impl SerialPort for TcpSerialPort {
184 fn name(&self) -> Option<String> {
185 Some(self.path.clone())
186 }
187
188 fn baud_rate(&self) -> serialport::Result<u32> {
189 Ok(self.baud_rate)
190 }
191
192 fn data_bits(&self) -> serialport::Result<DataBits> {
193 Ok(self.data_bits)
194 }
195
196 fn flow_control(&self) -> serialport::Result<FlowControl> {
197 Ok(self.flow_control)
198 }
199
200 fn parity(&self) -> serialport::Result<Parity> {
201 Ok(self.parity)
202 }
203
204 fn stop_bits(&self) -> serialport::Result<StopBits> {
205 Ok(self.stop_bits)
206 }
207
208 fn timeout(&self) -> Duration {
209 self.timeout
210 }
211
212 fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
213 self.baud_rate = baud_rate;
214 Ok(())
215 }
216
217 fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
218 self.data_bits = data_bits;
219 Ok(())
220 }
221
222 fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
223 self.flow_control = flow_control;
224 Ok(())
225 }
226
227 fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
228 self.parity = parity;
229 Ok(())
230 }
231
232 fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
233 self.stop_bits = stop_bits;
234 Ok(())
235 }
236
237 fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
238 self.stream.set_read_timeout(socket_timeout(timeout))?;
239 self.stream.set_write_timeout(socket_timeout(timeout))?;
240 self.timeout = timeout;
241 Ok(())
242 }
243
244 fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
245 Ok(())
246 }
247
248 fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
249 Ok(())
250 }
251
252 fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
254 Ok(true)
255 }
256
257 fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
258 Ok(true)
259 }
260
261 fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
262 Ok(false)
263 }
264
265 fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
266 Ok(true)
267 }
268
269 fn bytes_to_read(&self) -> serialport::Result<u32> {
270 self.stream.set_nonblocking(true)?;
271 let mut buf = [0u8; 4096];
272 let pending = match self.stream.peek(&mut buf) {
273 Ok(n) => n as u32,
274 Err(e) => match e.kind() {
275 io::ErrorKind::WouldBlock => 0,
276 _ => {
277 let _ = self.stream.set_nonblocking(false);
278 return Err(e.into());
279 }
280 },
281 };
282 self.stream.set_nonblocking(false)?;
283 Ok(pending)
284 }
285
286 fn bytes_to_write(&self) -> serialport::Result<u32> {
287 Ok(0)
288 }
289
290 fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
291 if matches!(buffer_to_clear, ClearBuffer::Output) {
292 return Ok(());
293 }
294 self.stream.set_nonblocking(true)?;
296 let mut buf = [0u8; 4096];
297 let result = loop {
298 match (&self.stream).read(&mut buf) {
299 Ok(0) => break Ok(()),
300 Ok(_) => continue,
301 Err(e) => match e.kind() {
302 io::ErrorKind::WouldBlock => break Ok(()),
303 _ => break Err(e.into()),
304 },
305 }
306 };
307 self.stream.set_nonblocking(false)?;
308 result
309 }
310
311 fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
312 Ok(Box::new(Self {
313 stream: self.stream.try_clone()?,
314 path: self.path.clone(),
315 baud_rate: self.baud_rate,
316 data_bits: self.data_bits,
317 flow_control: self.flow_control,
318 parity: self.parity,
319 stop_bits: self.stop_bits,
320 timeout: self.timeout,
321 }))
322 }
323
324 fn set_break(&self) -> serialport::Result<()> {
325 Ok(())
326 }
327
328 fn clear_break(&self) -> serialport::Result<()> {
329 Ok(())
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
337 use std::net::TcpListener;
338
339 fn connect(listener: &TcpListener) -> TcpSerialPort {
340 let path = format!("tcp://{}", listener.local_addr().unwrap());
341 TcpSerialPort::connect(
342 &path,
343 115_200,
344 DataBits::Eight,
345 FlowControl::None,
346 Parity::None,
347 StopBits::One,
348 Duration::from_millis(50),
349 )
350 .unwrap()
351 }
352
353 #[test]
354 fn keepalive_is_on_with_a_short_idle() {
355 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
356 let port = connect(&listener);
357 assert_eq!(
358 port.name(),
359 Some(format!("tcp://{}", listener.local_addr().unwrap()))
360 );
361 let sock = socket2::SockRef::from(&port.stream);
362 assert!(sock.keepalive().unwrap());
363 #[cfg(unix)]
364 {
365 assert_eq!(sock.tcp_keepalive_time().unwrap(), KEEPALIVE_IDLE);
366 #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
367 assert_eq!(sock.tcp_keepalive_interval().unwrap(), KEEPALIVE_INTERVAL);
368 }
369 let clone = port.try_clone().unwrap();
371 drop(clone);
372 }
373
374 #[test]
377 fn keepalive_timeout_reads_as_a_disconnect() {
378 use io::ErrorKind::*;
379 let timeout = map_read_error(io::Error::from(WouldBlock));
380 assert_eq!(timeout.kind(), TimedOut);
381 assert_eq!(
382 timeout.into_inner().unwrap().to_string(),
383 io::Error::from(WouldBlock).to_string()
384 );
385 #[cfg(unix)]
386 {
387 let dead = map_read_error(io::Error::from(TimedOut));
388 assert_eq!(dead.kind(), ConnectionAborted);
389 }
390 let reset = map_read_error(io::Error::from(ConnectionReset));
391 assert_eq!(reset.kind(), ConnectionReset);
392 assert!(
393 reset.get_ref().is_none(),
394 "an unmapped error is passed through as is"
395 );
396 for windows in [false, true] {
397 assert_eq!(read_error_kind(WouldBlock, None, windows), TimedOut);
398 assert_eq!(read_error_kind(Other, Some(WSAENETRESET), false), Other);
399 }
400 assert_eq!(read_error_kind(TimedOut, None, false), ConnectionAborted);
401 assert_eq!(read_error_kind(TimedOut, None, true), TimedOut);
402 assert_eq!(
403 read_error_kind(Other, Some(WSAENETRESET), true),
404 ConnectionReset
405 );
406 assert_eq!(read_error_kind(Other, Some(10053), true), Other);
407 assert_eq!(read_error_kind(Other, None, true), Other);
408 }
409}