use super::payload::{u8_at, u16_at, u32_at};
pub const ID: u32 = 65;
pub const CRC_EXTRA: u8 = 118;
const LEN: usize = 42;
const CHANNEL_COUNT: usize = 18;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RcChannels {
pub time_boot_ms: u32,
pub channels: [u16; CHANNEL_COUNT],
pub chancount: u8,
pub rssi: u8,
}
impl RcChannels {
pub(crate) fn decode(payload: &[u8]) -> Self {
let mut channels = [0u16; CHANNEL_COUNT];
for (i, ch) in channels.iter_mut().enumerate() {
*ch = u16_at(payload, 4 + i * 2);
}
Self {
time_boot_ms: u32_at(payload, 0),
channels,
chancount: u8_at(payload, 4 + CHANNEL_COUNT * 2),
rssi: u8_at(payload, 5 + CHANNEL_COUNT * 2),
}
}
pub(crate) fn encode(&self) -> [u8; LEN] {
let mut buf = [0u8; LEN];
buf[0..4].copy_from_slice(&self.time_boot_ms.to_le_bytes());
for (i, &ch) in self.channels.iter().enumerate() {
buf[4 + i * 2..6 + i * 2].copy_from_slice(&ch.to_le_bytes());
}
buf[4 + CHANNEL_COUNT * 2] = self.chancount;
buf[5 + CHANNEL_COUNT * 2] = self.rssi;
buf
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_a_real_captured_frame() {
let hex =
"88130000dc05dc05e803dc05e803e803e803e803000000000000000000000000000000000000000008c8";
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 rc = RcChannels::decode(&payload);
assert_eq!(rc.time_boot_ms, 5000);
assert_eq!(
rc.channels[..8],
[1500, 1500, 1000, 1500, 1000, 1000, 1000, 1000]
);
assert_eq!(rc.channels[8..], [0; 10]);
assert_eq!(rc.chancount, 8);
assert_eq!(rc.rssi, 200);
}
#[test]
fn round_trips_through_decode() {
let mut channels = [0u16; CHANNEL_COUNT];
for (i, ch) in channels.iter_mut().enumerate() {
*ch = 1000 + u16::try_from(i).unwrap();
}
let rc = RcChannels {
time_boot_ms: 123,
channels,
chancount: 18,
rssi: 255,
};
assert_eq!(RcChannels::decode(&rc.encode()), rc);
}
}