mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Raw `MAVLink` v1/v2 frame parsing and v2 encoding.
//!
//! A `MAVLink` frame is variable-length (0-255 byte payload, plus an
//! optional 13-byte v2 signature), so [`Frame`] borrows its bytes from the
//! caller rather than owning a fixed-size array.
//!
//! Checksum verification needs the message's `crc_extra` byte (see
//! [`crate::crc`]), which this layer doesn't know - only the message layer,
//! once it has looked up the message ID, does. So `Frame::parse` validates
//! structure (magic byte, declared length fits the buffer) but does not
//! verify the checksum; call [`Frame::verify_checksum`] once you know which
//! message this is.

use crate::error::FrameError;

/// Bit 0 of a v2 frame's `incompat_flags`: the frame is signed. This crate
/// doesn't verify or produce signatures, so signed frames are rejected at
/// parse time rather than silently accepted-but-unverified.
const INCOMPAT_FLAG_SIGNED: u8 = 0x01;

const V1_MAGIC: u8 = 0xFE;
const V2_MAGIC: u8 = 0xFD;
const V1_HEADER_LEN: usize = 6;
const V2_HEADER_LEN: usize = 10;

/// Largest possible unsigned v2 frame: 10-byte header + 255-byte payload +
/// 2-byte checksum. A buffer this size can hold any frame [`encode_v2`]
/// produces.
pub const MAX_V2_FRAME_LEN: usize = V2_HEADER_LEN + 255 + 2;

/// Which `MAVLink` wire format a [`Frame`] was parsed from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MavVersion {
    /// Legacy v1 framing (`0xFE` magic, 1-byte message ID).
    V1,
    /// Current v2 framing (`0xFD` magic, 24-bit message ID, optional
    /// signing - unsigned only, see the module docs).
    V2,
}

/// A parsed `MAVLink` v1 or v2 frame, borrowed from the caller's buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame<'a> {
    version: MavVersion,
    incompat_flags: u8,
    compat_flags: u8,
    sequence: u8,
    system_id: u8,
    component_id: u8,
    message_id: u32,
    payload: &'a [u8],
    checksum: u16,
    header_and_payload: &'a [u8],
}

impl<'a> Frame<'a> {
    /// Parses a single frame from the start of `buf`. `buf` may contain
    /// trailing bytes after the frame (e.g. the start of the next frame in
    /// a stream) - only the leading frame is parsed.
    ///
    /// # Errors
    /// Returns a [`FrameError`] if `buf` is shorter than the frame its own
    /// header declares, the magic byte isn't `0xFE`/`0xFD`, or the v2
    /// signing flag is set (unsupported, see the module docs).
    pub fn parse(buf: &'a [u8]) -> Result<Self, FrameError> {
        match buf.first() {
            None => Err(FrameError::TooShort { needed: 1, got: 0 }),
            Some(&V1_MAGIC) => Self::parse_v1(buf),
            Some(&V2_MAGIC) => Self::parse_v2(buf),
            Some(&other) => Err(FrameError::UnknownMagicByte(other)),
        }
    }

    fn parse_v1(buf: &'a [u8]) -> Result<Self, FrameError> {
        if buf.len() < V1_HEADER_LEN {
            return Err(FrameError::TooShort {
                needed: V1_HEADER_LEN,
                got: buf.len(),
            });
        }
        let len = usize::from(buf[1]);
        let needed = V1_HEADER_LEN + len + 2;
        if buf.len() < needed {
            return Err(FrameError::TooShort {
                needed,
                got: buf.len(),
            });
        }
        Ok(Self {
            version: MavVersion::V1,
            incompat_flags: 0,
            compat_flags: 0,
            sequence: buf[2],
            system_id: buf[3],
            component_id: buf[4],
            message_id: u32::from(buf[5]),
            payload: &buf[V1_HEADER_LEN..V1_HEADER_LEN + len],
            checksum: u16::from_le_bytes([buf[V1_HEADER_LEN + len], buf[V1_HEADER_LEN + len + 1]]),
            header_and_payload: &buf[1..V1_HEADER_LEN + len],
        })
    }

