diff --git a/src/improv.rs b/src/improv.rs index a896cee..502f170 100644 --- a/src/improv.rs +++ b/src/improv.rs @@ -103,3 +103,37 @@ pub fn calculate_checksum(data: &Vec) -> u8 { return checksum; } + +pub struct ImprovPacket { + pub version: u8, + pub r#type: PacketType, + pub data: Vec, +} + +impl ImprovPacket { + pub fn try_from_bytes(bytes: &Vec) -> Result { + 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 = 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(), + }); + } +} diff --git a/src/main.rs b/src/main.rs index d297e7b..43be4d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 + >::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: {}", ¤t_state); - packet_index += 1; } },