GUIDE · GO DRONES · 34 MIN READ
Drone telemetry in Go: MAVLink 2 frames, heartbeats, link loss and failsafe tests
MAVLink 2 telemetry in Go: frames, CRC_EXTRA, truncation, resync after garbage, heartbeat link-loss alarms and deterministic failsafe tests.
Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

What this edition tested
A ground station is mostly a parser with opinions. It reads bytes from a radio, decides which of them are frames, decides whether the vehicle is still there, and tells an operator when something needs attention. Each decision can be wrong in a way that appears only in the field: a checksum that passes on the bench and fails against real firmware, a parser that loses the frames after one corrupted byte, a link monitor that never fires because position messages keep arriving, or an alarm that expects a return to launch the vehicle was never configured to fly.
This is the 26 November 2026 edition, researched and first published on 3 December 2026. It covers MAVLink 2 telemetry for civilian and educational ground-station software: decoding, link supervision and the alarms an operator sees. The code reads telemetry and never commands a vehicle. Everything below was tested in an original standard-library lab with Go 1.27.3 on darwin/arm64. Go 1.27.4, released on 10 November 2026 with security fixes to cgo, the go command, the compiler, the linker and net/http, is the current patch release listed on go.dev; the lab was not re-run with it. The lab passed go vet ./..., gofmt -l . with no output and go test -race -count=3 ./..., and a 60-second fuzzing run of its parser found no failure.
The tests show that the lab's encoder produces byte-identical frames to github.com/bluenviron/gomavlib/v4 v4.0.2 for HEARTBEAT, SYS_STATUS and GLOBAL_POSITION_INT; that the CRC_EXTRA values 50, 124 and 104 follow from the XML field definitions; that the stream parser recovers every valid frame after garbage, a bad checksum, a corrupted length byte, an unknown message, an unsupported header flag or a signed frame, and gives the same result for every split of a test stream; that heartbeat loss is detected at exact times on an injected clock and inside a testing/synctest bubble; and that a deterministic simulated copter on a lossy two-way link produces the expected alarm timeline for an outage, a disabled failsafe and a draining battery. The simulation also exposed a trade-off that is easy to miss, covered in its own section: a single corrupted length byte can stall a quiet link for longer than a failsafe timeout.
The protocol is taught step by step in the Drones with Go course, whose exercises fly a deterministic simulator. This guide assumes you know what a flight controller and a ground station are, and concentrates on the parts that fail in production.
A MAVLink 2 frame, byte by byte
The serialization page on mavlink.io defines the format on the wire. A MAVLink 2 frame starts with the marker 0xFD, followed by nine header bytes: the payload length (0 to 255), incompat_flags, compat_flags, a sequence number, the sender's system ID and component ID, and a 24-bit message ID sent low byte first. The payload follows, then a two-byte checksum, low byte first. A signed frame ends with a 13-byte signature. The shortest frame is 12 bytes and the longest, signed with a full payload, is 280. Multi-byte fields are little-endian throughout. MAVLink 1 frames start with 0xFE and have a shorter header with an 8-bit message ID; the lab treats them as noise, which is only acceptable when you know every sender speaks MAVLink 2.
The two flag bytes behave differently. A receiver may ignore compat_flags bits it does not understand, but it must discard a frame whose incompat_flags contain a bit it does not understand, because such a bit can change the frame's layout. The serialization page still lists one incompatibility flag, 0x01 for a signed frame. In practice that list is now incomplete. Pymavlink pull request #1229, merged on 26 September 2026, implements 32-bit system IDs with two more flags: 0x02 widens the source system ID to four bytes, and 0x04 adds a four-byte target system ID after the message ID. Headers then measure 10, 13, 14 or 17 bytes including the marker, and a signed frame can reach 287 bytes. The C headers in mavlink/c_library_v2, regenerated the next day, define all three flags. A parser that implements only 0x01 must drop frames carrying the others, which the lab does and tests. Traffic whose system IDs fit in one byte keeps the standard framing.
The sequence number belongs to the sending component and increases by one with every frame it sends, so a receiver can count gaps to estimate loss. System ID 0 is the broadcast address and is not valid as a sender. By convention autopilots take system IDs counting up from 1, and ground stations count down from 255.
Once the payload is in wire order, encoding is short:
// AppendFrame appends a MAVLink 2 frame carrying payload to dst. Trailing
// zero bytes are truncated, as MAVLink 2 requires, but the first payload byte
// is always sent.
func AppendFrame(dst []byte, h Header, msgID uint32, payload []byte, crcExtra byte) []byte {
if len(payload) > MaxPayloadLen {
panic(fmt.Sprintf("dronelink: payload of %d bytes", len(payload)))
}
n := len(payload)
for n > 1 && payload[n-1] == 0 {
n--
}
start := len(dst)
dst = append(dst, STX, byte(n), 0, 0, h.Seq, h.SysID, h.CompID,
byte(msgID), byte(msgID>>8), byte(msgID>>16))
dst = append(dst, payload[:n]...)
sum := frameChecksum(dst[start+1:], crcExtra)
return binary.LittleEndian.AppendUint16(dst, sum)
}The checksum covers the bytes after the marker up to the end of the payload, plus one more byte that never travels: the message's CRC_EXTRA. The next two sections explain where the payload order and that byte come from.
Wire order is not XML order
MAVLink does not describe a message inside the frame. Sender and receiver must agree on the field order, and that order is not the order in the XML definition. The serialization page specifies a stable sort by the size of each field's type: 8-byte types first, then 4-byte, 2-byte and 1-byte types, keeping the XML order among fields of equal size. Arrays sort by their element type, not their total size. MAVLink 2 extension fields are the exception: they follow the base fields in XML order and are never reordered.
The three messages in the lab cover the range. HEARTBEAT, message 0 in minimal.xml, declares type, autopilot, base_mode, custom_mode, system_status and mavlink_version, but custom_mode is its only 4-byte field, so it is sent first. SYS_STATUS, message 1 in common.xml, declares battery_remaining seventh; as the only 1-byte base field it is sent last of the 31 base bytes, followed by three 4-byte extension fields. GLOBAL_POSITION_INT, message 33, is already sorted: a 4-byte boot time in milliseconds, latitude and longitude in degE7, two altitudes in millimetres, three 2-byte velocities in cm/s and a 2-byte heading in centidegrees. In the current repository it is defined in standard.xml, which common.xml includes.
The lab's HEARTBEAT encoder makes the reordering visible:
// Heartbeat is HEARTBEAT (#0). In the XML custom_mode is the fourth field,
// but on the wire it comes first: it is the only 4-byte field.
type Heartbeat struct {
Type, Autopilot, BaseMode uint8
CustomMode uint32
SystemStatus uint8
MavlinkVersion uint8
}
func (Heartbeat) MsgID() uint32 { return MsgIDHeartbeat }
func (m Heartbeat) AppendPayload(b []byte) []byte {
b = binary.LittleEndian.AppendUint32(b, m.CustomMode)
return append(b, m.Type, m.Autopilot, m.BaseMode, m.SystemStatus, m.MavlinkVersion)
}The lab's WireOrder function applies the rule to field lists copied from the XML, and a test checks the result against the hand-written encoders: HEARTBEAT starts with custom_mode, and SYS_STATUS ends its base fields with battery_remaining. Writing fields in declaration order is the classic mistake in hand-rolled MAVLink code, and whether anything catches it depends on where the byte described next comes from.

