ublox_core/interface/
serial.rs

1use super::DeviceInterface;
2use crate::Error;
3use embedded_hal as hal;
4
5use shufflebuf::ShuffleBuf;
6
7/// This encapsulates the Serial UART peripheral
8/// and associated pins such as
9/// - DRDY: Data Ready: Sensor uses this to indicate it had data available for read
10pub struct SerialInterface<SER> {
11    /// the serial port to use when communicating
12    serial: SER,
13    shuffler: ShuffleBuf,
14}
15
16impl<SER, CommE> SerialInterface<SER>
17where
18    SER: hal::serial::Read<u8, Error = CommE>,
19{
20    pub fn new(serial_port: SER) -> Self {
21        Self {
22            serial: serial_port,
23            shuffler: ShuffleBuf::default(),
24        }
25    }
26}
27
28impl<SER, CommE> DeviceInterface for SerialInterface<SER>
29where
30    SER: hal::serial::Read<u8, Error = CommE>,
31{
32    type InterfaceError = Error<CommE>;
33
34    fn read(&mut self) -> Result<u8, Self::InterfaceError> {
35        let (count, byte) = self.shuffler.read_one();
36        if count > 0 {
37            return Ok(byte);
38        } else {
39            let mut block_byte = [0u8; 1];
40            //TODO in practice this hasn't failed yet, but we should handle the error
41            self.read_many(&mut block_byte)?;
42            Ok(block_byte[0])
43        }
44    }
45
46    fn fill(&mut self) -> usize {
47        let mut fetch_count = self.shuffler.vacant();
48        let mut err_count = 0;
49
50        while fetch_count > 0 {
51            let rc = self.serial.read();
52            match rc {
53                Ok(byte) => {
54                    err_count = 0; //reset
55                    self.shuffler.push_one(byte);
56                    fetch_count -= 1;
57                }
58                Err(nb::Error::WouldBlock) => {}
59                Err(nb::Error::Other(_)) => {
60                    // in practice this is returning Overrun a ton on stm32h7
61                    err_count += 1;
62                    if err_count > 100 {
63                        break;
64                    }
65                }
66            }
67        }
68        self.shuffler.available()
69    }
70
71    fn read_many(
72        &mut self,
73        buffer: &mut [u8],
74    ) -> Result<usize, Self::InterfaceError> {
75        let avail = self.shuffler.available();
76        if avail >= buffer.len() {
77            let final_read_count = self.shuffler.read_many(buffer);
78            return Ok(final_read_count);
79        }
80
81        return Ok(0);
82    }
83}