← News & analysis

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.

An original turquoise rodent engineer at a field ground station receives a ribbon of glowing tiles from a distant quadcopter and sets a cracked tile aside.
Conceptual illustration for Drone telemetry in Go: MAVLink 2 frames, heartbeats, link loss and failsafe tests AI-generated conceptual illustration.

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.

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:

go
// 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.

A four-panel infographic headed frame, check, heartbeat and failsafe, summarising how a ground station decodes and supervises a drone telemetry link.
AI-generated conceptual illustration.

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:

go
// 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:

go
// 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:

go
// 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:

go
// 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_flags has 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.

go
// 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.

go
// 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.

A conveyor of sealed parcels passes a copper inspection gate; a damaged parcel is lifted off and the belt advances one notch so the next parcels continue.
When a candidate frame fails a check, the parser drops only its start byte and keeps scanning, so the intact frames behind it are still found. AI-generated conceptual illustration.

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:

go
	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.

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_TIMEOUT seconds, 5 by default, and stays inactive if no ground station ever connected. FS_GCS_ENABLE selects 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 of FS_OPTIONS lets 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_T seconds, 10 by default. Its action, NAV_DLL_ACT, defaults to 0, disabled; the other values are Hold, Return, Land, Terminate and Disarm, and COM_DLL_EXCEPT exempts 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:

go
// 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:

go
	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.

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:

go
// 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.

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.