Drone software: architecture, MAVLink and telemetry · 5 MIN READ
MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing
Encode and decode a MAVLink v2 HEARTBEAT in pure Go with encoding/binary, compute the CRC-16/MCRF4XX checksum seeded with CRC_EXTRA, and watch corruption and mismatched definitions get rejected.
MAVLink is the protocol PX4, ArduPilot, QGroundControl and most drone tooling speak. It is deliberately small: a 10-byte header, a payload of fixed-size little-endian fields and a 2-byte checksum, designed for slow and lossy serial radios. Building a frame by hand once is the best way to understand what every library does for you, and why one wrong byte or a mismatched message definition makes frames silently disappear.
drones · A MAP OF THE IDEA
- Order fields by size
- Trim trailing zeros
- CRC with CRC_EXTRA
- Validate, zero-extend
Useful when
- Small fixed headers suit slow, lossy serial radios.
- CRC_EXTRA catches mismatched message definitions.
Watch out
- A CRC detects accidents, not attackers; sign links that matter.
- Without a definition a receiver cannot validate a message.
Implementation & operation cost: A generated dialect or a small hand-written codec per message, plus key management if you enable signing.
The frame, byte by byte
A MAVLink v2 frame starts with the magic byte 0xFD, then len (the payload length after truncation), incompat_flags (flags a receiver must understand or drop the frame; 0x01 means signed), compat_flags (flags it may ignore), seq (a per-sender counter that wraps at 255 and reveals lost frames), sysid (the system, such as vehicle 1 or a ground station, often 255), compid (the component: 1 is the autopilot, 190 the mission planner), and a 24-bit message id, little-endian. The payload follows, up to 255 bytes, then the checksum low byte first, then an optional 13-byte signature. A frame is 12 to 280 bytes. MAVLink 1 frames start with 0xFE and have an 8-bit message id; most stacks still accept them, but new code should send v2.
Payload: reordered, little-endian, truncated
The XML definition lists fields in a readable order, but on the wire they are sorted by type size, largest first, keeping the declared order among equal sizes; extension fields come last in declared order. That is why HEARTBEAT's uint32 custom_mode comes before type and autopilot although it is declared after them. Everything is little-endian. MAVLink 2 then removes trailing zero bytes from the payload (the first byte is always kept) and the receiver zero-extends to the full size. Truncation is byte-wise, not field-wise: the high zero bytes of a small int32 go too. A Go struct whose fields follow the wire order maps straight onto the payload with binary.Append and binary.Decode, which never insert padding.
CRC-16/MCRF4XX and CRC_EXTRA
The checksum is CRC-16/MCRF4XX, which MAVLink's documentation and code call X.25: the reflected polynomial 0x1021, an initial value of 0xFFFF and no final XOR. It covers every byte after the magic byte through the end of the payload, and then one more byte that is never sent: CRC_EXTRA, an 8-bit value the code generator derives from the message name and the types and names of its base fields. If the receiver was generated from a different definition (a renamed field, a changed type or array length), its CRC differs and the frame is dropped rather than misread. It also means a receiver cannot validate a message it has no definition for: a router that forwards such messages has to pass them on unchecked.
Encode, decode and corrupt a HEARTBEAT
The program checks the CRC function against the published check value, encodes the HEARTBEAT of an armed ArduPilot quadrotor in GUIDED mode (custom mode 4 in ArduCopter's numbering) as system 1, component 1, decodes it back, flips the armed bit to show the CRC rejecting it, recomputes the checksum with a wrong CRC_EXTRA, and encodes a hovering GLOBAL_POSITION_INT to show truncation.
package main
import (
"encoding/binary"
"errors"
"fmt"
"log"
)
// MAVLink v2 frame layout:
//
// 0xFD len incompat compat seq sysid compid msgid(3, LE) payload crc(2, LE) [signature(13)]
const (
magicV2 = 0xFD
headerLen = 10
flagSigned = 0x01 // incompat flag: a 13-byte signature follows the CRC
)
// Message ids and their CRC_EXTRA seeds, generated from the XML definitions.
const (
msgHeartbeat = 0
msgGlobalPositionInt = 33
)
var crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}
// Heartbeat is HEARTBEAT (#0). Fields are in wire order: larger types first.
type Heartbeat struct {
CustomMode uint32
Type uint8 // MAV_TYPE: 2 = quadrotor, 6 = GCS
Autopilot uint8 // MAV_AUTOPILOT: 3 = ArduPilot, 12 = PX4, 8 = invalid
BaseMode uint8 // MAV_MODE_FLAG bits: 0x80 = safety armed, 0x01 = custom mode
SystemStatus uint8 // MAV_STATE: 3 = standby, 4 = active
MavlinkVersion uint8
}
// GlobalPositionInt is GLOBAL_POSITION_INT (#33), 28 bytes on the wire.
type GlobalPositionInt struct {
TimeBootMs uint32
Lat, Lon int32 // degE7
Alt, RelativeAlt int32 // mm
Vx, Vy, Vz int16 // cm/s, north, east, down
Hdg uint16
}
type Frame struct {
Seq, SysID, CompID uint8
MsgID uint32
Payload []byte // as received: possibly truncated
}
// crcAccumulate adds one byte to a CRC-16/MCRF4XX checksum (MAVLink calls it X.25).
func crcAccumulate(crc uint16, b byte) uint16 {
tmp := b ^ byte(crc)
tmp ^= tmp << 4
return crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4
}
// crc16 starts at 0xFFFF and has no final XOR.
func crc16(data []byte) uint16 {
crc := uint16(0xFFFF)
for _, b := range data {
crc = crcAccumulate(crc, b)
}
return crc
}
// frameCRC covers every byte after the magic byte, then the message's CRC_EXTRA.
func frameCRC(data []byte, extra byte) uint16 {
return crcAccumulate(crc16(data), extra)
}
// Encode serializes a message into a MAVLink v2 frame.
func Encode(seq, sysID, compID uint8, msgID uint32, msg any) ([]byte, error) {
payload, err := binary.Append(nil, binary.LittleEndian, msg)
if err != nil {
return nil, err
}
for len(payload) > 1 && payload[len(payload)-1] == 0 {
payload = payload[:len(payload)-1] // trailing zeros are not sent; the first byte always is
}
buf := []byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,
byte(msgID), byte(msgID >> 8), byte(msgID >> 16)}
buf = append(buf, payload...)
crc := frameCRC(buf[1:], crcExtra[msgID])
return binary.LittleEndian.AppendUint16(buf, crc), nil
}
var errBadCRC = errors.New("bad CRC")
// Decode parses one frame from the start of buf and validates its checksum.
func Decode(buf []byte) (Frame, error) {
if len(buf) < headerLen+2 || buf[0] != magicV2 {
return Frame{}, errors.New("not a MAVLink v2 frame")
}
n := int(buf[1])
if buf[2]&^flagSigned != 0 {
return Frame{}, fmt.Errorf("unknown incompat flags %#x", buf[2])
}
size := headerLen + n + 2
if buf[2]&flagSigned != 0 {
size += 13
}
if len(buf) < size {
return Frame{}, errors.New("short frame")
}
f := Frame{Seq: buf[4], SysID: buf[5], CompID: buf[6],
MsgID: uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16}
extra, ok := crcExtra[f.MsgID]
if !ok {
return Frame{}, fmt.Errorf("message %d: no CRC_EXTRA, cannot validate", f.MsgID)
}
got := binary.LittleEndian.Uint16(buf[headerLen+n:])
if want := frameCRC(buf[1:headerLen+n], extra); got != want {
return Frame{}, fmt.Errorf("%w: got %#04x, want %#04x", errBadCRC, got, want)
}
f.Payload = buf[headerLen : headerLen+n]
return f, nil
}
// Unmarshal zero-extends a truncated payload and decodes it into msg.
func Unmarshal(payload []byte, msg any) error {
full := make([]byte, binary.Size(msg))
copy(full, payload)
_, err := binary.Decode(full, binary.LittleEndian, msg)
return err
}
func main() {
fmt.Printf("CRC-16/MCRF4XX check value: %#04x\n", crc16([]byte("123456789")))
hb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}
frame, err := Encode(0, 1, 1, msgHeartbeat, hb)
if err != nil {
log.Fatal(err)
}
fmt.Printf("HEARTBEAT frame (%d bytes): % x\n", len(frame), frame)
f, err := Decode(frame)
if err != nil {
log.Fatal(err)
}
var got Heartbeat
if err := Unmarshal(f.Payload, &got); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded: seq %d sys %d comp %d msg %d %+v\n", f.Seq, f.SysID, f.CompID, f.MsgID, got)
// One bit flips in transit: base_mode 0x81 (armed) becomes 0x01 (disarmed).
bad := append([]byte(nil), frame...)
bad[headerLen+6] ^= 0x80
_, err = Decode(bad)
fmt.Println("flipped bit:", err, "| rejected:", errors.Is(err, errBadCRC))
// A receiver generated from a different HEARTBEAT definition has another
// CRC_EXTRA, so the same intact bytes fail its check.
sent := binary.LittleEndian.Uint16(frame[len(frame)-2:])
fmt.Printf("receiver with CRC_EXTRA 51 computes %#04x, frame carries %#04x\n",
frameCRC(frame[1:len(frame)-2], 51), sent)
// Hovering, heading north: the last 8 bytes (vx, vy, vz, hdg) are zero.
pos := GlobalPositionInt{TimeBootMs: 125000, Lat: 473977419, Lon: 85455938, Alt: 498300, RelativeAlt: 10000}
frame, err = Encode(1, 1, 1, msgGlobalPositionInt, pos)
if err != nil {
log.Fatal(err)
}
f, err = Decode(frame)
if err != nil {
log.Fatal(err)
}
var back GlobalPositionInt
if err := Unmarshal(f.Payload, &back); err != nil {
log.Fatal(err)
}
fmt.Printf("GLOBAL_POSITION_INT: payload %d bytes, sent %d, frame %d bytes, round trip equal: %t\n",
binary.Size(pos), len(f.Payload), len(frame), back == pos)
}0x6f91 is the catalogued check value of CRC-16/MCRF4XX for "123456789". The frame is 21 bytes: fd, len 09, two zero flag bytes, seq 00, sysid 01, compid 01, msgid 00 00 00, the payload with custom_mode 04 00 00 00 first, then type 02, autopilot 03, base_mode 81, system_status 04 and version 03, and the CRC 0x5603 sent as 03 56. Flipping the armed bit makes the receiver compute 0x7b6d instead, so the frame is dropped rather than reported as disarmed. A receiver with CRC_EXTRA 51 computes 0x478a and rejects even the intact frame. The hovering GLOBAL_POSITION_INT sends 18 of its 28 payload bytes: the zero velocities and heading and the two zero high bytes of relative_alt (10000 mm) are trimmed, and zero-extension restores an identical struct.
What the CRC does not protect
A CRC detects accidental corruption, not tampering: anyone can compute a valid checksum. MAVLink 2 signing sets incompat flag 0x01 and appends 13 bytes: a link id, a 48-bit timestamp in 10-microsecond units since 1 January 2015 that must increase on each link, and a 48-bit signature, the first six bytes of SHA-256 over a 32-byte secret key followed by the header, payload, CRC, link id and timestamp. Receivers reject bad signatures and stale timestamps, which blocks forged and replayed commands. The key is shared out of band, typically over a wired connection, and signing does not encrypt: telemetry remains readable to anyone listening on the link.
Fly it in GopherForge
This program uses only the standard library. In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay), and tap Run; there is no replay because it never calls sim.Save. To feed it simulator data, fly a drone in a sim.Run loop and, each time d.Telemetry().Time changes, build a GLOBAL_POSITION_INT from the report (latitude and longitude from the position as in the coordinates lesson, velocity in cm/s north, east and down) and encode one frame per report.
TAKE THIS WITH YOU
A MAVLink v2 frame is a 10-byte header, a payload of size-ordered little-endian fields with trailing zeros removed, and a CRC-16/MCRF4XX that ends with the message's CRC_EXTRA. Corrupted bytes and mismatched definitions both fail the CRC; only signing protects against forgery.
Check your understanding
Intact frames of one message type fail the CRC at a receiver while every other message passes. What does the CRC_EXTRA seed reveal here?
Go to the source
Progress stays in this browser. No account needed.