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 match self.stream.read(buf) {
156 Ok(0) => Err(io::Error::new(
158 io::ErrorKind::UnexpectedEof,
159 "TCP serial bridge closed the connection",
160 )),
161 Err(e) => Err(map_read_error(e)),
162 ok => ok,
163 }
164 }
165}
166
167impl Write for TcpSerialPort {
168 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
169 self.stream.write(buf)
170 }
171
172 fn flush(&mut self) -> io::Result<()> {
174 Ok(())
175 }
176}
177
178impl SerialPort for TcpSerialPort {
179 fn name(&self) -> Option<String> {
180 Some(self.path.clone())
181 }
182
183 fn baud_rate(&self) -> serialport::Result<u32> {
184 Ok(self.baud_rate)
185 }
186
187 fn data_bits(&self) -> serialport::Result<DataBits> {
188 Ok(self.data_bits)
189 }
190
191 fn flow_control(&self) -> serialport::Result<FlowControl> {
192 Ok(self.flow_control)
193 }
194
195 fn parity(&self) -> serialport::Result<Parity> {
196 Ok(self.parity)
197 }
198
199 fn stop_bits(&self) -> serialport::Result<StopBits> {
200 Ok(self.stop_bits)
201 }
202
203 fn timeout(&self) -> Duration {
204 self.timeout
205 }
206
207 fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
208 self.baud_rate = baud_rate;
209 Ok(())
210 }
211
212 fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
213 self.data_bits = data_bits;
214 Ok(())
215 }
216
217 fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
218 self.flow_control = flow_control;
219 Ok(())
220 }
221
222 fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
223 self.parity = parity;
224 Ok(())
225 }
226
227 fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
228 self.stop_bits = stop_bits;
229 Ok(())
230 }
231
232 fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
233 self.stream.set_read_timeout(socket_timeout(timeout))?;
234 self.stream.set_write_timeout(socket_timeout(timeout))?;
235 self.timeout = timeout;
236 Ok(())
237 }
238
239 fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
240 Ok(())
241 }
242
243 fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
244 Ok(())
245 }
246
247 fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
249 Ok(true)
250 }
251
252 fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
253 Ok(true)
254 }
255
256 fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
257 Ok(false)
258 }
259
260 fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
261 Ok(true)
262 }
263
264 fn bytes_to_read(&self) -> serialport::Result<u32> {
265 self.stream.set_nonblocking(true)?;
266 let mut buf = [0u8; 4096];
267 let pending = match self.stream.peek(&mut buf) {
268 Ok(n) => n as u32,
269 Err(e) => match e.kind() {
270 io::ErrorKind::WouldBlock => 0,
271 _ => {
272 let _ = self.stream.set_nonblocking(false);
273 return Err(e.into());
274 }
275 },
276 };
277 self.stream.set_nonblocking(false)?;
278 Ok(pending)
279 }
280
281 fn bytes_to_write(&self) -> serialport::Result<u32> {
282 Ok(0)
283 }
284
285 fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
286 if matches!(buffer_to_clear, ClearBuffer::Output) {
287 return Ok(());
288 }
289 self.stream.set_nonblocking(true)?;
291 let mut buf = [0u8; 4096];
292 let result = loop {
293 match (&self.stream).read(&mut buf) {
294 Ok(0) => break Ok(()),
295 Ok(_) => continue,
296 Err(e) => match e.kind() {
297 io::ErrorKind::WouldBlock => break Ok(()),
298 _ => break Err(e.into()),
299 },
300 }
301 };
302 self.stream.set_nonblocking(false)?;
303 result
304 }
305
306 fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
307 Ok(Box::new(Self {
308 stream: self.stream.try_clone()?,
309 path: self.path.clone(),
310 baud_rate: self.baud_rate,
311 data_bits: self.data_bits,
312 flow_control: self.flow_control,
313 parity: self.parity,
314 stop_bits: self.stop_bits,
315 timeout: self.timeout,
316 }))
317 }
318
319 fn set_break(&self) -> serialport::Result<()> {
320 Ok(())
321 }
322
323 fn clear_break(&self) -> serialport::Result<()> {
324 Ok(())
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331 use std::net::TcpListener;
332
333 fn connect(listener: &TcpListener) -> TcpSerialPort {
334 let path = format!("tcp://{}", listener.local_addr().unwrap());
335 TcpSerialPort::connect(
336 &path,
337 115_200,
338 DataBits::Eight,
339 FlowControl::None,
340 Parity::None,
341 StopBits::One,
342 Duration::from_millis(50),
343 )
344 .unwrap()
345 }
346
347 #[test]
348 fn keepalive_is_on_with_a_short_idle() {
349 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
350 let port = connect(&listener);
351 assert_eq!(
352 port.name(),
353 Some(format!("tcp://{}", listener.local_addr().unwrap()))
354 );
355 let sock = socket2::SockRef::from(&port.stream);
356 assert!(sock.keepalive().unwrap());
357 #[cfg(unix)]
358 {
359 assert_eq!(sock.tcp_keepalive_time().unwrap(), KEEPALIVE_IDLE);
360 #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
361 assert_eq!(sock.tcp_keepalive_interval().unwrap(), KEEPALIVE_INTERVAL);
362 }
363 let clone = port.try_clone().unwrap();
365 drop(clone);
366 }
367
368 #[test]
371 fn keepalive_timeout_reads_as_a_disconnect() {
372 use io::ErrorKind::*;
373 let timeout = map_read_error(io::Error::from(WouldBlock));
374 assert_eq!(timeout.kind(), TimedOut);
375 assert_eq!(
376 timeout.into_inner().unwrap().to_string(),
377 io::Error::from(WouldBlock).to_string()
378 );
379 #[cfg(unix)]
380 {
381 let dead = map_read_error(io::Error::from(TimedOut));
382 assert_eq!(dead.kind(), ConnectionAborted);
383 }
384 let reset = map_read_error(io::Error::from(ConnectionReset));
385 assert_eq!(reset.kind(), ConnectionReset);
386 assert!(
387 reset.get_ref().is_none(),
388 "an unmapped error is passed through as is"
389 );
390 for windows in [false, true] {
391 assert_eq!(read_error_kind(WouldBlock, None, windows), TimedOut);
392 assert_eq!(read_error_kind(Other, Some(WSAENETRESET), false), Other);
393 }
394 assert_eq!(read_error_kind(TimedOut, None, false), ConnectionAborted);
395 assert_eq!(read_error_kind(TimedOut, None, true), TimedOut);
396 assert_eq!(
397 read_error_kind(Other, Some(WSAENETRESET), true),
398 ConnectionReset
399 );
400 assert_eq!(read_error_kind(Other, Some(10053), true), Other);
401 assert_eq!(read_error_kind(Other, None, true), Other);
402 }
403
404 #[test]
405 fn socket_timeouts_are_never_zero() {
406 assert_eq!(
407 socket_timeout(Duration::ZERO),
408 Some(Duration::from_millis(1))
409 );
410 assert_eq!(
411 socket_timeout(Duration::from_millis(50)),
412 Some(Duration::from_millis(50))
413 );
414 }
415
416 #[cfg(not(target_os = "android"))]
418 #[test]
419 fn bridge_gone_ends_in_disconnect_event() {
420 use crate::events::{EventSink, SerialEvent};
421 use std::sync::{mpsc, Arc, Mutex};
422
423 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
424 let port = connect(&listener);
425 let (peer, _) = listener.accept().unwrap();
426 let (tx, rx) = mpsc::channel();
427 let tx = Mutex::new(tx);
428 let sink: EventSink = Arc::new(move |event: SerialEvent| {
429 if matches!(event, SerialEvent::Disconnect { .. }) {
430 let _ = tx.lock().unwrap().send(());
431 }
432 true
433 });
434 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(port)));
435 let hub = crate::hub::PortRxHub::start(port, "tcp://bridge".into());
436 hub.attach_watch_with(sink, 10, 64, false, None);
437 drop(peer);
438 rx.recv_timeout(Duration::from_secs(3))
439 .expect("no Disconnect after the bridge closed");
440 hub.stop();
441 }
442}