diff --git a/src/decoder.rs b/src/decoder.rs index eb5ac8107..df4487147 100644 --- a/src/decoder.rs +++ b/src/decoder.rs @@ -4,7 +4,7 @@ use crate::message::{ProtocolMessage, HEADER}; pub enum ParseError { InvalidStartByte, IncompleteData, - ChecksumError, + ChecksumError(ProtocolMessage), } #[derive(Debug)] @@ -89,9 +89,12 @@ impl Decoder { self.buffer.push(byte); if self.buffer.len() == 2 { self.message.checksum = u16::from_le_bytes([self.buffer[0], self.buffer[1]]); + self.reset(); let message = self.message.clone(); self.message = ProtocolMessage::new(); - self.reset(); + if !message.has_valid_crc() { + return DecoderResult::Error(ParseError::ChecksumError(message)); + } return DecoderResult::Success(message); } return DecoderResult::InProgress; diff --git a/tests/deserialize.rs b/tests/deserialize.rs index d977d4c3b..a21000640 100644 --- a/tests/deserialize.rs +++ b/tests/deserialize.rs @@ -39,6 +39,23 @@ fn test_simple_deserialization() { panic!("Failed to use decoder with valid message"); }; + // Retry with a wrong receipt CRC + for byte in &buffer[0..buffer.len() - 2] { + dbg!(byte, &decoder.state); + assert!(matches!( + decoder.parse_byte(byte.clone()), + DecoderResult::InProgress + )); + } + assert!(matches!( + decoder.parse_byte(buffer[buffer.len() - 2]), + DecoderResult::InProgress + )); + assert!(matches!( + decoder.parse_byte(0x01), // force a crc error + DecoderResult::Error(ParseError::ChecksumError(_)) + )); + // Wrong CRC test let buffer: Vec = vec![ 0x42, 0x52, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x05, 0x00, 0xa1, 0x01,