32 lines
975 B
Rust
32 lines
975 B
Rust
use serde::{Serialize, Deserialize};
|
|
use std::error::Error;
|
|
use tracing::debug;
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Packet {
|
|
pub packet_size: u16,
|
|
pub packet_type: u16,
|
|
pub packet_crc: u16,
|
|
pub payload: Vec<u8>,
|
|
}
|
|
|
|
impl Packet {
|
|
pub fn parse(data: &[u8]) -> Result<Self, Box<dyn Error>> {
|
|
if data.len() < 6 {
|
|
return Err("Invalid packet: Too short".into());
|
|
}
|
|
|
|
let packet_size = u16::from_be_bytes(data[0..2].try_into()?);
|
|
let packet_type = u16::from_be_bytes(data[2..4].try_into()?);
|
|
let packet_crc = u16::from_be_bytes(data[4..6].try_into()?);
|
|
let payload = data[6..].to_vec();
|
|
|
|
debug!("Packet Size: {}", packet_size);
|
|
debug!("Packet Type: {}", packet_type);
|
|
debug!("Packet CRC: {}", packet_crc);
|
|
debug!("Payload: {:?}", String::from_utf8(payload.clone())?);
|
|
|
|
Ok(Packet { packet_size, packet_type, packet_crc, payload })
|
|
}
|
|
}
|