From 9a2b76864cc4970e486ce59282c8f9b911a76871 Mon Sep 17 00:00:00 2001 From: clerie Date: Wed, 18 Dec 2024 20:00:26 +0100 Subject: [PATCH] Generate response structs from packet --- src/improv.rs | 44 ++++++++++++++++++++++++++++++++++++++++++-- src/main.rs | 7 +++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/improv.rs b/src/improv.rs index 1a5513a..893dbf6 100644 --- a/src/improv.rs +++ b/src/improv.rs @@ -104,9 +104,11 @@ pub fn calculate_checksum(data: &[u8]) -> u8 { return checksum; } -pub trait ImprovDataToPacket { +pub trait ImprovDataPacketType { const packet_type: PacketType; +} +pub trait ImprovDataToPacket: ImprovDataPacketType { fn to_bytes(&self) -> Vec; fn to_packet(&self) -> ImprovPacket { @@ -119,6 +121,12 @@ pub trait ImprovDataToPacket { } } +pub trait ImprovDataFromPacket: ImprovDataPacketType + Sized { + type Error; + + fn try_from_packet(improv_packet: &ImprovPacket) -> Result; +} + pub struct ImprovPacket { pub version: u8, pub r#type: PacketType, @@ -179,12 +187,44 @@ impl ImprovPacket { } } +pub struct CurrentStateResponse { + pub current_state: CurrentState, +} + +impl ImprovDataPacketType for CurrentStateResponse { + const packet_type: PacketType = PacketType::CurrentState; +} + +impl ImprovDataToPacket for CurrentStateResponse { + fn to_bytes(self: &Self) -> Vec { + let mut out = Vec::new(); + out.push(self.current_state.clone() as u8); + return out; + } +} + +impl ImprovDataFromPacket for CurrentStateResponse { + type Error = &'static str; + + fn try_from_packet(improv_packet: &ImprovPacket) -> Result{ + if improv_packet.r#type != Self::packet_type { + return Err("Packet is not CurrentStateResponse"); + } + + return Ok(Self { + current_state: CurrentState::try_from(&improv_packet.data[0])?, + }) + } +} + pub struct RequestCurrentStateCommand { } -impl ImprovDataToPacket for RequestCurrentStateCommand { +impl ImprovDataPacketType for RequestCurrentStateCommand { const packet_type: PacketType = PacketType::RPCCommand; +} +impl ImprovDataToPacket for RequestCurrentStateCommand { fn to_bytes(self: &Self) -> Vec { let mut out = Vec::new(); out.push(RPCCommand::RequestCurrentState as u8); diff --git a/src/main.rs b/src/main.rs index cc5f517..61f1906 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,9 @@ use improv_setup::improv::{ CurrentState, calculate_checksum, ImprovDataToPacket, + ImprovDataFromPacket, ImprovPacket, + CurrentStateResponse, RequestCurrentStateCommand, }; use log::{ @@ -148,8 +150,9 @@ async fn main() -> Result<()>{ println!("Type: {}", &improv_packet.r#type); if improv_packet.r#type == PacketType::CurrentState { - let current_state = CurrentState::try_from(&improv_packet.data[0]).unwrap(); - println!("Current state: {}", ¤t_state); + let current_state_response = CurrentStateResponse::try_from_packet(&improv_packet).unwrap(); + + println!("Current state: {}", ¤t_state_response.current_state); } },