mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
//! `PARAM_VALUE` (message id 22): a single parameter's current value, sent
//! in response to a read/set request or during a full parameter dump.

use super::payload::{array_at, f32_at, u8_at, u16_at};
use super::text::FixedText;

/// This message's id.
pub const ID: u32 = 22;
/// This message's `crc_extra` byte (see [`crate::crc`]).
pub const CRC_EXTRA: u8 = 220;
const LEN: usize = 25;
const PARAM_ID_LEN: usize = 16;

/// A decoded `PARAM_VALUE` message.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ParamValue {
    /// Parameter name.
    pub param_id: FixedText<PARAM_ID_LEN>,
    /// Onboard parameter value, always transmitted as `MAVLink`'s generic
    /// `f32` parameter encoding regardless of `param_type`.
    pub param_value: f32,
    /// Onboard parameter type (`MAV_PARAM_TYPE`).
    pub param_type: u8,
    /// Total number of onboard parameters.
    pub param_count: u16,
    /// Index of this parameter among all onboard parameters.
    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() {
        // Real wire payload from pymavlink: param_id="THR_MAX"
        // param_value=1.0 param_type=9 param_count=50 param_index=3.
        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);
    }
}