mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
//! A `no_std`, allocation-free parser and encoder for `MAVLink` v1/v2
//! telemetry messages, the wire protocol used by most drone/autopilot
//! flight stacks (`ArduPilot`, PX4) and ground control stations.
//!
//! # Layering
//!
//! - [`frame`] parses/encodes the raw v1/v2 wire framing and CRC.
//! - [`crc`] is `MAVLink`'s CRC-16/MCRF4XX checksum.
//! - [`message`] decodes/encodes a frame's payload into a typed
//!   [`MavMessage`], one variant per supported message id, verifying the
//!   checksum along the way (using the message's `crc_extra` byte, which
//!   only this layer knows how to look up).
//!
//! # No allocation
//!
//! Nothing in this crate uses `alloc`.
#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod crc;
pub mod error;
pub mod frame;
pub mod message;

pub use error::MavError;
pub use frame::Frame;
pub use message::MavMessage;

/// Parses and decodes a single `MAVLink` v1 or v2 frame from the start of
/// `buf`.
///
/// # Errors
/// Returns a [`MavError`] if the frame fails to parse, its checksum is
/// wrong, or its message id isn't one this crate decodes yet.
pub fn decode(buf: &[u8]) -> Result<MavMessage, MavError> {
    let frame = Frame::parse(buf)?;
    Ok(MavMessage::decode(&frame)?)
}

/// Encodes a typed message into a v2 frame in `buf`, returning the number
/// of bytes written.
///
/// # Errors
/// Returns a [`MavError`] under the same conditions as
/// [`MavMessage::encode_v2`].
pub fn encode_v2(
    message: &MavMessage,
    buf: &mut [u8],
    system_id: u8,
    component_id: u8,
    sequence: u8,
) -> Result<usize, MavError> {
    Ok(message.encode_v2(buf, system_id, component_id, sequence)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frame::MAX_V2_FRAME_LEN;
    use crate::message::Heartbeat;

    #[test]
    fn decodes_a_real_heartbeat_frame() {
        let hex = "fd090000000101000000000000000203510403e71e";
        let mut buf = [0u8; 32];
        for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
            buf[i] = u8::from_str_radix(core::str::from_utf8(chunk).unwrap(), 16).unwrap();
        }
        let msg = decode(&buf[..hex.len() / 2]).unwrap();
        let MavMessage::Heartbeat(hb) = msg else {
            panic!("expected Heartbeat");
        };
        assert_eq!(hb.mavlink_version, 3);
    }

    #[test]
    fn encode_v2_round_trips() {
        let original = MavMessage::Heartbeat(Heartbeat {
            mav_type: 2,
            autopilot: 3,
            base_mode: 81,
            custom_mode: 0,
            system_status: 4,
            mavlink_version: 3,
        });
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let n = encode_v2(&original, &mut buf, 1, 1, 0).unwrap();
        assert_eq!(decode(&buf[..n]).unwrap(), original);
    }
}