1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use anyhow::Result;
use std::thread;
use std::time::Duration;

pub trait Connection {
    fn write(&mut self, command: &[u8]) -> Result<()>;
    fn read(&mut self) -> Result<Vec<u8>>;
    fn write_and_read(&mut self, command: &[u8]) -> Result<Vec<u8>>;
}

pub struct Serial {
    port: Box<dyn serialport::SerialPort>,
}

impl Serial {
    pub fn new(port: &str, baudrate: u32) -> Serial {
        let port = serialport::new(port, baudrate)
            .timeout(Duration::from_millis(10))
            .open()
            .expect("Failed to open port.");
        Serial { port }
    }
}

impl Connection for Serial {
    fn write(&mut self, command: &[u8]) -> Result<()> {
        self.port.write_all(command)?;
        thread::sleep(Duration::from_millis(50));
        Ok(())
    }
    fn read(&mut self) -> Result<Vec<u8>> {
        let mut data = Vec::<u8>::new();
        loop {
            let mut buf = vec![0u8; 1];
            match self.port.read_exact(buf.as_mut_slice()) {
                Ok(_t) => data.extend(buf),
                Err(_e) => break,
            }
        }
        Ok(data)
    }
    fn write_and_read(&mut self, command: &[u8]) -> Result<Vec<u8>> {
        self.write(command)?;
        let res = self.read()?;
        Ok(res)
    }
}