From 1be1defc352b7662905e9f1a3dbf759c76e0d7ac Mon Sep 17 00:00:00 2001 From: clerie Date: Wed, 30 Oct 2024 20:35:31 +0100 Subject: [PATCH] Convert ImprovPackets back to bytes --- src/improv.rs | 28 +++++++++++++++++++++++++++- src/main.rs | 22 ++++++++-------------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/improv.rs b/src/improv.rs index 502f170..5428538 100644 --- a/src/improv.rs +++ b/src/improv.rs @@ -92,7 +92,7 @@ pub enum RPCCommand { RequestCurrentState = 0x02, } -pub fn calculate_checksum(data: &Vec) -> u8 { +pub fn calculate_checksum(data: &[u8]) -> u8 { // Pass data as full packet, with header, but without checksum byte let mut checksum: u8 = 0x00; @@ -136,4 +136,30 @@ impl ImprovPacket { data: bytes[9..(bytes.len()-1)].to_vec(), }); } + + pub fn to_bytes(self: &Self) -> Vec { + let mut out = Vec::new(); + + for b in IMPROV_HEADER.clone() { + out.push(b); + } + + out.push(self.version.clone()); + + out.push(self.r#type.clone() as u8); + + let length: u8 = self.data.len().try_into().unwrap(); + + out.push(length.clone()); + + for b in self.data.clone() { + out.push(b); + } + + let checksum: u8 = calculate_checksum(&out); + + out.push(checksum.clone()); + + return out; + } } diff --git a/src/main.rs b/src/main.rs index 43be4d7..06767ef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -117,28 +117,22 @@ async fn main() -> Result<()>{ .fold(String::new(), |a, b| a + &b + &String::from("\n"))); }, Commands::Device {path, baud_rate, device_command} => { - let mut rpc_command_request_current_state: Vec = Vec::new(); - rpc_command_request_current_state.extend(IMPROV_HEADER); - rpc_command_request_current_state.push(IMPROV_VERSION); - rpc_command_request_current_state.push(PacketType::RPCCommand as u8); - let mut data: Vec = Vec::new(); data.push(RPCCommand::RequestCurrentState as u8); // command data.push(0x00); // command data length - rpc_command_request_current_state.push(data.len().try_into().unwrap()); // length - rpc_command_request_current_state.extend(data.clone()); // data + let request_current_state_packet = ImprovPacket { + version: IMPROV_VERSION, + r#type: PacketType::RPCCommand, + data: data, + }; - let checksum: u8 = calculate_checksum(&rpc_command_request_current_state); - println!("{}", hex::encode([checksum.clone()])); - rpc_command_request_current_state.push(checksum); - - println!("{}", hex::encode(&rpc_command_request_current_state)); - println!("{}", to_ascii_debug(&rpc_command_request_current_state)); + println!("{}", hex::encode(&request_current_state_packet.to_bytes())); + println!("{}", to_ascii_debug(&request_current_state_packet.to_bytes())); let mut serial_interface = tokio_serial::new(path, *baud_rate).open().unwrap(); - serial_interface.write(&rpc_command_request_current_state).unwrap(); + serial_interface.write(&request_current_state_packet.to_bytes()).unwrap(); let mut buffer: Vec = Vec::new(); serial_interface.read_to_end(&mut buffer);