Read improv packet bytes into struct

This commit is contained in:
clerie 2024-10-27 12:46:42 +01:00
parent 5134589f6e
commit 5582ec6cb2
2 changed files with 41 additions and 15 deletions

View File

@ -103,3 +103,37 @@ pub fn calculate_checksum(data: &Vec<u8>) -> u8 {
return checksum;
}
pub struct ImprovPacket {
pub version: u8,
pub r#type: PacketType,
pub data: Vec<u8>,
}
impl ImprovPacket {
pub fn try_from_bytes(bytes: &Vec<u8>) -> Result<Self, &str> {
if bytes.len() < 11 {
return Err("Packet too small");
}
for i in 0..5 {
if bytes[i] != IMPROV_HEADER[i] {
return Err("Improv header not found");
}
}
let data: Vec<u8> = Vec::new();
let length: usize = bytes[8].into();
if bytes.len() != length + 10 {
return Err("Packet with invalid length");
}
return Ok(Self {
version: bytes[6],
r#type: PacketType::try_from(&bytes[7])?,
data: bytes[9..(bytes.len()-1)].to_vec(),
});
}
}

View File

@ -15,6 +15,7 @@ use improv_setup::improv::{
RPCCommand,
CurrentState,
calculate_checksum,
ImprovPacket,
};
use log::{
debug,
@ -149,27 +150,18 @@ async fn main() -> Result<()>{
let improv_packet_offset = find_begin_of_improv_packet(&buffer).unwrap();
println!("{}", improv_packet_offset);
let mut packet_index = improv_packet_offset;
// skip header
packet_index += 6;
let improv_packet_end = improv_packet_offset + 10 + <u8 as Into<usize>>::into(buffer[improv_packet_offset+8]);
let improv_packet = ImprovPacket::try_from_bytes(&buffer[improv_packet_offset..improv_packet_end].to_vec()).unwrap();
// version
println!("Version: {}", &buffer[packet_index]);
packet_index += 1;
println!("Version: {}", &improv_packet.version);
// type
let packet_type = PacketType::try_from(&buffer[packet_index]).unwrap();
println!("Type: {}", &packet_type);
packet_index += 1;
println!("Type: {}", &improv_packet.r#type);
if packet_type == PacketType::CurrentState {
// skip length
packet_index +=1;
let current_state = CurrentState::try_from(&buffer[packet_index]).unwrap();
if improv_packet.r#type == PacketType::CurrentState {
let current_state = CurrentState::try_from(&improv_packet.data[0]).unwrap();
println!("Current state: {}", &current_state);
packet_index += 1;
}
},