1use std::pin::Pin;
5use std::task::{Context, Poll};
6
7use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum FlowControl {
12 #[default]
14 None,
15 Hardware,
17 Software,
19}
20
21pub enum Port {
23 Serial(tokio_serial::SerialStream),
25 Tcp(tokio::net::TcpStream),
27}
28
29impl std::fmt::Debug for Port {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 Port::Serial(_) => f.write_str("Port::Serial"),
33 Port::Tcp(_) => f.write_str("Port::Tcp"),
34 }
35 }
36}
37
38pub async fn open(name: &str, baud: u32, flow: FlowControl) -> std::io::Result<Port> {
40 if let Some(addr) = name.strip_prefix("tcp://") {
41 let stream = tokio::net::TcpStream::connect(addr).await?;
42 stream.set_nodelay(true)?;
43 return Ok(Port::Tcp(stream));
44 }
45 use tokio_serial::SerialPortBuilderExt;
46 let flow = match flow {
47 FlowControl::None => tokio_serial::FlowControl::None,
48 FlowControl::Hardware => tokio_serial::FlowControl::Hardware,
49 FlowControl::Software => tokio_serial::FlowControl::Software,
50 };
51 let builder = tokio_serial::new(name, baud)
52 .data_bits(tokio_serial::DataBits::Eight)
53 .parity(tokio_serial::Parity::None)
54 .stop_bits(tokio_serial::StopBits::One)
55 .flow_control(flow);
56 let deadline = tokio::time::Instant::now() + BUSY_WAIT;
61 loop {
62 match builder.clone().open_native_async() {
63 Ok(stream) => return Ok(Port::Serial(stream)),
64 Err(e)
65 if e.kind == tokio_serial::ErrorKind::NoDevice
66 && tokio::time::Instant::now() < deadline =>
67 {
68 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
69 }
70 Err(e) => return Err(e.into()),
71 }
72 }
73}
74
75const BUSY_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
77
78impl AsyncRead for Port {
79 fn poll_read(
80 self: Pin<&mut Self>,
81 cx: &mut Context<'_>,
82 buf: &mut ReadBuf<'_>,
83 ) -> Poll<std::io::Result<()>> {
84 match self.get_mut() {
85 Port::Serial(s) => Pin::new(s).poll_read(cx, buf),
86 Port::Tcp(s) => Pin::new(s).poll_read(cx, buf),
87 }
88 }
89}
90
91impl AsyncWrite for Port {
92 fn poll_write(
93 self: Pin<&mut Self>,
94 cx: &mut Context<'_>,
95 buf: &[u8],
96 ) -> Poll<std::io::Result<usize>> {
97 match self.get_mut() {
98 Port::Serial(s) => Pin::new(s).poll_write(cx, buf),
99 Port::Tcp(s) => Pin::new(s).poll_write(cx, buf),
100 }
101 }
102 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
103 match self.get_mut() {
104 Port::Serial(s) => Pin::new(s).poll_flush(cx),
105 Port::Tcp(s) => Pin::new(s).poll_flush(cx),
106 }
107 }
108 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
109 match self.get_mut() {
110 Port::Serial(s) => Pin::new(s).poll_shutdown(cx),
111 Port::Tcp(s) => Pin::new(s).poll_shutdown(cx),
112 }
113 }
114}