Added create response message functions

This commit is contained in:
2026-01-03 20:16:51 +01:00
parent b3274e942c
commit 7d27e6337c

View File

@@ -53,6 +53,59 @@ impl Protocol300Message {
}
}
#[inline]
/// Creates a new `Protocol300message` used to respond to a message requesting data
///
/// # Arguments
/// * `data_address`: Address of the data to read
/// * `data`: Data which should be used to respond to the message
///
/// # Panics
/// Panics if the data vec is longer than 256 (u8), can never happen in protocol 300
pub fn new_read_response_message(data_address: u16, data: &[u8]) -> Self{
let message_identifier = MessageIdentifier::Response;
let function_code = FunctionCode::VirtualREAD;
let data_length = u8::try_from(data.len()).expect("Data should never be longer than 256");
let telegram_length: u8 = 5 + data_length;
let data = data.to_owned();
let checksum = calculate_checksum(telegram_length, message_identifier, function_code, data_address, data_length, &data);
Self {
telegram_length,
message_identifier,
function_code,
data_address,
data_length,
data,
checksum
}
}
#[inline]
/// Creates a new `Protocol300message` used to respond to a message writing data
///
/// # Arguments
/// * `data_address`: Address of the data to read
/// * `data`: Data which should be used to respond to the message
///
/// # Panics
/// Panics if the data vec is longer than 256 (u8), can never happen in protocol 300
pub fn new_write_response_message(data_address: u16, written_data_length: u8) -> Self{
let message_identifier = MessageIdentifier::Response;
let function_code = FunctionCode::VirtualWRITE;
let telegram_length: u8 = 5;
let checksum = calculate_checksum(telegram_length, message_identifier, function_code, data_address, written_data_length, &[]);
Self {
telegram_length,
message_identifier,
function_code,
data_address,
data_length: written_data_length,
data: vec![],
checksum
}
}
#[inline]
/// Creates a new `Protocol300message` used to write data to the device
///
@@ -447,5 +500,19 @@ mod tests {
assert_eq!(8_usize, expected_message.get_expected_return_telegram_length().unwrap());
}
#[test]
fn create_read_response_message() {
let generated_message = Protocol300Message::new_read_response_message(0x5525, &[0x07, 0x01]).to_bytes();
let expected_message = vec![0x41, 0x07, 0x01, 0x01, 0x55, 0x25, 0x02, 0x07, 0x01, 0x8D];
assert_eq!(generated_message, expected_message);
}
#[test]
fn create_write_response_message() {
let generated_message = Protocol300Message::new_write_response_message(0x2323, 1).to_bytes();
let expected_message = vec![0x41, 0x05, 0x01, 0x02, 0x23, 0x23, 0x01, 0x4F];
assert_eq!(generated_message, expected_message);
}
}