CRC_EXTRA catches mismatched definitions
The checksum is CRC-16/MCRF4XX, which MAVLink's sources call X.25: polynomial 0x1021 processed bit-reflected, initial value 0xFFFF, no final XOR. The CRC catalogue gives its check value for the ASCII string 123456789 as 0x6F91. A lab test asserts that value, and gomavlib's x25 package returns it too. The lab uses the byte-wise form from checksum.h in the MAVLink C library:
// crcAccumulate adds one byte to a CRC-16/MCRF4XX checksum. It is the
// byte-wise form from MAVLink's checksum.h: polynomial 0x1021 processed
// bit-reflected, initial value 0xFFFF and no final XOR.
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 continues the checksum crc over data. Start from 0xFFFF.
func CRC16(crc uint16, data []byte) uint16 {
for _, b := range data {
crc = crcAccumulate(crc, b)
}
return crc
}CRC_EXTRA is one byte per message, derived from its definition and added to the checksum after the payload. The code generator computes it as a CRC over the message name and a space, then the type and name of each base field in wire order, each followed by a space, plus the array length for arrays, and folds the 16-bit result to 8 bits by XORing its two halves. Extension fields are left out, so adding one does not change the value. The lab reproduces the calculation:
// CRCExtra computes a message's CRC_EXTRA byte the way the MAVLink generator
// does: a CRC over "NAME " and then "type name " for each base field in wire
// order (plus the array length for arrays), folded to one byte.
func CRCExtra(name string, base []Field) byte {
crc := CRC16(crcInit, []byte(name+" "))
for _, f := range WireOrder(base) {
crc = CRC16(crc, []byte(f.Type+" "+f.Name+" "))
if f.ArrayLen > 0 {
crc = crcAccumulate(crc, byte(f.ArrayLen))
}
}
return byte(crc) ^ byte(crc>>8)
}Given the definitions from the XML, it returns 50 for HEARTBEAT, 124 for SYS_STATUS and 104 for GLOBAL_POSITION_INT. Those are the values in the generated C headers, such as MAVLINK_MSG_ID_HEARTBEAT_CRC, and in gomavlib's dialect. A generator that sorted wrongly would compute its seed from its own order: over HEARTBEAT's fields in XML order the same calculation gives 155, and every frame it produced would fail at a correct receiver. That is why the serialization page computes CRC_EXTRA after reordering, and why a changed definition becomes a checksum failure instead of silently wrong numbers.
The protection has a gap for hand-written code. The checksum covers the bytes as sent, so an encoder that writes HEARTBEAT in XML order but copies 50 from a table produces frames that pass every check, and the receiver decodes custom_mode from the wrong bytes. TestWrongOrderWithCopiedSeedPassesTheChecksum builds exactly that frame: it is accepted and decodes with a custom_mode of 58786562. Compare encoded frames with an independent implementation, as the lab does with gomavlib below, rather than trusting the checksum to find layout errors.
The consequence for parsers is easy to miss. A receiver can only check a frame whose CRC_EXTRA it knows. A frame with an unknown message ID cannot be told apart from noise that happens to start with 0xFD, so a ground station should carry the CRC_EXTRA table for every message its vehicles send, even if it decodes only a few of them. The lab knows three messages and rejects the rest; a production station would generate the full table from the same XML its firmware was built from.
Truncated payloads and extension fields
MAVLink 2 senders must remove zero bytes from the end of the serialized payload and set the length byte to match. The first payload byte is always sent, even when the whole payload is zero. Receivers zero-extend what arrives to the length they know before decoding. Because of field reordering, truncation usually removes the smallest fields or the extension fields. The golden frames in the lab show both cases: a SYS_STATUS whose extension fields are zero travels with a 31-byte payload instead of 43, and a GLOBAL_POSITION_INT with zero vertical speed and heading travels with 24 bytes instead of 28. The serialization page also requires receivers to decode frames from non-compliant senders that leave trailing zeros in place.
The opposite case matters for fleets with mixed firmware. A vehicle built against a newer definition can send a longer payload, because new fields are appended as extensions, and since CRC_EXTRA ignores extensions its frames still pass the checksum. A receiver should decode the fields it knows and ignore the rest:
// A newer definition may append extension fields. CRC_EXTRA ignores them, so
// the frame still checks out; this program reads the fields it knows.
func TestLongerPayloadFromNewerDefinition(t *testing.T) {
payload := goldenSysStatus.AppendPayload(nil)
payload = append(payload, 0xAA, 0xBB, 0xCC, 0xDD) // a field we do not know
b := AppendFrame(nil, Header{SysID: 1, CompID: 1}, MsgIDSysStatus, payload, 124)
p := NewParser(Common)
frames := p.Feed(b)
if len(frames) != 1 || len(frames[0].Payload) != 47 {
t.Fatalf("got %d frames", len(frames))
}
if m, _ := Decode(frames[0]); m != goldenSysStatus {
t.Fatalf("decoded %+v", m)
}
strict := NewParser(Common)
strict.StrictLength = true
if frames := strict.Feed(b); len(frames) != 0 || strict.Stats().BadLength != 1 {
t.Fatalf("StrictLength accepted a 47-byte SYS_STATUS: %d frames, %+v", len(frames), strict.Stats())
}
}Decode copies the received payload into a zeroed buffer of the known length, which handles both directions: missing bytes read as zero, and surplus bytes are never looked at. The second half of the test shows the price of the StrictLength option discussed later, which rejects this legitimate frame.
gomavlib or a small decoder of your own
As of 3 December 2026 the current major version of github.com/bluenviron/gomavlib is v4, and the Go module proxy's latest version is v4.0.2, published on 22 November 2026. v4.0.0 appeared on 1 June 2026, and the older /v3 path ends at v3.3.5. Its README lists serial, UDP, TCP and custom transports; MAVLink 1 and 2 with checksums, truncation, signatures and extensions; ready-to-use standard dialects such as common and ardupilotmega, plus a generator for custom XML definitions; routing without decoding; and telemetry logs. It asks for Go 1.26 or newer.
The lab's golden frames come from gomavlib. A throwaway module outside the lab encoded five test messages with its common dialect and printed them as hex. The lab's encoder produces the same bytes, its decoder reads them back into the same values, and gomavlib's dialect reports the same CRC_EXTRA values. Keeping that program out of the lab keeps the lab free of dependencies, while the vectors keep testing it:
// Golden frames written by github.com/bluenviron/gomavlib/v4 v4.0.2 with its
// common dialect, in a separate throwaway module (see the checks file).
var golden = map[string]string{
"heartbeat": "fd090000000101000000030000000203810403f692",
"sys_status": "fd1f0000010101010000000000000000000000000000fa00b83de2040000000000000000000000004c26f5",
"position": "fd1c000002010121000040e201004c52401c44f4170540720700e02e00009600ecffddff282383f9",
"position_trunc": "fd18000003010121000028e601004c52401c44f4170540720700e02e00009600ecff8a9e",
"gcs_heartbeat": "fd09000007ffbe0000000000000006080004037efa",
}Two details of v4.0.2 are worth knowing before you adopt it for a ground station. First, its Node sends heartbeats every 5 seconds unless you set HeartbeatPeriod, and ArduPilot's GCS failsafe triggers after 5 seconds without a ground-station heartbeat by default. Set HeartbeatPeriod: time.Second, the 1 Hz that mavlink.io describes as typical. Second, its frame.Reader reads a frame's full claimed length before checking the checksum, and returns messages that are not in its dialect as message.MessageRaw without checking them. The second behaviour suits a router, and mavlink.io asks routers to forward messages they cannot process. The first one has a cost: in the throwaway check, a HEARTBEAT whose length byte was changed from 9 to 60 made the reader consume the GLOBAL_POSITION_INT behind it and part of the following SYS_STATUS. It reported one checksum error and then one invalid-magic-byte error per leftover byte, and neither frame was delivered.
Write your own decoder when you consume a handful of messages, want no dependencies, or need exact control over resynchronisation and its tests. Use gomavlib when you need many messages, signing, MAVLink 1, transports or routing; its standard dialects are generated code, and it has shipped three v4 releases between June and November 2026. Either way, the tests in this guide apply: feed the parser corrupted and split input and check what comes out.
Resynchronising after garbage and split reads
A serial port or a UDP socket hands over whatever bytes have arrived. A frame may be split across reads, and a radio link adds noise, partial frames after a reconnect and the occasional flipped bit. The lab's parser keeps a buffer, appends each read to it and walks it with five rules:
- Find the next 0xFD; everything before it is discarded.
- Wait until the 10-byte header is complete.
- Reject the candidate if
incompat_flagshas any bit other than 0x01, or if its message ID has no known CRC_EXTRA. - Wait until the claimed frame is complete, then verify the checksum.
- On any rejection, drop only the 0xFD and resume scanning at the next byte.
The last rule is the one that matters. A corrupted length byte makes a candidate claim bytes that belong to the frames after it. A parser that skips the whole claimed frame on a bad checksum loses those frames with it; one that skips a single byte finds them again. When a damaged frame is rejected, its own payload may contain 0xFD bytes, which become candidates in turn, but each must carry a known message ID and pass a 16-bit checksum before it is accepted.
// Feed adds data and returns the frames it completes. A candidate that fails
// any check costs only its STX byte: scanning resumes at the next byte, so a
// corrupted length byte cannot swallow the frames that follow it. It can
// delay them, until enough bytes arrive to show that its checksum is wrong.
func (p *Parser) Feed(data []byte) []Frame {
p.buf = append(p.buf, data...)
var out []Frame
i := 0
for {
j := bytes.IndexByte(p.buf[i:], STX)
if j < 0 {
p.stats.Discarded += len(p.buf) - i
i = len(p.buf)
break
}
p.stats.Discarded += j
i += j
c := p.buf[i:]
if len(c) < HeaderLen {
break // wait for the rest of the header
}
flags := c[2]
if flags&^IFlagSigned != 0 { // unknown flag: the layout is unknown too
p.stats.BadFlags++
p.stats.Discarded++
i++
continue
}
msgID := uint32(c[7]) | uint32(c[8])<<8 | uint32(c[9])<<16
spec, known := p.dialect[msgID]
if !known { // no CRC_EXTRA, so no way to tell a frame from noise
p.stats.UnknownID++
p.stats.Discarded++
i++
continue
}
if p.StrictLength && int(c[1]) > spec.Len {
p.stats.BadLength++
p.stats.Discarded++
i++
continue
}
n := HeaderLen + int(c[1]) + ChecksumLen
if flags&IFlagSigned != 0 {
n += SignatureLen
}
if len(c) < n {
break // wait for the rest of the frame
}
end := HeaderLen + int(c[1])
sum := binary.LittleEndian.Uint16(c[end:])
if frameChecksum(c[1:end], spec.CRCExtra) != sum {
p.stats.BadCRC++
p.stats.Discarded++
i++
continue
}
if flags&IFlagSigned != 0 { // well formed, but signing is out of scope
p.stats.Signed++
p.stats.Discarded += n
i += n
continue
}
out = append(out, Frame{
IncompatFlags: flags, CompatFlags: c[3],
Header: Header{Seq: c[4], SysID: c[5], CompID: c[6]},
MsgID: msgID,
Payload: bytes.Clone(c[HeaderLen:end]),
Checksum: sum,
})
p.stats.Frames++
i += n
}
p.buf = append(p.buf[:0], p.buf[i:]...)
return out
}Every decision depends only on bytes already received, never on how they were split, so the same input gives the same frames and counters however reads are sized. TestParserSplitReads checks this at every split point of a stream that contains a stray 0xFD, a frame whose length was changed from 9 to 60, two bytes of noise and three valid frames, and once more feeding one byte at a time. The table test covers each rejection path, and in the corrupted-length case it receives the GLOBAL_POSITION_INT and SYS_STATUS behind the damaged frame. Signed frames are consumed whole once their checksum verifies, so the stream stays in step, and then dropped: a signature that has not been verified authenticates nothing. The buffer never reaches 280 bytes, because a candidate either completes by then or is rejected.
Reading from an io.Reader follows the contract in the io documentation: process the n bytes a call returned before looking at its error.
// ReadFrames reads r until it fails, feeding each read to p and sending the
// frames it completes to out. Serial ports and sockets return whatever bytes
// have arrived, so a frame is often split across reads. It returns nil at EOF.
func ReadFrames(ctx context.Context, r io.Reader, p *Parser, out chan<- Frame) error {
buf := make([]byte, 512)
for {
n, err := r.Read(buf)
for _, f := range p.Feed(buf[:n]) { // use n bytes before looking at err
select {
case out <- f:
case <-ctx.Done():
return ctx.Err()
}
}
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
}
}testing/iotest supplies awkward readers for free. OneByteReader returns one byte per call, HalfReader returns half of what was asked for, and DataErrReader returns the final data together with io.EOF. The lab runs ReadFrames over all three and gets the same frames every time.