    fn parse_v2(buf: &'a [u8]) -> Result<Self, FrameError> {
        if buf.len() < V2_HEADER_LEN {
            return Err(FrameError::TooShort {
                needed: V2_HEADER_LEN,
                got: buf.len(),
            });
        }
        let incompat_flags = buf[2];
        if incompat_flags & INCOMPAT_FLAG_SIGNED != 0 {
            return Err(FrameError::SigningNotSupported);
        }
        let len = usize::from(buf[1]);
        let needed = V2_HEADER_LEN + len + 2;
        if buf.len() < needed {
            return Err(FrameError::TooShort {
                needed,
                got: buf.len(),
            });
        }
        let message_id = u32::from(buf[7]) | (u32::from(buf[8]) << 8) | (u32::from(buf[9]) << 16);
        Ok(Self {
            version: MavVersion::V2,
            incompat_flags,
            compat_flags: buf[3],
            sequence: buf[4],
            system_id: buf[5],
            component_id: buf[6],
            message_id,
            payload: &buf[V2_HEADER_LEN..V2_HEADER_LEN + len],
            checksum: u16::from_le_bytes([buf[V2_HEADER_LEN + len], buf[V2_HEADER_LEN + len + 1]]),
            header_and_payload: &buf[1..V2_HEADER_LEN + len],
        })
    }

    /// Which wire format this frame was parsed from.
    #[must_use]
    pub const fn version(&self) -> MavVersion {
        self.version
    }

    /// The v2 incompatibility flags (always `0` for a v1 frame).
    #[must_use]
    pub const fn incompat_flags(&self) -> u8 {
        self.incompat_flags
    }

    /// The v2 compatibility flags (always `0` for a v1 frame).
    #[must_use]
    pub const fn compat_flags(&self) -> u8 {
        self.compat_flags
    }

    /// The packet sequence number.
    #[must_use]
    pub const fn sequence(&self) -> u8 {
        self.sequence
    }

    /// The sending system's ID.
    #[must_use]
    pub const fn system_id(&self) -> u8 {
        self.system_id
    }

    /// The sending component's ID.
    #[must_use]
    pub const fn component_id(&self) -> u8 {
        self.component_id
    }

    /// The message ID (0-255 for v1, 0-16,777,215 for v2).
    #[must_use]
    pub const fn message_id(&self) -> u32 {
        self.message_id
    }

    /// The raw payload bytes as they appeared on the wire. For a v2 frame
    /// this may be *shorter* than the message's full defined length: v2
    /// senders strip trailing zero bytes (see [`encode_v2`]), so decoding
    /// fixed-position fields must treat any bytes past this slice as zero,
    /// not read them directly.
    #[must_use]
    pub const fn payload(&self) -> &'a [u8] {
        self.payload
    }

    /// The checksum as read from the wire (not yet verified - see
    /// [`Self::verify_checksum`]).
    #[must_use]
    pub const fn checksum(&self) -> u16 {
        self.checksum
    }

    /// This frame's total length in bytes (header + payload + checksum),
    /// i.e. how far to advance past it in a byte stream containing more
    /// than one frame. Never `0` (a parsed frame is always at least 8
    /// bytes), so there's no `is_empty` counterpart.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        1 + self.header_and_payload.len() + 2
    }

    /// Verifies this frame's checksum given the transmitted message's
    /// `crc_extra` byte (only the message layer, which knows how to map
    /// [`Self::message_id`] to a `crc_extra`, can supply this).
    #[must_use]
    pub fn verify_checksum(&self, crc_extra: u8) -> bool {
        crate::crc::checksum(self.header_and_payload, crc_extra) == self.checksum
    }
}

/// Encodes a v2 frame into `buf`, returning the number of bytes written.
///
/// `payload` should be the message's full fixed-position field encoding;
/// trailing zero bytes are stripped automatically (`MAVLink` v2's wire size
/// optimization - at least one payload byte is always kept), matching what
/// real `MAVLink` v2 senders (including `pymavlink`) produce. `crc_extra` is
/// the transmitted message's per-definition byte (see [`crate::crc`]); the
/// message layer looks this up by `message_id`.
///
/// # Errors
/// Returns a [`FrameError`] if `payload` is longer than 255 bytes (the
/// largest length a `MAVLink` frame can declare) or `buf` is too small to
/// hold the encoded frame (size it with [`MAX_V2_FRAME_LEN`] to always be
/// safe).
pub fn encode_v2(
    buf: &mut [u8],
    system_id: u8,
    component_id: u8,
    sequence: u8,
    message_id: u32,
    payload: &[u8],
    crc_extra: u8,
) -> Result<usize, FrameError> {
    if payload.len() > 255 {
        return Err(FrameError::PayloadTooLong {
            max: 255,
            got: payload.len(),
        });
    }

    let mut len = payload.len();
    while len > 1 && payload[len - 1] == 0 {
        len -= 1;
    }
    let truncated = &payload[..len];

    let total = V2_HEADER_LEN + len + 2;
    if buf.len() < total {
        return Err(FrameError::TooShort {
            needed: total,
            got: buf.len(),
        });
    }

    buf[0] = V2_MAGIC;
    #[allow(
        clippy::cast_possible_truncation,
        reason = "len <= payload.len() <= 255, checked above"
    )]
    {
        buf[1] = len as u8;
    }
    buf[2] = 0; // incompat_flags: signing not supported
    buf[3] = 0; // compat_flags
    buf[4] = sequence;
    buf[5] = system_id;
    buf[6] = component_id;
    #[allow(
        clippy::cast_possible_truncation,
        reason = "message_id is documented as fitting 24 bits; only the low 3 bytes are used"
    )]
    {
        buf[7] = message_id as u8;
        buf[8] = (message_id >> 8) as u8;
        buf[9] = (message_id >> 16) as u8;
    }
    buf[V2_HEADER_LEN..V2_HEADER_LEN + len].copy_from_slice(truncated);

    let crc = crate::crc::checksum(&buf[1..V2_HEADER_LEN + len], crc_extra);
    buf[V2_HEADER_LEN + len..total].copy_from_slice(&crc.to_le_bytes());

    Ok(total)
}

