From 7b7c85f976602640856277e05e4387affc11d8f7 Mon Sep 17 00:00:00 2001 From: clerie Date: Wed, 30 Oct 2024 22:03:13 +0100 Subject: [PATCH] Generate packet from struct --- src/improv.rs | 29 +++++++++++++++++++++++++++++ src/main.rs | 12 +++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/improv.rs b/src/improv.rs index 5428538..1a5513a 100644 --- a/src/improv.rs +++ b/src/improv.rs @@ -104,6 +104,21 @@ pub fn calculate_checksum(data: &[u8]) -> u8 { return checksum; } +pub trait ImprovDataToPacket { + const packet_type: PacketType; + + fn to_bytes(&self) -> Vec; + + fn to_packet(&self) -> ImprovPacket { + return ImprovPacket { + version: IMPROV_VERSION, + r#type: Self::packet_type, + data: self.to_bytes().to_vec(), + } + + } +} + pub struct ImprovPacket { pub version: u8, pub r#type: PacketType, @@ -163,3 +178,17 @@ impl ImprovPacket { return out; } } + +pub struct RequestCurrentStateCommand { +} + +impl ImprovDataToPacket for RequestCurrentStateCommand { + const packet_type: PacketType = PacketType::RPCCommand; + + fn to_bytes(self: &Self) -> Vec { + let mut out = Vec::new(); + out.push(RPCCommand::RequestCurrentState as u8); + out.push(0x00); // rpc command payload length + return out; + } +} diff --git a/src/main.rs b/src/main.rs index 06767ef..cc5f517 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,9 @@ use improv_setup::improv::{ RPCCommand, CurrentState, calculate_checksum, + ImprovDataToPacket, ImprovPacket, + RequestCurrentStateCommand, }; use log::{ debug, @@ -117,15 +119,7 @@ async fn main() -> Result<()>{ .fold(String::new(), |a, b| a + &b + &String::from("\n"))); }, Commands::Device {path, baud_rate, device_command} => { - let mut data: Vec = Vec::new(); - data.push(RPCCommand::RequestCurrentState as u8); // command - data.push(0x00); // command data length - - let request_current_state_packet = ImprovPacket { - version: IMPROV_VERSION, - r#type: PacketType::RPCCommand, - data: data, - }; + let request_current_state_packet = (RequestCurrentStateCommand {}).to_packet(); println!("{}", hex::encode(&request_current_state_packet.to_bytes())); println!("{}", to_ascii_debug(&request_current_state_packet.to_bytes()));