diff --git a/src/transmission.rs b/src/transmission.rs index c0746c1..4295092 100644 --- a/src/transmission.rs +++ b/src/transmission.rs @@ -61,6 +61,16 @@ impl Protocol300Transmission { Self::Message(protocol300_message) => protocol300_message.to_bytes(), } } + + /// Returns the length in bytes of the transmission + #[must_use] + pub fn length_in_bytes(&self) -> usize { + match self { + Self::Ack | Self::Enq | Self::Eot | Self::Nack => 1, + Self::Init => 3, + Self::Message(protocol300_message) => (protocol300_message.telegram_length + 3).into(), + } + } } /// Errors that can occur when getting a Protocol 300 Transmission from bytes @@ -155,4 +165,44 @@ mod tests { }; assert_eq!(Protocol300Transmission::Message(message).to_bytes(), &[0x41, 0x09, 0x01, 0x01, 0x55, 0x25, 0x04, 0x07, 0x01, 0x27, 0x11, 0xC9]); } + + #[test] + fn length_in_bytes_ack() { + assert_eq!(Protocol300Transmission::Ack.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_enq() { + assert_eq!(Protocol300Transmission::Enq.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_eot() { + assert_eq!(Protocol300Transmission::Eot.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_nack() { + assert_eq!(Protocol300Transmission::Nack.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_init() { + assert_eq!(Protocol300Transmission::Init.length_in_bytes(), 3); + } + + #[test] + fn length_in_bytes_message() { + let message = Protocol300Message{ + data_address: 0x5525, + telegram_length: 0x09, + function_code: FunctionCode::VirtualREAD, + message_identifier: MessageIdentifier::Response, + data_length: 0x04, + data: vec![0x07, 0x01, 0x27, 0x11], + checksum: 0xC9 + }; + // telegram_length is 0x09, so expected length is 0x09 + 3 = 12 + assert_eq!(Protocol300Transmission::Message(message).length_in_bytes(), 12); + } }