Fuzzing the parser
A byte-stream parser is a natural fuzz target: its input is untrusted and its properties are easy to state. The lab's FuzzParser takes arbitrary bytes and a split point. Its seeds are the golden frames on their own, frames surrounded by garbage and stray 0xFD bytes, a frame with a corrupted length, a truncated frame and empty input. For every input it checks that each delivered frame occurs verbatim in the input, carries a valid checksum and decodes; that delivered, discarded and buffered bytes add up to the input length; that the buffer stays under 280 bytes; and that feeding the input in two pieces gives the same frames and counters as feeding it whole:
f.Fuzz(func(t *testing.T, data []byte, split uint16) {
whole := NewParser(Common)
got := whole.Feed(data)
frameBytes := 0
for _, fr := range got {
raw := fr.AppendTo(nil)
frameBytes += len(raw)
if !bytes.Contains(data, raw) {
t.Fatalf("frame %x is not in the input", raw)
}
if fr.Checksum != frameChecksum(raw[1:len(raw)-2], Common[fr.MsgID].CRCExtra) {
t.Fatalf("delivered a frame with a bad checksum: %x", raw)
}
if _, err := Decode(fr); err != nil {
t.Fatalf("delivered an undecodable frame: %v", err)
}
}
st := whole.Stats()
if frameBytes+st.Discarded+whole.Buffered() != len(data) {
t.Fatalf("%d frame bytes + %d discarded + %d buffered != %d input bytes",
frameBytes, st.Discarded, whole.Buffered(), len(data))
}
if whole.Buffered() >= MaxFrameLen {
t.Fatalf("buffered %d bytes", whole.Buffered())
}
i := int(split) % (len(data) + 1)
two := NewParser(Common)
got2 := append(two.Feed(data[:i]), two.Feed(data[i:])...)
if !framesEqual(got, got2) || two.Stats() != st || two.Buffered() != whole.Buffered() {
t.Fatalf("split at %d changed the result: %d vs %d frames", i, len(got2), len(got))
}
})go test -run '^$' -fuzz=FuzzParser -fuzztime=60s ran once on an Apple M4 with 10 CPUs: about 20.7 million executions, 42 new interesting inputs on top of the 9 seeds, and no failure. A plain go test runs only the seeds, so they act as regression tests in every build. When fuzzing finds a failure, Go writes the input under testdata/fuzz/FuzzParser, and committing that file keeps it in the seed set for good. The guide to fuzzing parsers covers corpus management in more depth.
A corrupted length byte can stall a quiet link
Skipping one byte at a time recovers every following frame, but not at once. When a length byte is corrupted upwards, the parser cannot know the candidate is bad until enough bytes have arrived to check its checksum, up to 280 bytes from the marker. Any parser that honours the length byte waits the same way. On a busy downlink, where position alone arrives ten times a second, the wait is a fraction of a second. On a quiet link it is much longer. The lab's station sends nothing but a 21-byte HEARTBEAT each second, so a HEARTBEAT whose length byte reads 255 instead of 9 holds the receiving parser for about twelve seconds.
The simulation described below makes this concrete. Each direction drops 5% of frames, flips one byte in 2% and puts random garbage before 2%, and the simulated vehicle parses the uplink with the lab's parser and runs a 5-second ground-station failsafe. Over 200 seeded two-minute flights with no outage, 14 vehicles flew a failsafe RTL anyway. In the one pinned as a test, seed 2, the station heartbeat sent at 96.5 s arrived with its length byte changed from 9 to 183, and the vehicle's parser was still waiting for the rest of that frame when its 5-second timeout expired at 100.51 s.
The lab's mitigation is an option that rejects a candidate claiming more payload than the known definition, before waiting for any bytes:
// Parser finds MAVLink 2 frames in a byte stream that may contain garbage
// and may arrive in pieces of any size. It is not safe for concurrent use.
type Parser struct {
// StrictLength rejects a frame that claims a longer payload than the
// dialect's definition, instead of waiting for the bytes. It stops a
// corrupted length byte from stalling the stream, but it also drops
// frames from senders whose definitions gained extension fields.
StrictLength bool
dialect Dialect
buf []byte
stats Stats
}With StrictLength on, the same 200 flights produced one failsafe. The other 13 had all been triggered the same way as seed 2, by a station heartbeat with a corrupted length byte. The remaining one, seed 150, lost four consecutive station heartbeats and received the fifth corrupted: a real loss of link by any definition. The option has the cost its comment states, and TestLongerPayloadFromNewerDefinition demonstrates it: frames from senders whose definitions have grown extension fields since yours were generated are dropped. The MAVLink C library offers a similar trade as the compile-time option MAVLINK_CHECK_MESSAGE_LENGTH, which rejects a length below a message's minimum or above its maximum; since MAVLink 2 truncation makes shorter payloads legal, read that code before enabling it. Turn length checking on only when your definitions are at least as new as your vehicles', and update the definitions together with firmware.
Heartbeats decide whether the link is up
The MAVLink heartbeat page leaves the rate and the number of misses to each channel, and describes common practice on RF links: publish at 1 Hz and consider a system disconnected after four or five missed heartbeats. It also asks components not to send heartbeats from a thread that cannot see the state of the rest of the component, so that a heartbeat means the component is working. That is why the lab's monitor accepts only HEARTBEAT as proof of life. A position stream from a component whose main loop has hung would otherwise keep the link green. TestPositionsDoNotKeepTheLinkAlive sends GLOBAL_POSITION_INT at 10 Hz with no heartbeats and expects LINK_LOST at 5.1 s.
The lab's policy marks the link degraded after 2.5 s without a heartbeat, two missed at 1 Hz, so a single lost packet does not alarm the operator, and lost after 5 s. A heartbeat whose autopilot field is MAV_AUTOPILOT_INVALID (8) comes from a ground station, gimbal or other component that is not a flight controller; mavlink.io recommends exactly that check to recognise an autopilot, so those heartbeats never create a vehicle. Silence produces no frames, so the check has to run on a timer:
// Tick checks every vehicle's heartbeat age at now. Call it on a timer: a
// silent link produces no frames, so Handle alone can never notice it.
func (g *GroundStation) Tick(now time.Time) []Alarm {
var out []Alarm
p := g.policy
for _, id := range slices.Sorted(maps.Keys(g.vehicles)) {
v := g.vehicles[id]
age := now.Sub(v.lastHeartbeat)
switch {
case v.link != linkLost && age > p.LostAfter:
v.link = linkLost
out = append(out, Alarm{now, id, LinkLost, Critical, fmt.Sprintf("no heartbeat for %v", age)})
case v.link == linkUp && age > p.DegradedAfter:
v.link = linkDegraded
out = append(out, Alarm{now, id, LinkDegraded, Warning, fmt.Sprintf("no heartbeat for %v", age)})
}
if v.link == linkLost && !v.expectFailsafe && p.VehicleFailsafeAfter > 0 && v.armed &&
age > p.VehicleFailsafeAfter+p.GCSHeartbeat {
v.expectFailsafe = true
out = append(out, Alarm{now, id, FailsafeExpected, Warning,
"vehicle should now be flying its link-loss action"})
}
}
return out
}Three habits keep the monitor honest. Take time.Now() when a frame arrives and measure ages with Sub: Go uses the monotonic clock reading when both times carry one, so wall-clock adjustments neither fire nor hide alarms, and the vehicle's own time_boot_ms says nothing about the radio. Count sequence gaps per component with uint8 arithmetic, so that 255 followed by 0 is not a gap, and remember that gaps of 256 frames or more wrap and are undercounted. And watch time_boot_ms for a decrease: the routing guide names a decrease in SYSTEM_TIME.time_boot_ms as the sign of a reboot, and the same field in GLOBAL_POSITION_INT serves a station that does not receive SYSTEM_TIME.
Tick and Handle take the time as an argument, so most tests need no clock at all. TestLinkLossExpectsTheVehicleToReturn delivers heartbeats at 0 to 9 s and ticks every 100 ms; it sees LINK_DEGRADED at 11.6 s, LINK_LOST at 14.1 s and FAILSAFE_EXPECTED at 15.1 s on every run. The goroutine that drives the station in production calls time.Now and uses a time.Ticker, and is tested inside a testing/synctest bubble, where both run on a fake clock that advances only when every goroutine in the bubble is durably blocked. Go 1.27 adds synctest.Sleep, which is time.Sleep followed by synctest.Wait:
// Inside a synctest bubble time.Now, tickers and sleeps use a fake clock
// that advances only when every goroutine in the bubble is durably blocked,
// so 20 simulated seconds pass without real waiting. synctest.Sleep (new in
// Go 1.27) is time.Sleep followed by synctest.Wait: Run has handled
// everything due before the test goroutine continues.
func TestRunOnAFakeClock(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
start := time.Now()
in, out := make(chan Frame), make(chan Alarm, 16)
done := make(chan error, 1)
go func() { done <- NewGroundStation(ArduCopterPolicy()).Run(ctx, in, 100*time.Millisecond, out) }()
for s := range 10 { // heartbeats at 0..9 s, then silence
in <- frameOf(t, uint8(s), heartbeatIn(CopterModeAuto))
synctest.Sleep(time.Second)
}
synctest.Sleep(10 * time.Second)
cancel()
<-done
close(out)
var got []string
for a := range out {
got = append(got, fmt.Sprintf("%v %s", a.At.Sub(start), a.Kind))
}
want := []string{"11.6s LINK_DEGRADED", "14.1s LINK_LOST", "15.1s FAILSAFE_EXPECTED"}
if !slices.Equal(got, want) {
t.Fatalf("alarms %v, want %v", got, want)
}
})
}Twenty seconds of radio silence pass without real waiting (the test reports 0.00s), and the alarm times are exact. A second test runs the whole pipeline in a bubble: a goroutine writes frames into an io.Pipe seven bytes at a time with noise in front, ReadFrames parses them, and Run raises the same three alarms at the same instants. The synctest guide explains what counts as durably blocked.
Failsafe decisions the station can check
While the link is down the station cannot command anything, so the vehicle's onboard failsafe is the authority. The station's job is to know what the vehicle was configured to do, tell the operator what to expect, and check it when telemetry returns. The details differ by flight stack, and they are parameters rather than constants:
- ArduPilot Copter's GCS failsafe triggers when no heartbeat from the ground station has arrived for
FS_GCS_TIMEOUTseconds, 5 by default, and stays inactive if no ground station ever connected.FS_GCS_ENABLEselects the action: 0 disables it, 1 switches to RTL, or to Land when the position is not usable, and other values select SmartRTL, Land, a DO_LAND_START mission or Brake. Bit 1 ofFS_OPTIONSlets an AUTO mission continue instead. When the heartbeat returns, the copter stays in its failsafe mode; it does not go back to the mode it was flying before. - PX4's data link loss failsafe triggers after
COM_DL_LOSS_Tseconds, 10 by default. Its action,NAV_DLL_ACT, defaults to 0, disabled; the other values are Hold, Return, Land, Terminate and Disarm, andCOM_DLL_EXCEPTexempts chosen modes.
The flight mode arrives in HEARTBEAT's custom_mode, whose meaning depends on the autopilot. ArduPilot's developer documentation says the vehicle reports its mode there once a second; for Copter the numbers are the COPTER_MODE enum in ardupilotmega.xml, where AUTO is 3, RTL 6, LAND 9 and SMART_RTL 21. The lab's policy for an ArduPilot Copter with FS_GCS_ENABLE=1:
// ArduCopterPolicy matches an ArduPilot Copter with FS_GCS_ENABLE=1 (RTL,
// or Land without a position estimate) and the default FS_GCS_TIMEOUT of 5 s.
func ArduCopterPolicy() Policy {
return Policy{
DegradedAfter: 2500 * time.Millisecond,
LostAfter: 5 * time.Second,
VehicleFailsafeAfter: 5 * time.Second,
GCSHeartbeat: time.Second,
FailsafeModes: []uint32{CopterModeRTL, CopterModeLand, CopterModeSmartRTL},
BatteryLow: 30,
BatteryCrit: 20,
Hysteresis: 3,
}
}Once the link has been silent for the vehicle's timeout plus one station heartbeat period, the station raises FAILSAFE_EXPECTED; the extra period covers the vehicle having heard the station up to one heartbeat after the station last heard the vehicle. When heartbeats return, the reported mode decides the outcome:
if v.expectFailsafe {
if slices.Contains(g.policy.FailsafeModes, hb.CustomMode) || !hb.Armed() {
out = append(out, Alarm{now, sysID, FailsafeConfirmed, Info,
"vehicle reports " + ModeName(hb.Autopilot, hb.CustomMode)})
} else {
out = append(out, Alarm{now, sysID, FailsafeNotObserved, Critical,
"link was lost but vehicle still reports " + ModeName(hb.Autopilot, hb.CustomMode)})
}
}A disarmed vehicle counts as handled, because a copter that landed during the outage has done its job. The critical branch is the one worth testing: the operator believes the drone is coming home while it is still flying its mission. Two easy ways to get there are a policy copied from another airframe and a PX4 vehicle whose NAV_DLL_ACT is still at its default, disabled. Build the policy from parameters read from the vehicle, not from defaults in your code, and show the operator which action the station expects.
A deterministic drone on a lossy link
Unit tests check decisions one at a time; a simulation checks them together, with the timing a flight produces. The lab's RunSim advances in 10 ms steps and never reads the clock. A copter flies a 100 m square at 5 m/s and 20 m in AUTO, sends HEARTBEAT and SYS_STATUS at 1 Hz and GLOBAL_POSITION_INT at 10 Hz, and behaves like the ArduPilot description above: RTL after 5 s without a station heartbeat once one has been heard, RTL at a battery threshold, then Land and disarm at home. The station heartbeats at 1 Hz, half a second out of phase. The link applies per-frame loss, corruption, garbage and outage windows in both directions, each drawn from its own seeded math/rand/v2 PCG stream, and the station reads the downlink in random chunks.
A 20-second outage starting at 40 s gives this timeline, pinned as a test:
func TestOutageExpectsRTL(t *testing.T) {
cfg := baseFlight()
cfg.Outages = []Outage{{From: 40 * time.Second, To: 60 * time.Second}}
res := RunSim(cfg)
checkTimeline(t, res.Timeline, []string{
"41.51s LINK_DEGRADED no heartbeat for 2.51s",
"44.01s LINK_LOST no heartbeat for 5.01s",
"44.51s vehicle AUTO -> RTL (GCS failsafe)",
"45.01s FAILSAFE_EXPECTED vehicle should now be flying its link-loss action",
"60.00s LINK_RESTORED after 21s without heartbeat",
"60.00s MODE_CHANGED AUTO -> RTL",
"60.00s FAILSAFE_CONFIRMED vehicle reports RTL",
"69.81s vehicle RTL -> LAND (home reached)",
"70.00s MODE_CHANGED RTL -> LAND",
"89.81s vehicle landed and disarmed",
})
}Every line follows from the rules. The vehicle's last heartbeat before the outage left at 39 s, and the last station heartbeat the vehicle heard was the one at 39.5 s. With the vehicle's failsafe disabled, the same flight ends in FAILSAFE_NOT_OBSERVED at 60 s with critical severity.
Other scenarios pin the remaining decisions. A battery draining 0.8% per second with the vehicle set to RTL at 25% gives BATTERY_LOW at 86 s, the vehicle's switch to RTL at 93.76 s, MODE_CHANGED at the next heartbeat and BATTERY_CRITICAL at 100 s. The reported percentage jitters by a point; with hysteresis set to zero, the negative control raises BATTERY_LOW a second time, and with three points it fires once. ArduPilot's own battery failsafe latches harder: once triggered it cannot be reset until the autopilot reboots. A station heartbeat every 5 s, gomavlib's default, with one heartbeat lost sends the vehicle home at 15.51 s; at 1 s the same loss does nothing. On the noisy link from the stall section, seeds 1, 3 and 5 raise no critical alarm and accept no altered position, and the station's sequence-gap count equals exactly the number of frames the link dropped or corrupted. Changing the station's reads from up to 64 bytes to single bytes leaves the timeline unchanged.
The Drone flight template is a good place to rehearse the vehicle side of these ideas: its simulator adds wind, gusts and drag, and has its own low-battery and geofence failsafes.
Decimate the display, not the alarms
A browser or tablet does not need fifty position updates a second per vehicle, and a queue that buffers them all falls further behind with every slow repaint. There are two places to reduce the rate. At the source, MAV_CMD_SET_MESSAGE_INTERVAL (command 511) asks the vehicle to send a message at an interval in microseconds, with -1 to stop it and 0 for the default rate; mavlink.io documents it as the replacement for REQUEST_DATA_STREAM. At the station, keep only the latest value of each stream and release it at most once per interval:
// Coalescer keeps the latest frame of each stream and releases it at most
// once per interval. Nothing queues: a slow display sees fewer updates, never
// older ones, and memory is one slot per stream. Feed alarms from every
// frame, not from what the Coalescer releases.
type Coalescer struct {
Default time.Duration // interval for streams not in Interval
Interval map[uint32]time.Duration // per message ID; 0 releases every change
slots map[Key]*slot
}
// Offer replaces the stream's latest frame.
func (c *Coalescer) Offer(f Frame) {
if c.slots == nil {
c.slots = map[Key]*slot{}
}
k := Key{f.SysID, f.CompID, f.MsgID}
s := c.slots[k]
if s == nil {
s = &slot{}
c.slots[k] = s
}
s.frame, s.pending = f, true
}
// Poll returns, in a stable order, the latest frame of every stream that
// changed since it was last released and whose interval has passed.
func (c *Coalescer) Poll(now time.Time) []Frame {
var keys []Key
for k, s := range c.slots {
every, ok := c.Interval[k.MsgID]
if !ok {
every = c.Default
}
if s.pending && (!s.sent || now.Sub(s.last) >= every) {
keys = append(keys, k)
}
}
slices.SortFunc(keys, Key.compare)
out := make([]Frame, 0, len(keys))
for _, k := range keys {
s := c.slots[k]
out = append(out, s.frame)
s.pending, s.sent, s.last = false, true, now
}
return out
}Nothing queues, so a slow display sees fewer updates but never older ones, and memory is one slot per stream. In the lab, 101 positions offered at 50 Hz over two seconds come out as 9 releases, at 0, 250 and so on up to 2,000 ms, each newer than the last and ending with the final value, while heartbeats, configured with an interval of zero, pass on every change.
The rule that matters is where alarms come from. TestAlarmsDoNotWaitForTheDisplay feeds SYS_STATUS at 10 Hz with the battery falling half a point per frame. The display, at one update per second, shows 36% and then 31%; it never draws 30%. The alarm fires at 1.2 s, the time of the frame that crossed the threshold, because the station handles every frame and only the display is decimated.
Checklist for a telemetry link
Before a ground station is used on a real flight:
- Definitions: take field order, extension fields and CRC_EXTRA from the same XML as the vehicles' firmware. Test CRC_EXTRA against values computed from the definitions, and keep a table for every message your vehicles send.
- Encoding: serialize in wire order, truncate trailing zeros but keep the first payload byte, and compare a few frames with an independent implementation.
- Decoding: zero-extend short payloads, ignore surplus bytes from newer definitions, and drop frames with unknown
incompat_flagsbits, which now include 0x02 and 0x04. - Resynchronisation: on any rejected candidate skip one byte, not the claimed frame. Test every split point, run a fuzzer with properties, and decide deliberately whether length checking suits your fleet.
- Liveness: derive it from HEARTBEAT alone, timed on the monotonic clock at receipt; degraded after two missed heartbeats, lost after four or five.
- Your own heartbeat: send it at 1 Hz from the code that does the work, and set
HeartbeatPeriodif you use gomavlib'sNode. - Failsafes: mirror the vehicle's parameters in the station's policy, raise an expectation during the outage, and confirm the reported mode when the link returns.
- Alarms: compute them from every frame, add hysteresis to thresholds, and decimate only what is drawn.
- Signing: treat signed frames as unauthenticated unless you verify the signature with the shared key.
The lab is in the dronelink folder of this edition's downloadable archive. It needs Go 1.27 and nothing outside the standard library:
go vet ./...
go test -race -count=1 ./...
go test -run '^$' -fuzz=FuzzParser -fuzztime=60s .
DRONELINK_SWEEP=1 go test -run Sweep -v .Primary sources & editorial method
We checked these primary references on 3 December 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.
- MAVLink packet serialization
- MAVLink 2 overview
- MAVLink heartbeat/connection protocol
- MAVLink routing
- MAVLink message signing
- MAVLink minimal.xml messages (HEARTBEAT)
- MAVLink common.xml messages (SYS_STATUS, GLOBAL_POSITION_INT, MAV_CMD_SET_MESSAGE_INTERVAL)
- MAVLink ardupilotmega.xml messages (COPTER_MODE)
- MAVLink: how to request and stream messages
- mavlink/mavlink standard.xml
- MAVLink C library checksum.h
- MAVLink C library mavlink_helpers.h
- pymavlink pull request #1229: implement 32 bit system IDs
- gomavlib repository
- gomavlib v4 package documentation
- ArduPilot Copter GCS failsafe
- ArduPilot Copter battery failsafe
- ArduPilot: get and set flight mode
- PX4 safety configuration (failsafes)
- PX4 parameter reference
- CRC RevEng catalogue: 16-bit CRCs
- Go 1.27 release notes
- Go release history
- testing/synctest package
- testing/iotest package
- io package
- time package (monotonic clocks)
- Go fuzzing