framed_serial/
serialwrap.rs

1use serial::SerialPort;
2use super::embedded_serial;
3use super::{std, Error};
4
5/// Implment the traits required for a `FramedConnection` based
6/// on a `serial::SerialPort`.
7///
8/// Note that the async processing of `FramedConnection` depends on
9/// a short timeout being set. At the time of writing, `serial::open()` returned
10/// a SerialPort with a default of 100 msec.
11pub struct SerialWrap<T>
12    where T: SerialPort,
13{
14    inner: T,
15}
16
17impl<T> SerialWrap<T>
18    where T: SerialPort,
19{
20    /// Constructor
21    pub fn new(port: T) -> SerialWrap<T> {
22        // do not block
23        SerialWrap {inner: port}
24    }
25}
26
27impl<T> embedded_serial::NonBlockingRx for SerialWrap<T>
28    where T: SerialPort,
29{
30    type Error=Error;
31    fn getc_try(&mut self) -> Result<Option<u8>, Self::Error> {
32        let mut buf: [u8;1] = [0];
33
34        match self.inner.read(&mut buf) {
35            Ok(1) => Ok(Some(buf[0])),
36            Ok(n_bytes) => return Err(Error::new(format!("no error, but {} bytes read.", n_bytes))),
37            Err(e) => {
38                match e.kind() {
39                    std::io::ErrorKind::TimedOut => {Ok(None)},
40                    _ => return Err(Error::new(format!("Can't read, err {:?}", e))),
41                }
42            },
43        }
44    }
45}
46
47impl<T> embedded_serial::NonBlockingTx for SerialWrap<T>
48    where T: SerialPort,
49{
50    type Error=Error;
51
52    /// Try and write a single octet to the port's transmitter.
53    /// Will return `Ok(None)` if the FIFO/buffer was full
54    /// and the octet couldn't be stored or `Ok(Some(ch))`
55    /// if it was stored OK.
56    ///
57    /// In some implementations, this can result in an Error.
58    /// If not, use `type Error = !`.
59    fn putc_try(&mut self, ch: u8) -> Result<Option<u8>, Self::Error> {
60        let buf: [u8; 1] = [ch];
61        match self.inner.write(&buf) {
62            Ok(0) => {
63                return Ok(None);
64            },
65            Ok(1) => {
66                return Ok(Some(ch));
67            },
68            Ok(_) => {
69                unreachable!();
70            },
71            Err(e) => {
72                return Err(Error::new(format!("write error {:?}",e)));
73            },
74        }
75    }
76}