Drone software: architecture, MAVLink and telemetry · 6 MIN READ
A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts
Structure a MAVLink ground station with a reader goroutine, a periodic heartbeat, a channel of decoded frames, a select loop with a resettable link-loss timer and a context that shuts everything down cleanly.
A ground station is a small concurrent system: bytes arrive whenever the radio delivers them, heartbeats must go out on time whether or not anything arrives, operator commands interleave with both, and the link can vanish at any moment. Goroutines, channels, select and context map onto that shape directly. The hard parts are deciding who owns what and making sure every goroutine stops when the link or the program ends.
drones · A MAP OF THE IDEA
- Reader goroutine decodes
- Heartbeat tied to ctx
- Select frames and timer
- Cancel, close, wait
Useful when
- One owner per piece of state needs no locks.
- A resettable timer turns silence into a typed error.
Watch out
- Read ignores contexts; only Close or a deadline unblocks it.
- A heartbeat that outlives the station misleads the vehicle.
Implementation & operation cost: Two goroutines and a WaitGroup per link, plus a timeout chosen for the radio you actually fly.
One owner per job
The reader goroutine owns conn.Read and the parser, and sends decoded frames on a small buffered channel. The heartbeat goroutine owns periodic writes and the sequence counter. Run's loop owns the state (latest values, the log) and is the only goroutine that touches it, so no mutex is needed. net.Conn allows concurrent calls, but keep a single writer per link anyway, so sequence numbers stay ordered and frames never interleave on transports that split large writes; operator commands would go through that writer too. The reader reports its final error on a channel with a buffer of one, so it can always exit even if nobody is listening any more.
Heartbeats and link loss
On radio links components usually send HEARTBEAT at 1 Hz and treat four or five missing ones as a disconnection. A ground station identifies itself with type MAV_TYPE_GCS (6), autopilot MAV_AUTOPILOT_INVALID (8) and usually system id 255; the vehicle uses those heartbeats for its own ground-station failsafe (FS_GCS_ENABLE in ArduPilot, the data-link-loss action NAV_DLL_ACT in PX4). Link loss on the station side is a time.Timer reset on every valid frame; since Go 1.23, with a go.mod that says go 1.23 or later, Reset and Stop guarantee that no stale value is received afterwards, so the old drain-before-reset idiom is unnecessary. The MAVLink documentation also warns against sending heartbeats from a thread that does not know the state of the rest of the component: tie the heartbeat to the same context so it stops when the station stops.
A ground station over net.Pipe
main connects the GroundStation to a simulated vehicle through net.Pipe, an in-memory, synchronous, full-duplex connection where each Write waits for the other side to read. The vehicle streams four HEARTBEAT and GLOBAL_POSITION_INT pairs 20 ms apart, then its radio goes quiet while its reader keeps draining heartbeats. The station sends a heartbeat every 100 ms and declares link loss after 500 ms without a valid frame, both scaled down from flight values so the program finishes in under a second. It prints only what the protocol orders: the station's log in stream order, the error Run returned and the first heartbeat the vehicle saw, never how many heartbeats were sent, which depends on scheduling.
package main
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
"time"
)
const (
magicV2 = 0xFD
headerLen = 10
msgHeartbeat = 0
msgGlobalPositionInt = 33
)
var crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}
type Heartbeat struct {
CustomMode uint32
Type, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8
}
type GlobalPositionInt struct {
TimeBootMs uint32
Lat, Lon int32
Alt, RelativeAlt int32
Vx, Vy, Vz int16
Hdg uint16
}
type Frame struct {
Seq, SysID, CompID uint8
MsgID uint32
Payload []byte
}
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, sysID, compID uint8, msgID uint32, msg any) []byte {
payload, err := binary.Append(nil, binary.LittleEndian, msg)
if err != nil {
panic(err) // only fixed-size structs are passed in
}
for len(payload) > 1 && payload[len(payload)-1] == 0 {
payload = payload[:len(payload)-1]
}
buf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,
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) error {
full := make([]byte, binary.Size(msg))
copy(full, payload)
_, err := binary.Decode(full, binary.LittleEndian, msg)
return err
}
// Parser cuts a byte stream into frames that pass their CRC (lesson 3).
type Parser struct{ buf []byte }
func (p *Parser) Feed(data []byte) []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.buf = p.buf[i:]
if len(p.buf) < headerLen || len(p.buf) < headerLen+int(p.buf[1])+2 {
return out
}
n := int(p.buf[1])
id := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16
extra, known := crcExtra[id]
if !known || binary.LittleEndian.Uint16(p.buf[headerLen+n:]) != frameCRC(p.buf[1:headerLen+n], extra) {
p.buf = p.buf[1:]
continue
}
out = append(out, Frame{Seq: p.buf[4], SysID: p.buf[5], CompID: p.buf[6], MsgID: id,
Payload: append([]byte(nil), p.buf[headerLen:headerLen+n]...)})
p.buf = p.buf[headerLen+n+2:]
}
}
var ErrLinkLost = errors.New("link lost")
// GroundStation owns one link. Run starts a reader and a heartbeat goroutine
// and handles decoded frames in its own loop until the link or ctx ends.
type GroundStation struct {
Conn net.Conn
Heartbeat time.Duration // 1 s on a real link
LinkTimeout time.Duration // several missed heartbeats on a real link
Log []string // written only by Run's goroutine
seq uint8
}
func (g *GroundStation) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
frames := make(chan Frame, 16)
readErr := make(chan error, 1)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); readErr <- g.readLoop(ctx, frames) }()
go func() { defer wg.Done(); g.heartbeatLoop(ctx) }()
defer func() {
cancel() // stops the heartbeat: never advertise a dead ground station
g.Conn.Close() // unblocks a Read or Write in progress
wg.Wait()
}()
timer := time.NewTimer(g.LinkTimeout)
defer timer.Stop()
for {
select {
case f := <-frames:
g.handle(f)
timer.Reset(g.LinkTimeout)
case <-timer.C:
return fmt.Errorf("%w: no frame for %v", ErrLinkLost, g.LinkTimeout)
case err := <-readErr:
return err
case <-ctx.Done():
return ctx.Err()
}
}
}
func (g *GroundStation) readLoop(ctx context.Context, out chan<- Frame) error {
var p Parser
buf := make([]byte, 512)
for {
n, err := g.Conn.Read(buf)
for _, f := range p.Feed(buf[:n]) {
select {
case out <- f:
case <-ctx.Done():
return ctx.Err()
}
}
if err != nil {
return err
}
}
}
func (g *GroundStation) heartbeatLoop(ctx context.Context) {
tick := time.NewTicker(g.Heartbeat)
defer tick.Stop()
for {
// MAV_TYPE_GCS (6), MAV_AUTOPILOT_INVALID (8), MAV_STATE_ACTIVE (4)
hb := Heartbeat{Type: 6, Autopilot: 8, SystemStatus: 4, MavlinkVersion: 3}
if _, err := g.Conn.Write(Encode(g.seq, 255, 190, msgHeartbeat, hb)); err != nil {
return
}
g.seq++
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
func (g *GroundStation) handle(f Frame) {
switch f.MsgID {
case msgHeartbeat:
var hb Heartbeat
if Unmarshal(f.Payload, &hb) == nil {
g.Log = append(g.Log, fmt.Sprintf("seq %d HEARTBEAT from %d/%d: type %d, autopilot %d, armed %t, custom mode %d",
f.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot, hb.BaseMode&0x80 != 0, hb.CustomMode))
}
case msgGlobalPositionInt:
var p GlobalPositionInt
if Unmarshal(f.Payload, &p) == nil {
g.Log = append(g.Log, fmt.Sprintf("seq %d GLOBAL_POSITION_INT: %.7f, %.7f, %.2f m above home",
f.Seq, float64(p.Lat)/1e7, float64(p.Lon)/1e7, float64(p.RelativeAlt)/1000))
}
}
}
// vehicle plays the autopilot at the other end of the link: it streams four
// rounds of telemetry, then its radio goes quiet. Its reader keeps draining
// the ground station's heartbeats until the link closes.
func vehicle(conn net.Conn, wg *sync.WaitGroup, firstGCS *string) {
wg.Add(2)
go func() {
defer wg.Done()
var p Parser
buf := make([]byte, 512)
for {
n, err := conn.Read(buf)
for _, f := range p.Feed(buf[:n]) {
var hb Heartbeat
if *firstGCS == "" && f.MsgID == msgHeartbeat && Unmarshal(f.Payload, &hb) == nil {
*firstGCS = fmt.Sprintf("seq %d HEARTBEAT from %d/%d, type %d, autopilot %d", f.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot)
}
}
if err != nil {
return
}
}
}()
go func() {
defer wg.Done()
var seq uint8
for i := range 4 {
hb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}
pos := GlobalPositionInt{TimeBootMs: uint32(60000 + 20*i), Lat: 473977419, Lon: 85455938 + 27*int32(i),
Alt: 498300, RelativeAlt: 10000 + 50*int32(i), Vy: 100, Hdg: 9000}
for _, frame := range [][]byte{Encode(seq, 1, 1, msgHeartbeat, hb), Encode(seq+1, 1, 1, msgGlobalPositionInt, pos)} {
if _, err := conn.Write(frame); err != nil {
return
}
}
seq += 2
time.Sleep(20 * time.Millisecond)
}
}()
}
func main() {
gcsEnd, vehicleEnd := net.Pipe() // in memory, synchronous, like a socket pair
var vehicleWG sync.WaitGroup
var firstGCS string
vehicle(vehicleEnd, &vehicleWG, &firstGCS)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
gcs := &GroundStation{Conn: gcsEnd, Heartbeat: 100 * time.Millisecond, LinkTimeout: 500 * time.Millisecond}
err := gcs.Run(ctx)
vehicleWG.Wait() // Run closed the link, so both vehicle goroutines have returned
for _, line := range gcs.Log {
fmt.Println("gcs:", line)
}
fmt.Println("gcs stopped:", err, "| link lost:", errors.Is(err, ErrLinkLost))
fmt.Println("vehicle saw:", firstGCS)
}The eight gcs lines arrive in sequence order 0 to 7: HEARTBEATs from 1/1 with type 2, autopilot 3, armed true and custom mode 4, interleaved with GLOBAL_POSITION_INT reports whose longitude moves from 8.5455938 to 8.5456019 and whose altitude rises from 10.00 to 10.15 m above home. Then the timer fires and Run returns "link lost: no frame for 500ms"; errors.Is finds the wrapped ErrLinkLost, so the caller can tell a lost link from a cancelled context. The vehicle saw "seq 0 HEARTBEAT from 255/190, type 6, autopilot 8", the station's first heartbeat, sent before any telemetry arrived. Run's deferred function cancels the context, closes the connection to unblock the reader and waits for both goroutines.
Shutdown without leaks
Order matters. cancel() makes the heartbeat loop return at its next select and lets a reader blocked on the frames channel give up. Close on the connection is what unblocks a goroutine sitting in Read or Write, because neither looks at a context; on network sockets SetReadDeadline is the other way to wake a reader. Only then does wg.Wait() return. Cancelling without closing leaves the reader blocked in Read for ever, and closing without cancelling leaves the heartbeat loop waiting for its next tick to discover the closed link. Run the program under go run -race and in tests that start and stop many stations: a leaked goroutine per reconnect is a slow memory leak on a companion computer that stays up for months.
The same with gomavlib
In production, github.com/bluenviron/gomavlib (v4) supplies the codec, dialects generated from the official XML such as common and ardupilotmega, endpoints for serial ports, UDP (server, client, broadcast), TCP and custom transports, automatic heartbeats, signing and routing; the mavp2p router is built on it. A Node takes Endpoints, a Dialect, OutVersion and OutSystemID; Initialize starts it, and Events delivers frames, channel openings and parse errors on one channel. EndpointUDPServer on :14550 receives what most vehicles and simulators send to the conventional ground-station port.
import (
"log"
"time"
"github.com/bluenviron/gomavlib/v4"
"github.com/bluenviron/gomavlib/v4/pkg/dialects/common"
)
func listen() {
node := &gomavlib.Node{
Endpoints: []gomavlib.Endpoint{
&gomavlib.EndpointUDPServer{Address: ":14550"},
},
Dialect: common.Dialect,
OutVersion: gomavlib.V2,
OutSystemID: 255,
HeartbeatPeriod: time.Second, // the library default is 5 s
}
if err := node.Initialize(); err != nil {
log.Fatal(err)
}
defer node.Close()
for evt := range node.Events() {
frm, ok := evt.(*gomavlib.EventFrame)
if !ok {
continue
}
switch msg := frm.Message().(type) {
case *common.MessageHeartbeat:
log.Printf("system %d: type %d, custom mode %d", frm.SystemID(), msg.Type, msg.CustomMode)
case *common.MessageGlobalPositionInt:
log.Printf("%.7f, %.7f, %.2f m above home",
float64(msg.Lat)/1e7, float64(msg.Lon)/1e7, float64(msg.RelativeAlt)/1000)
}
}
}The node owns the sockets, the codec and its own heartbeat goroutine, and hands frames to one loop, which stays the single owner of state as in the program above. HeartbeatPeriod is set because gomavlib sends one every 5 s by default, slower than the 1 Hz most radio links expect. Staleness checks and a link-loss timer still belong around this loop: the library tells you what arrived, not what stopped arriving.
Fly it in GopherForge
The program uses only the standard library, and net.Pipe needs no network, so it runs in the app's sandbox: choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To put the simulator behind the link, replace the vehicle's four fixed rounds with a sim.Run loop that encodes a GLOBAL_POSITION_INT from d.Telemetry() each time its Time changes and writes it to vehicleEnd, then call sim.Save at the end so Output shows the flight the ground station watched.
TAKE THIS WITH YOU
Give each job one goroutine and each piece of state one owner: a reader that decodes into a channel, a heartbeat tied to the same context, and a loop that selects on frames, a resettable link-loss timer and cancellation. Shut down by cancelling, closing the connection and waiting.
Check your understanding
A ground station cancels its context on shutdown, but the reader goroutine never exits: it is blocked in conn.Read. What makes Read return?
Go to the source
Progress stays in this browser. No account needed.