From f3b79bb9aa95d88b962ba7e538ba3e623cc04dda Mon Sep 17 00:00:00 2001 From: Tobias Maier Date: Sat, 22 Nov 2025 00:16:09 +0100 Subject: [PATCH] added expected return --- src/message.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/message.rs b/src/message.rs index a381508..6f68cbf 100644 --- a/src/message.rs +++ b/src/message.rs @@ -143,6 +143,23 @@ impl Protocol300Message { bytes_vec } + + // TODO docs and test + /// Returns the expected length of the return telegram, include start byte but excluding ACK byte + /// + /// Currently only implemented for Read and Write requests, as the rest is not needed and/or + /// unknown behaviour + /// + /// # Errors: + /// - `MessageReturnLengthError` - Describes the error which occured when converting + pub const fn get_expected_return_telegram_length(&self) -> Result { + match (self.message_identifier, self.function_code) { + (MessageIdentifier::Request, FunctionCode::VirtualREAD) => Ok(8 + self.data_length as usize), + (MessageIdentifier::Request, FunctionCode::VirtualWRITE) => Ok(8), + (MessageIdentifier::Response, _) => Err(MessageReturnLengthError::NonsensicalRequest), + _ => Err(MessageReturnLengthError::Unimplemented()) + } + } } /// Errors that can occur while creating a message @@ -151,6 +168,18 @@ pub enum MessageCreationError { /// The data length is longer than u8 #[error("Data too long")] DataTooLong(#[from] std::num::TryFromIntError), + +} + +/// Errors that can occur while getting the expected return length of a message +#[derive(Error, Debug, PartialEq, Eq)] +pub enum MessageReturnLengthError { + /// The data length is longer than u8 + #[error("Unimplemented")] + Unimplemented(), + /// It makes no sense to get the expected length for a response + #[error("Nonsensical request")] + NonsensicalRequest } /// Errors that can occur while decoding a message from bytes @@ -343,5 +372,33 @@ mod tests { assert_eq!(bytes_expected, bytes_generated); } + #[test] + fn test_expected_return_length_read() { + let expected_message = Protocol300Message{ + telegram_length: 5, + message_identifier: MessageIdentifier::Request, + function_code: FunctionCode::VirtualREAD, + data_address: 0x0101, + data_length: 2, + data: vec![], + checksum: 0x0A + }; + assert_eq!(10_usize, expected_message.get_expected_return_telegram_length().unwrap()); + } + + #[test] + fn test_expected_return_length_write() { + let expected_message = Protocol300Message{ + telegram_length: 9, + message_identifier: MessageIdentifier::Request, + function_code: FunctionCode::VirtualWRITE, + data_address: 0x0101, + data_length: 4, + data: vec![0x01, 0x02, 0x03, 0x04], + checksum: 0x1B + }; + assert_eq!(8_usize, expected_message.get_expected_return_telegram_length().unwrap()); + } + } \ No newline at end of file