Drone software: architecture, MAVLink and telemetry · 5 MIN READ
Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection
Decode a recorded MAVLink stream, measure per-message rates and gaps on the ground station's clock, interpret GLOBAL_POSITION_INT's scaled integers, and flag stale streams and a lost link.
A vehicle does not answer questions about its position; it streams messages at configured rates and the ground station keeps the latest value of each. That design is efficient on a narrow radio link, but it means the newest value you hold may be seconds old. A ground station that shows a position without knowing its age, or calls a link healthy because heartbeats still arrive, is behind many confusing incidents.
drones · A MAP OF THE IDEA
- Stamp frames on receipt
- Rate and gap per message
- Timeout per stream
- Heartbeat for link loss
Useful when
- Stale data is flagged even while heartbeats still arrive.
- Receipt timestamps expose radio buffering and bursts.
Watch out
- A heartbeat-only monitor misses a stalled data stream.
- Vehicle timestamps reset on reboot and drift from yours.
Implementation & operation cost: A small record per message type (count, last receipt, expected interval) and a periodic check that turns ages into alarms.
Streams and their rates
An autopilot streams a default set of messages on each link. To change a rate, send MAV_CMD_SET_MESSAGE_INTERVAL in a COMMAND_LONG with param1 the message id and param2 the interval in microseconds (-1 disables the stream, 0 restores the default) and wait for its COMMAND_ACK. To ask for the current rate, send MAV_CMD_REQUEST_MESSAGE with param1 244 and param2 the message id; the reply is MESSAGE_INTERVAL with message_id and interval_us, where -1 means disabled and 0 not available. ArduPilot also has per-port stream-rate parameters such as SR1_POSITION, and PX4 sets default rate profiles per MAVLink instance. Rates compete for bandwidth: a 57600-baud telemetry radio moves only a few kilobytes per second, so ask for what each consumer needs, not everything at 50 Hz.
GLOBAL_POSITION_INT, field by field
GLOBAL_POSITION_INT (#33) is the flight controller's fused position estimate, not raw GPS (GPS_RAW_INT carries the receiver's own solution). time_boot_ms is the vehicle's clock since boot; lat and lon are int32 in degE7, 1e-7 degree or about 1.1 cm; alt is millimetres above mean sea level and relative_alt millimetres above home; vx, vy and vz are int16 centimetres per second north, east and down, so a climb is a negative vz; hdg is centidegrees from 0 to 35999, with 65535 meaning unknown. Scaled integers keep full resolution in few bytes, and they are where bugs hide: millimetres treated as metres, vz read as climb, or lat and lon swapped.
Timestamp on receipt
time_boot_ms says when the vehicle made the estimate, on a clock that starts at boot, restarts after a reboot and drifts against yours. It cannot tell you how old the value is now, because radios buffer, retry and deliver in bursts. Stamp every frame with your own monotonic clock when it is complete (in Go, time.Now carries a monotonic reading and time.Since uses it) and compute ages, rates and gaps from those stamps. Keep time_boot_ms for ordering samples and for spotting a reboot, when it jumps backwards. The seq byte, counted per sender, shows frames lost on the link.
Rates, gaps and staleness from a recorded stream
vehicleLink builds what a radio delivers over 8.45 s: a MESSAGE_INTERVAL reply confirming GLOBAL_POSITION_INT at 200000 microseconds, HEARTBEAT at 1 Hz, ATTITUDE at 10 Hz and GLOBAL_POSITION_INT at 5 Hz, with three noise bytes, a radio that holds 0.6 s of frames and delivers them in a burst, one corrupted ATTITUDE frame, a position stream that stops at 6 s and silence after 8.45 s. The parser resynchronises on 0xFD, each stream records its count, receipt times and largest gaps, and five checks compare ages with per-stream timeouts: three expected intervals for data, five seconds of missing heartbeats for the link.
package main
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"math"
"time"
)
const (
magicV2 = 0xFD
headerLen = 10
msgHeartbeat = 0
msgAttitude = 30
msgGlobalPositionInt = 33
msgMessageInterval = 244
)
var crcExtra = map[uint32]byte{msgHeartbeat: 50, msgAttitude: 39, msgGlobalPositionInt: 104, msgMessageInterval: 95}
type Heartbeat struct {
CustomMode uint32
Type, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8
}
type Attitude struct {
TimeBootMs uint32
Roll, Pitch, Yaw, RollSpeed, PitchSpeed, YawSpeed float32
}
type GlobalPositionInt struct {
TimeBootMs uint32
Lat, Lon int32 // degE7
Alt, RelativeAlt int32 // mm (MSL, above home)
Vx, Vy, Vz int16 // cm/s north, east, down
Hdg uint16 // cdeg, 65535 = unknown
}
type MessageInterval struct {
IntervalUs int32 // wire order: the int32 comes before the uint16
MessageID uint16
}
type Frame struct {
Seq uint8
MsgID uint32
Payload []byte
Rx time.Duration // ground-station clock when the frame was complete
}
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
}
func frameCRC(data []byte, extra byte) uint16 {
crc := uint16(0xFFFF)
for _, b := range data {
crc = crcAccumulate(crc, b)
}
return crcAccumulate(crc, extra)
}
func encode(seq uint8, msgID uint32, msg any) []byte {
payload, err := binary.Append(nil, binary.LittleEndian, msg)
if err != nil {
log.Fatal(err)
}
for len(payload) > 1 && payload[len(payload)-1] == 0 {
payload = payload[:len(payload)-1]
}
buf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, 1, 1,
byte(msgID), byte(msgID >> 8), byte(msgID >> 16)}, payload...)
return binary.LittleEndian.AppendUint16(buf, frameCRC(buf[1:], crcExtra[msgID]))
}
func unmarshal(payload []byte, msg any) {
full := make([]byte, binary.Size(msg))
copy(full, payload)
if _, err := binary.Decode(full, binary.LittleEndian, msg); err != nil {
log.Fatal(err)
}
}
// Parser cuts a byte stream into valid frames and resynchronises on the next
// 0xFD after junk or a frame that fails its CRC.
type Parser struct {
buf []byte
BadCRC, Skipped int
}
func (p *Parser) Feed(data []byte, rx time.Duration) []Frame {
p.buf = append(p.buf, data...)
var out []Frame
for {
i := bytes.IndexByte(p.buf, magicV2)
if i < 0 {
i = len(p.buf)
}
p.Skipped += i
p.buf = p.buf[i:]
if len(p.buf) < headerLen {
return out
}
n := int(p.buf[1])
if len(p.buf) < headerLen+n+2 {
return out
}
id := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16
extra, known := crcExtra[id]
got := binary.LittleEndian.Uint16(p.buf[headerLen+n:])
if !known || got != frameCRC(p.buf[1:headerLen+n], extra) {
p.BadCRC++
p.Skipped++
p.buf = p.buf[1:] // not a frame after all: hunt for the next 0xFD
continue
}
payload := append([]byte(nil), p.buf[headerLen:headerLen+n]...)
out = append(out, Frame{Seq: p.buf[4], MsgID: id, Payload: payload, Rx: rx})
p.buf = p.buf[headerLen+n+2:]
}
}
// Stream is what the ground station knows about one message type.
type Stream struct {
Name string
ID uint32
Timeout time.Duration
Count int
First, Last time.Duration
MaxGap time.Duration
lastBoot uint32
MaxBootGap time.Duration
hasBootStamp bool
}
func (s *Stream) Add(f Frame, boot uint32, hasBoot bool) {
if s.Count == 0 {
s.First = f.Rx
} else {
s.MaxGap = max(s.MaxGap, f.Rx-s.Last)
if hasBoot {
s.MaxBootGap = max(s.MaxBootGap, time.Duration(boot-s.lastBoot)*time.Millisecond)
}
}
s.Count++
s.Last, s.lastBoot, s.hasBootStamp = f.Rx, boot, hasBoot
}
func (s *Stream) Rate() float64 {
if s.Count < 2 {
return 0
}
return float64(s.Count-1) / (s.Last - s.First).Seconds()
}
type chunk struct {
rx time.Duration
data []byte
}
// vehicleLink builds what a radio delivers: HEARTBEAT at 1 Hz, ATTITUDE at
// 10 Hz and GLOBAL_POSITION_INT at 5 Hz. The radio holds frames sent between
// 3.0 and 3.6 s and delivers them at 3.65 s; GLOBAL_POSITION_INT stops at
// 6 s; one ATTITUDE frame is corrupted; the link dies after 8.45 s.
func vehicleLink() []chunk {
const bootAtStart = 125000 // the vehicle booted 125 s before we started listening
var out []chunk
var seq uint8
rx := time.Duration(0)
send := func(sent int, data []byte) {
seq++
arrive := time.Duration(sent+8+sent%7) * time.Millisecond // a few ms of latency
if sent >= 3000 && sent < 3600 {
arrive = 3650 * time.Millisecond
}
rx = max(rx, arrive) // a serial link is first in, first out
out = append(out, chunk{rx, data})
}
out = append(out, chunk{0, []byte{0x55, 0x00, 0xAA}}) // noise before the first frame
send(0, encode(seq, msgMessageInterval, MessageInterval{IntervalUs: 200000, MessageID: msgGlobalPositionInt}))
lon := int32(85455938)
for ms := 0; ms <= 8450; ms += 50 {
boot := uint32(bootAtStart + ms)
if ms%1000 == 0 {
send(ms, encode(seq, msgHeartbeat, Heartbeat{CustomMode: 3, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}))
}
if ms%100 == 0 {
f := encode(seq, msgAttitude, Attitude{TimeBootMs: boot, Yaw: math.Pi / 2})
if ms == 5000 {
f[12] ^= 0x10 // a bit error the radio's own checks missed
}
send(ms, f)
}
if ms%200 == 0 && ms < 6000 {
lon += 106 // 4 m/s east is about 106e-7 degrees of longitude per 0.2 s here
send(ms, encode(seq, msgGlobalPositionInt, GlobalPositionInt{TimeBootMs: boot, Lat: 473977419,
Lon: lon, Alt: 508300, RelativeAlt: 20150, Vy: 400, Hdg: 9000}))
}
}
return out
}
func main() {
streams := []*Stream{
{Name: "HEARTBEAT", ID: msgHeartbeat, Timeout: 5 * time.Second}, // five missed heartbeats
{Name: "ATTITUDE", ID: msgAttitude, Timeout: 300 * time.Millisecond},
{Name: "GLOBAL_POSITION_INT", ID: msgGlobalPositionInt},
}
byID := map[uint32]*Stream{}
for _, s := range streams {
byID[s.ID] = s
}
var p Parser
var lastPos GlobalPositionInt
var nextSeq uint8
frames, lost := 0, 0
check := func(at time.Duration) {
hb := streams[0]
state := "link up "
if hb.Count == 0 || at-hb.Last > hb.Timeout {
state = "LINK LOST"
}
line := fmt.Sprintf("t=%5.1fs HEARTBEAT %.2fs %s", at.Seconds(), (at - hb.Last).Seconds(), state)
for _, s := range streams[1:] {
age := at - s.Last
mark := "ok"
if age > s.Timeout {
mark = "STALE"
}
line += fmt.Sprintf(" %s %.2fs %s", s.Name, age.Seconds(), mark)
}
fmt.Println(line)
}
checks := []time.Duration{2 * time.Second, 3500 * time.Millisecond, 7 * time.Second, 11 * time.Second, 14 * time.Second}
for _, c := range vehicleLink() {
for len(checks) > 0 && checks[0] < c.rx {
check(checks[0])
checks = checks[1:]
}
for _, f := range p.Feed(c.data, c.rx) {
if frames > 0 {
lost += int(f.Seq - nextSeq) // uint8 arithmetic wraps at 256
}
frames, nextSeq = frames+1, f.Seq+1
switch f.MsgID {
case msgMessageInterval:
var mi MessageInterval
unmarshal(f.Payload, &mi)
fmt.Printf("MESSAGE_INTERVAL: message %d every %d us (%.1f Hz)\n", mi.MessageID, mi.IntervalUs, 1e6/float64(mi.IntervalUs))
if s := byID[uint32(mi.MessageID)]; s != nil && mi.IntervalUs > 0 {
s.Timeout = 3 * time.Duration(mi.IntervalUs) * time.Microsecond
}
case msgHeartbeat:
byID[f.MsgID].Add(f, 0, false)
case msgAttitude:
var a Attitude
unmarshal(f.Payload, &a)
byID[f.MsgID].Add(f, a.TimeBootMs, true)
case msgGlobalPositionInt:
unmarshal(f.Payload, &lastPos)
byID[f.MsgID].Add(f, lastPos.TimeBootMs, true)
}
}
}
for _, at := range checks {
check(at)
}
fmt.Printf("frames %d, failed CRC %d, bytes skipped %d, lost by sequence %d\n", frames, p.BadCRC, p.Skipped, lost)
fmt.Println("message count rx rate max gap (rx) max gap (vehicle clock)")
for _, s := range streams {
vehicle := "-"
if s.hasBootStamp {
vehicle = s.MaxBootGap.String()
}
fmt.Printf("%-19s %5d %4.1f Hz %12s %s\n", s.Name, s.Count, s.Rate(), s.MaxGap, vehicle)
}
g := lastPos
fmt.Printf("last position: %.7f, %.7f alt %.2f m MSL, %.2f m above home\n",
float64(g.Lat)/1e7, float64(g.Lon)/1e7, float64(g.Alt)/1000, float64(g.RelativeAlt)/1000)
fmt.Printf("velocity: north %.2f, east %.2f, climb %.2f m/s, heading %.2f deg\n",
float64(g.Vx)/100, float64(g.Vy)/100, float64(-g.Vz)/100, float64(g.Hdg)/100)
}At 2.0 s everything is fresh. At 3.5 s, inside the radio hold, the heartbeat is 1.49 s old and the link is up, yet ATTITUDE (0.59s) and GLOBAL_POSITION_INT (0.69s) are STALE. At 7.0 s only GLOBAL_POSITION_INT is stale (1.19s) while heartbeats arrive: the case a heartbeat-only monitor misses. At 11.0 s the link has been dead for 2.5 s but the heartbeat is 2.99 s old, so it still says link up; at 14.0 s it reaches 5.99s and reports LINK LOST. The summary shows 124 frames, 1 failed CRC, 31 skipped bytes (3 noise bytes and the 28-byte corrupted frame) and 1 frame lost by sequence. Receipt gaps of 740ms and 842ms reveal the burst that the vehicle clock (200ms) hides. The last position decodes to 47.3977419, 8.5459118 at 20.15 m above home, 4.00 m/s east on heading 90.00 deg.
Decide per stream, not per link
Give every consumer a maximum age it tolerates: a map can show a 2 s old position with a warning, a geofence monitor may need data younger than half a second, and a command that depends on the vehicle's mode should check that the mode is fresh. Show the age next to each value and grey out stale ones. Declare link loss from missed heartbeats (on radio links the MAVLink documentation describes 1 Hz heartbeats and four or five missed before disconnecting), but alarm on stale data first, because a heartbeat comes from a different code path than the estimator and can keep arriving while position does not. When a link returns, the first frames may be old ones from a buffer: check that time_boot_ms moves forward before trusting them.
Fly it in GopherForge
The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To feed it simulator data, fly in a sim.Run loop and, each time d.Telemetry().Time changes, encode a GLOBAL_POSITION_INT from the report (GPS position converted to degE7 around a home point, BaroAlt in millimetres as relative_alt, velocity in cm/s north, east and down) and pass the frame to Parser.Feed with the simulated time as the receipt time. Stop encoding for a few seconds and watch the checks turn STALE; add sim.Save for a replay.
TAKE THIS WITH YOU
Treat every telemetry value as a sample with an age. Stamp frames on receipt with your own clock, measure rates and gaps per message, keep time_boot_ms for ordering and reboot detection, and alarm on stale data streams before the heartbeat timeout declares the link lost.
Check your understanding
A ground station shows how old the vehicle position is. Which clock should it use to measure that age?
Go to the source
Progress stays in this browser. No account needed.