Skip to main content

zigbee_host/
port.rs

1//! Open a coordinator's port by name: a serial device, or `tcp://host:port`
2//! for network-attached coordinators and the simulator.
3
4use std::pin::Pin;
5use std::task::{Context, Poll};
6
7use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
8
9/// Serial flow control.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum FlowControl {
12    /// None (most USB coordinators with EmberZNet's default firmware).
13    #[default]
14    None,
15    /// RTS/CTS hardware flow control.
16    Hardware,
17    /// XON/XOFF software flow control.
18    Software,
19}
20
21/// An open coordinator port.
22pub enum Port {
23    /// A serial device.
24    Serial(tokio_serial::SerialStream),
25    /// A TCP connection.
26    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
38/// Open `name`: `tcp://host:port`, or a serial device path at `baud`.
39pub 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    // A port its last user just closed stays locked until the kernel has
57    // finished closing it (the tty's close delay, half a second by default),
58    // so reopening at once (the next family in a probe, a restart) finds it
59    // busy. `NoDevice` is that busy lock; a missing device is `NotFound`.
60    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
75/// How long [`open`] waits for a busy serial port to be released.
76const 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}