mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
//! `COMMAND_ACK` (message id 77): the result of executing a `COMMAND_LONG`.

use super::payload::{i32_at, u8_at, u16_at};

/// This message's id.
pub const ID: u32 = 77;
/// This message's `crc_extra` byte (see [`crate::crc`]).
pub const CRC_EXTRA: u8 = 143;
const LEN: usize = 10;

/// A decoded `COMMAND_ACK` message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandAck {
    /// The command being acknowledged (`MAV_CMD`).
    pub command: u16,
    /// The command's result (`MAV_RESULT`).
    pub result: u8,
    /// Completion progress, `0`-`100` (only meaningful while `result` is
    /// `MAV_RESULT_IN_PROGRESS`).
    pub progress: u8,
    /// Command-specific additional result info.
    pub result_param2: i32,
    /// System id of the originator of this command, for a command
    /// broadcast to multiple systems.
    pub target_system: u8,
    /// Component id of the originator of this command.
    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() {
        // Real wire payload from pymavlink: command=400 result=0
        // progress=255 result_param2=0 target_system=1 target_component=1.
        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);
    }
}