Skip to main content

zwave_serial/
port.rs

1//! Opening the link to a controller: a local serial device, or a TCP socket
2//! for sticks shared over the network (ser2net, socat, a simulator).
3
4use tokio::io::{AsyncRead, AsyncWrite};
5
6/// A bidirectional byte stream to a controller.
7pub trait Port: AsyncRead + AsyncWrite + Send + Unpin + 'static {}
8impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> Port for T {}
9
10/// The Serial API's fixed line settings: 115200 baud, 8N1, no flow control.
11pub const BAUD_RATE: u32 = 115_200;
12
13/// Opens `path`: `tcp://host:port` for a network link, anything else as a
14/// local serial device.
15pub async fn open(path: &str) -> std::io::Result<Box<dyn Port>> {
16    if let Some(addr) = path.strip_prefix("tcp://") {
17        let s = tokio::net::TcpStream::connect(addr).await?;
18        s.set_nodelay(true)?;
19        return Ok(Box::new(s));
20    }
21    open_serial(path).await
22}
23
24/// How long [`open`] waits for a busy serial port to be released.
25#[cfg(feature = "serialport")]
26const BUSY_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
27
28/// A port its last user just closed stays locked until the kernel has
29/// finished closing it (the tty's close delay, half a second by default), so
30/// reopening at once (a restart) finds it busy. `NoDevice` is that busy lock;
31/// a missing device is `NotFound`, which fails at once.
32#[cfg(feature = "serialport")]
33async fn open_serial(path: &str) -> std::io::Result<Box<dyn Port>> {
34    use tokio_serial::SerialPortBuilderExt;
35    let builder = tokio_serial::new(path, BAUD_RATE)
36        .data_bits(tokio_serial::DataBits::Eight)
37        .parity(tokio_serial::Parity::None)
38        .stop_bits(tokio_serial::StopBits::One)
39        .flow_control(tokio_serial::FlowControl::None);
40    let deadline = tokio::time::Instant::now() + BUSY_WAIT;
41    loop {
42        match builder.clone().open_native_async() {
43            Ok(port) => return Ok(Box::new(port)),
44            Err(e)
45                if e.kind == tokio_serial::ErrorKind::NoDevice
46                    && tokio::time::Instant::now() < deadline =>
47            {
48                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
49            }
50            Err(e) => return Err(std::io::Error::other(e)),
51        }
52    }
53}
54
55#[cfg(not(feature = "serialport"))]
56async fn open_serial(path: &str) -> std::io::Result<Box<dyn Port>> {
57    Err(std::io::Error::new(
58        std::io::ErrorKind::Unsupported,
59        format!("{path}: built without serial port support; use tcp://"),
60    ))
61}