use super::payload::{array_at, f32_at, u8_at, u16_at};
use super::text::FixedText;
pub const ID: u32 = 22;
pub const CRC_EXTRA: u8 = 220;
const LEN: usize = 25;
const PARAM_ID_LEN: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ParamValue {
pub param_id: FixedText<PARAM_ID_LEN>,
pub param_value: f32,
pub param_type: u8,
pub param_count: u16,
pub param_index: u16,
}
impl ParamValue {
pub(crate) fn decode(payload: &[u8]) -> Self {
Self {
param_value: f32_at(payload, 0),
param_count: u16_at(payload, 4),
param_index: u16_at(payload, 6),
param_id: FixedText::from_bytes(array_at(payload, 8)),
param_type: u8_at(payload, 24),
}
}
pub(crate) fn encode(&self) -> [u8; LEN] {
let mut buf = [0u8; LEN];
buf[0..4].copy_from_slice(&self.param_value.to_le_bytes());
buf[4..6].copy_from_slice(&self.param_count.to_le_bytes());
buf[6..8].copy_from_slice(&self.param_index.to_le_bytes());
buf[8..24].copy_from_slice(self.param_id.as_bytes());
buf[24] = self.param_type;
buf
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_a_real_captured_frame() {
let hex = "0000803f320003005448525f4d415800000000000000000009";
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 p = ParamValue::decode(&payload);
assert_eq!(p.param_id.as_str(), "THR_MAX");
assert!((p.param_value - 1.0).abs() < f32::EPSILON);
assert_eq!(p.param_type, 9);
assert_eq!(p.param_count, 50);
assert_eq!(p.param_index, 3);
}
#[test]
fn round_trips_through_decode() {
let p = ParamValue {
param_id: FixedText::from_text("ARSPD_USE"),
param_value: -12.5,
param_type: 4,
param_count: 700,
param_index: 12,
};
assert_eq!(ParamValue::decode(&p.encode()), p);
}
}