use super::payload::{i32_at, u8_at, u16_at};
pub const ID: u32 = 77;
pub const CRC_EXTRA: u8 = 143;
const LEN: usize = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandAck {
pub command: u16,
pub result: u8,
pub progress: u8,
pub result_param2: i32,
pub target_system: u8,
pub target_component: u8,
}
impl CommandAck {
pub(crate) fn decode(payload: &[u8]) -> Self {
Self {
command: u16_at(payload, 0),
result: u8_at(payload, 2),
progress: u8_at(payload, 3),
result_param2: i32_at(payload, 4),
target_system: u8_at(payload, 8),
target_component: u8_at(payload, 9),
}
}
pub(crate) fn encode(&self) -> [u8; LEN] {
let mut buf = [0u8; LEN];
buf[0..2].copy_from_slice(&self.command.to_le_bytes());
buf[2] = self.result;
buf[3] = self.progress;
buf[4..8].copy_from_slice(&self.result_param2.to_le_bytes());
buf[8] = self.target_system;
buf[9] = self.target_component;
buf
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_a_real_captured_frame() {
let hex = "900100ff000000000101";
let mut payload = [0u8; LEN];
for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
payload[i] = u8::from_str_radix(core::str::from_utf8(chunk).unwrap(), 16).unwrap();
}
let ack = CommandAck::decode(&payload);
assert_eq!(
ack,
CommandAck {
command: 400,
result: 0,
progress: 255,
result_param2: 0,
target_system: 1,
target_component: 1,
}
);
}
#[test]
fn round_trips_through_decode() {
let ack = CommandAck {
command: 22,
result: 4,
progress: 50,
result_param2: -1,
target_system: 9,
target_component: 10,
};
assert_eq!(CommandAck::decode(&ack.encode()), ack);
}
}