// Frame::parse bounds-checks buf.len() against the header's own declared
// length before ever slicing, so it never panics regardless of buffer
// size -- a small fixed-size symbolic buffer still exercises every branch
// (CBMC explores all possible values of the length/magic bytes within it,
// including ones where that same small buffer is exactly long enough to
// parse successfully). encode_v2's own trailing-zero-strip loop has a
// compile-time-fixed trip count (the payload array's length), so it needs
// no #[kani::unwind] -- but it then calls crc::checksum with a *slice*
// whose length is computed at runtime from that strip (data-dependent, not
// knowable at compile time the way a fixed-array call site is), so any
// proof that goes through encode_v2 does need an explicit unwind bound for
// checksum's internal loop. Omitting this the first time around made
// CBMC unwind past 1000 iterations rather than stopping at the true
// (single-digit) bound, chewing through 30+ minutes of CPU with no result.
#[cfg(kani)]
mod kani_proofs {
    use super::{Frame, encode_v2};

    #[kani::proof]
    fn parse_never_panics() {
        let buf: [u8; 16] = kani::any();
        let _ = Frame::parse(&buf);
    }

    #[kani::proof]
    #[kani::unwind(20)]
    fn encode_v2_never_panics() {
        let mut buf = [0u8; super::MAX_V2_FRAME_LEN];
        let payload: [u8; 8] = kani::any();
        let system_id: u8 = kani::any();
        let component_id: u8 = kani::any();
        let sequence: u8 = kani::any();
        let message_id: u32 = kani::any();
        let crc_extra: u8 = kani::any();
        let _ = encode_v2(
            &mut buf,
            system_id,
            component_id,
            sequence,
            message_id,
            &payload,
            crc_extra,
        );
    }

