From b7b01d8600b6e750245f56311d59b1a1356c1afe Mon Sep 17 00:00:00 2001 From: clerie Date: Wed, 25 Dec 2024 18:00:35 +0100 Subject: [PATCH] Buffer read but unhandled data from serial device --- src/serial.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/serial.rs b/src/serial.rs index b4ff837..9336f45 100644 --- a/src/serial.rs +++ b/src/serial.rs @@ -42,6 +42,7 @@ pub fn find_begin_of_improv_packet(buffer: &Vec) -> Result { pub struct SerialInterface { interface: Box, + buffer: Vec, } impl SerialInterface { @@ -51,6 +52,7 @@ impl SerialInterface { return Ok(Self { interface: interface, + buffer: Vec::new(), }); } @@ -76,20 +78,42 @@ impl SerialInterface { } pub fn recv_bytes(&mut self) -> Result> { - let available_bytes = self.interface.bytes_to_read()?.try_into()?; + let available_bytes = self.interface.bytes_to_read() + .context("Failed to figure out how many bytes are available to read")? + .try_into()?; + + debug!("Available bytes to read: {}", available_bytes); let mut buffer: Vec = vec![0; available_bytes]; - self.interface.read(&mut buffer)?; + + if buffer.len() > 0 { + self.interface.read(&mut buffer) + .context("Failed to read bytes from serial device")?; + } if log_enabled!(Level::Debug) { debug!("Received bytes: \n{}\n{}", hex::encode(&buffer), to_ascii_debug(&buffer)); } + self.buffer.append(&mut buffer); + + buffer = self.buffer.clone(); + + if log_enabled!(Level::Debug) { + debug!("Buffer: \n{}\n{}", hex::encode(&buffer), to_ascii_debug(&buffer)); + } + let improv_packet_offset = find_begin_of_improv_packet(&buffer).context("Failed to find improv header in received bytes from serial device")?; let improv_packet_end = improv_packet_offset + 10 + >::into(buffer[improv_packet_offset+8]); + if buffer.len() <= improv_packet_end { + bail!("Incomplete packet, packet longer than available in buffer"); + } + let packet_bytes = buffer[improv_packet_offset..improv_packet_end].to_vec(); + self.buffer = buffer[improv_packet_end..].to_vec(); + if log_enabled!(Level::Debug) { debug!("Received packet: \n{}\n{}", hex::encode(&packet_bytes), to_ascii_debug(&packet_bytes)); }