serial_embedded_hal/
lib.rs

1extern crate embedded_hal as hal;
2extern crate nb;
3extern crate serial;
4
5use serial::prelude::*;
6use std::ffi::OsStr;
7use std::io::prelude::*;
8
9pub use serial::BaudRate;
10pub use serial::CharSize;
11pub use serial::FlowControl;
12pub use serial::Parity;
13pub use serial::PortSettings;
14pub use serial::StopBits;
15
16use std::sync::{Arc, Mutex};
17
18/// Newtype over [`serial-rs`](https://crates.io/crates/serial)'s serial port abstraction.
19pub struct Serial(Arc<Mutex<serial::SystemPort>>);
20
21pub struct Tx(Arc<Mutex<serial::SystemPort>>);
22
23pub struct Rx(Arc<Mutex<serial::SystemPort>>);
24
25impl Serial {
26    pub fn new<T: AsRef<OsStr> + ?Sized>(
27        port: &T,
28        settings: &serial::PortSettings,
29    ) -> serial::Result<Self> {
30        let mut port = serial::open(&port)?;
31        port.configure(settings)?;
32        Ok(Serial(Arc::new(Mutex::new(port))))
33    }
34
35    pub fn split(self) -> (Tx, Rx) {
36        (Tx(Arc::clone(&self.0)), Rx(Arc::clone(&self.0)))
37    }
38}
39
40impl hal::serial::Read<u8> for Rx {
41    type Error = serial::Error;
42
43    fn read(&mut self) -> nb::Result<u8, Self::Error> {
44        let mut buf: [u8; 1] = [0];
45        match (*self.0).lock().unwrap().read(&mut buf) {
46            Ok(_) => Ok(buf[0]),
47            Err(e) => match e.kind() {
48                std::io::ErrorKind::WouldBlock => Err(nb::Error::WouldBlock),
49                std::io::ErrorKind::TimedOut => Err(nb::Error::WouldBlock),
50                _ => Err(nb::Error::Other(serial::Error::new(
51                    serial::ErrorKind::Io(e.kind()),
52                    "bad read",
53                ))),
54            },
55        }
56    }
57}
58
59impl hal::serial::Write<u8> for Tx {
60    type Error = serial::Error;
61
62    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
63        match (*self.0).lock().unwrap().write(&[byte]) {
64            Ok(_) => Ok(()),
65            Err(e) => Err(nb::Error::Other(serial::Error::new(
66                serial::ErrorKind::Io(e.kind()),
67                "bad write",
68            ))),
69        }
70    }
71
72    fn flush(&mut self) -> nb::Result<(), Self::Error> {
73        match (*self.0).lock().unwrap().flush() {
74            Ok(_) => Ok(()),
75            Err(e) => Err(nb::Error::Other(serial::Error::new(
76                serial::ErrorKind::Io(e.kind()),
77                "bad flush",
78            ))),
79        }
80    }
81}