embedded_nano_mesh_linux_io/
lib.rs

1pub use embedded_io::{Read, ReadReady, Write};
2pub use serialport;
3pub use std::io::{Read as _, Write as _};
4
5pub struct LinuxIO {
6    serial: serialport::TTYPort,
7    inner_byte_cache: Option<u8>,
8}
9
10impl LinuxIO {
11    pub fn new(serial: serialport::TTYPort) -> LinuxIO {
12        LinuxIO {
13            serial,
14            inner_byte_cache: None,
15        }
16    }
17}
18
19impl embedded_io::ErrorType for LinuxIO {
20    type Error = core::convert::Infallible;
21}
22
23impl embedded_io::ReadReady for LinuxIO {
24    fn read_ready(&mut self) -> Result<bool, Self::Error> {
25        if self.inner_byte_cache.is_some() {
26            return Ok(true);
27        }
28
29        let mut read_buf = [0u8; 1];
30
31        match self.serial.read(&mut read_buf) {
32            Ok(0) | Err(_) => Ok(false),
33            Ok(_) => {
34                self.inner_byte_cache
35                    .replace(*read_buf.first().unwrap_or(&0));
36                Ok(true)
37            }
38        }
39    }
40}
41
42impl embedded_io::Read for LinuxIO {
43    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
44        let mut red_count = usize::default();
45
46        for read_buf_byte in buf.iter_mut() {
47            if let Some(byte) = self.inner_byte_cache.take() {
48                *read_buf_byte = byte;
49                red_count += 1;
50            } else {
51                match self.read_ready() {
52                    Ok(false) | Err(_) => break,
53                    Ok(true) => continue,
54                }
55            }
56        }
57
58        Ok(red_count)
59    }
60}
61
62impl embedded_io::Write for LinuxIO {
63    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
64        match self.serial.write(buf) {
65            Ok(_) => Ok(buf.len()),
66            _ => Ok(0),
67        }
68    }
69
70    fn flush(&mut self) -> Result<(), Self::Error> {
71        match self.serial.flush() {
72            Ok(_) => Ok(()),
73            _ => Ok(()),
74        }
75    }
76}
77
78impl ufmt::uWrite for LinuxIO {
79    type Error = core::convert::Infallible;
80    fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
81        let _ = self.serial.write_all(s.as_bytes());
82        Ok(())
83    }
84}