match payload v.s. sent bytes length in Serial::send_bytes

This commit is contained in:
Vladan Popovic 2022-07-20 12:20:17 +02:00
parent a01b6d3a7b
commit db3cd1548e

View file

@ -8,7 +8,7 @@ use esp_idf_hal::serial::{self, Rx, Tx};
#[derive(Debug)] #[derive(Debug)]
pub enum SerialError { pub enum SerialError {
ReadError, ReadError,
WriteError(String), WriteError,
TimeoutError, TimeoutError,
} }
@ -79,13 +79,19 @@ impl<UART: serial::Uart> SerialIO<UART> {
} }
pub fn send_bytes(&mut self, payload: &[u8], eos: Option<u8>) -> Result<usize> { pub fn send_bytes(&mut self, payload: &[u8], eos: Option<u8>) -> Result<usize> {
//self.rx.clear(); let mut num_bytes = 0;
for b in payload.iter() { for b in payload.iter() {
nb::block!(self.tx.write(*b)) nb::block!(self.tx.write(*b))
.map_err(|err| SerialError::WriteError(format!("Error writing '{}' to serial, Original error {}", b, err)))?; .map_err(|err| SerialError::WriteError)?;
num_bytes += 1;
} }
if num_bytes == payload.len() {
eos.map(|b| nb::block!(self.tx.write(b))); eos.map(|b| nb::block!(self.tx.write(b)));
Ok(payload.len() + if eos.is_none() { 0 } else { 1 }) Ok(num_bytes + if eos.is_none() { 0 } else { 1 })
}
else {
Err(SerialError::WriteError)
}
} }
/// Reads a whole line (that ends with \\n) within the given `timeout` passed on input. /// Reads a whole line (that ends with \\n) within the given `timeout` passed on input.