mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
//! `STATUSTEXT` (message id 253): a human-readable status/log message.

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

/// This message's id.
pub const ID: u32 = 253;
/// This message's `crc_extra` byte (see [`crate::crc`]).
pub const CRC_EXTRA: u8 = 83;
const LEN: usize = 54;
const TEXT_LEN: usize = 50;

/// A decoded `STATUSTEXT` message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StatusText {
    /// Severity (`MAV_SEVERITY`, follows syslog levels: `0` = emergency,
    /// `7` = debug).
    pub severity: u8,
    /// The status text.
    pub text: FixedText<TEXT_LEN>,
    /// Message id, for a text spanning multiple chunked `STATUSTEXT`
    /// messages (`0` if this is the only/first chunk).
    pub id: u16,
    /// This chunk's sequence number, for a multi-chunk message.
    pub chunk_seq: u8,
}

impl StatusText {
    pub(crate) fn decode(payload: &[u8]) -> Self {
        Self {
            severity: u8_at(payload, 0),
            text: FixedText::from_bytes(array_at(payload, 1)),
            id: u16_at(payload, 51),
            chunk_seq: u8_at(payload, 53),
        }
    }

    pub(crate) fn encode(&self) -> [u8; LEN] {
        let mut buf = [0u8; LEN];
        buf[0] = self.severity;
        buf[1..51].copy_from_slice(self.text.as_bytes());
        buf[51..53].copy_from_slice(&self.id.to_le_bytes());
        buf[53] = self.chunk_seq;
        buf
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_a_real_captured_frame() {
        // Real wire payload from pymavlink, truncated to 6 of 54 bytes
        // (text's remaining padding, id, and chunk_seq are all zero and
        // get stripped, see frame.rs): severity=6 text="hello" id=0
        // chunk_seq=0.
        let hex = "0668656c6c6f";
        let mut payload = [0u8; 6];
        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 s = StatusText::decode(&payload);
        assert_eq!(s.severity, 6);
        assert_eq!(s.text.as_str(), "hello");
        assert_eq!(s.id, 0);
        assert_eq!(s.chunk_seq, 0);
    }

    #[test]
    fn round_trips_through_decode() {
        let s = StatusText {
            severity: 2,
            text: FixedText::from_text("ARMING CHECK FAILED"),
            id: 42,
            chunk_seq: 1,
        };
        assert_eq!(StatusText::decode(&s.encode()), s);
    }
}