    // A 1-byte payload and a message_id pre-constrained to the 24 bits a
    // real v2 frame actually carries (dropping the truncation-of-a-wider-
    // value edge case, covered instead by a plain unit test below) keeps
    // this tractable for CBMC.
    #[kani::proof]
    #[kani::unwind(13)]
    fn encode_then_parse_round_trips() {
        let mut buf = [0u8; super::MAX_V2_FRAME_LEN];
        let payload: [u8; 1] = kani::any();
        let system_id: u8 = kani::any();
        let component_id: u8 = kani::any();
        let sequence: u8 = kani::any();
        let message_id: u32 = kani::any();
        kani::assume(message_id <= 0x00FF_FFFF);
        let crc_extra: u8 = kani::any();

        let n = encode_v2(
            &mut buf,
            system_id,
            component_id,
            sequence,
            message_id,
            &payload,
            crc_extra,
        )
        .unwrap();

        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.system_id(), system_id);
        assert_eq!(frame.component_id(), component_id);
        assert_eq!(frame.sequence(), sequence);
        assert_eq!(frame.message_id(), message_id);
        assert!(frame.verify_checksum(crc_extra));
    }
}

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

    fn hex_decode(hex: &str) -> [u8; 32] {
        let mut out = [0u8; 32];
        for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
            let s = core::str::from_utf8(chunk).unwrap();
            out[i] = u8::from_str_radix(s, 16).unwrap();
        }
        out
    }

    #[test]
    fn parses_a_real_captured_heartbeat_v2_frame() {
        // From pymavlink: HEARTBEAT type=2 autopilot=3 base_mode=81
        // custom_mode=0 system_status=4 mavlink_version=3, sysid=1
        // compid=1 seq=0, crc_extra=50.
        let hex = "fd090000000101000000000000000203510403e71e";
        let buf = hex_decode(hex);
        let frame = Frame::parse(&buf[..hex.len() / 2]).unwrap();
        assert_eq!(frame.version(), MavVersion::V2);
        assert_eq!(frame.system_id(), 1);
        assert_eq!(frame.component_id(), 1);
        assert_eq!(frame.sequence(), 0);
        assert_eq!(frame.message_id(), 0);
        assert_eq!(frame.payload().len(), 9);
        assert!(frame.verify_checksum(50));
        assert!(!frame.verify_checksum(51));
    }

    #[test]
    fn parses_a_truncated_v2_statustext_frame() {
        // From pymavlink: STATUSTEXT severity=6 text="hello" id=0
        // chunk_seq=0, sysid=1 compid=1 seq=0, crc_extra=83. Full payload
        // is 54 bytes but trailing zeros are stripped to 6 on the wire.
        let hex = "fd060000000101fd00000668656c6c6f4795";
        let buf = hex_decode(hex);
        let frame = Frame::parse(&buf[..hex.len() / 2]).unwrap();
        assert_eq!(frame.message_id(), 253);
        assert_eq!(frame.payload(), b"\x06hello");
        assert!(frame.verify_checksum(83));
    }

    #[test]
    fn rejects_a_signed_v2_frame() {
        let mut buf = hex_decode("fd090000000101000000000000000203510403e71e");
        buf[2] = INCOMPAT_FLAG_SIGNED;
        assert_eq!(
            Frame::parse(&buf[..21]),
            Err(FrameError::SigningNotSupported)
        );
    }

    #[test]
    fn rejects_an_unknown_magic_byte() {
        assert_eq!(
            Frame::parse(&[0x00, 0x00]),
            Err(FrameError::UnknownMagicByte(0x00))
        );
    }

    #[test]
    fn rejects_a_buffer_shorter_than_the_declared_length() {
        let buf = hex_decode("fd090000000101000000000000000203510403e71e");
        assert_eq!(
            Frame::parse(&buf[..10]),
            Err(FrameError::TooShort {
                needed: 21,
                got: 10
            })
        );
    }

    #[test]
    fn encode_v2_matches_a_real_pymavlink_heartbeat_frame() {
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let payload = [0u8, 0, 0, 0, 2, 3, 0x51, 4, 3]; // custom_mode=0, type=2, autopilot=3, base_mode=81, system_status=4, mavlink_version=3
        let n = encode_v2(&mut buf, 1, 1, 0, 0, &payload, 50).unwrap();
        let expected = hex_decode("fd090000000101000000000000000203510403e71e");
        assert_eq!(&buf[..n], &expected[..n]);
    }

    #[test]
    fn encode_v2_strips_trailing_zeros_like_a_real_statustext_frame() {
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let mut payload = [0u8; 54];
        payload[0] = 6; // severity
        payload[1..6].copy_from_slice(b"hello");
        let n = encode_v2(&mut buf, 1, 1, 0, 253, &payload, 83).unwrap();
        let expected = hex_decode("fd060000000101fd00000668656c6c6f4795");
        assert_eq!(&buf[..n], &expected[..n]);
    }

    #[test]
    fn encode_v2_round_trips_through_parse() {
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let payload = [1u8, 2, 3, 4, 5];
        let n = encode_v2(&mut buf, 7, 8, 9, 12345, &payload, 200).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.system_id(), 7);
        assert_eq!(frame.component_id(), 8);
        assert_eq!(frame.sequence(), 9);
        assert_eq!(frame.message_id(), 12345);
        assert_eq!(frame.payload(), &payload);
        assert!(frame.verify_checksum(200));
    }

    #[test]
    fn encode_v2_truncates_a_message_id_wider_than_24_bits() {
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let n = encode_v2(&mut buf, 1, 1, 0, 0xAB00_1234, &[0], 0).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.message_id(), 0x00_1234);
    }

    #[test]
    fn byte_len_matches_the_bytes_actually_consumed() {
        let mut buf = [0u8; MAX_V2_FRAME_LEN];
        let payload = [1u8, 2, 3, 4, 5];
        let n = encode_v2(&mut buf, 1, 1, 0, 12345, &payload, 200).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.byte_len(), n);
    }
}