Generate response structs from packet

This commit is contained in:
clerie 2024-12-18 20:00:26 +01:00
parent 7b7c85f976
commit 9a2b76864c
2 changed files with 47 additions and 4 deletions

View File

@ -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<u8>;
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<Self, Self::Error>;
}
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<u8> {
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<Self, Self::Error>{
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<u8> {
let mut out = Vec::new();
out.push(RPCCommand::RequestCurrentState as u8);

View File

@ -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: {}", &current_state);
let current_state_response = CurrentStateResponse::try_from_packet(&improv_packet).unwrap();
println!("Current state: {}", &current_state_response.current_state);
}
},