Missions, safety and fleets · 5 MIN READ
Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation
Structure a multi-vehicle ground station with one goroutine per vehicle, fan telemetry into a supervisor over channels, stop everything with context cancellation and monitor pairwise separation with altitude layers, while keeping the simulation deterministic.
Go's concurrency maps naturally onto fleets: every vehicle has its own link, its own state machine and its own failures, and a supervisor watches them all. The hard parts are not the goroutines. They are keeping one slow or broken vehicle from stalling the others, shutting down cleanly, and showing at every moment that no two aircraft are too close, with tests that stay deterministic although the code is concurrent.
drones · A MAP OF THE IDEA
- Goroutine per vehicle
- Fan-in tagged telemetry
- Supervisor with context
- Check pairs every cycle
Useful when
- Each vehicle state has exactly one owner, so no locks.
- One context cancel stops every vehicle goroutine.
Watch out
- A slow consumer can stall a fan-in unless channels are bounded.
- Lockstep tests hide the timing problems of real links.
Implementation & operation cost: A goroutine and inbox per vehicle, a supervisor loop with a context, and a pairwise separation check sized to position error.
One goroutine per vehicle
Give each vehicle a goroutine that owns its link and mission state: it reads that vehicle's telemetry, runs its state machine and emits commands, and nothing else touches that state, so it needs no lock. Telemetry fans in to the supervisor over one channel, tagged with the vehicle's ID, much as every MAVLink frame carries a system ID. With a library such as gomavlib, a node delivers frames from all its endpoints as events on one channel, and a dispatcher fans them out by system ID to the vehicle goroutines. Bound every channel and decide what a slow consumer means: telemetry may be dropped or replaced by the latest sample, commands must never be silently dropped.
Supervisor, context and shutdown
The supervisor starts the vehicle goroutines with sync.WaitGroup.Go (Go 1.25 and later), hands them a context and cancels it to stop everything: at the end of the mission, on an operator abort, or when an error makes the fleet unable to continue. Every blocking send and receive in a vehicle goroutine also selects on ctx.Done(); otherwise cancel leaves goroutines stuck on a channel nobody reads, and wg.Wait never returns. Decide per error whether it is local (that vehicle returns home, the others carry on) or global (everyone holds). A supervisor that restarts a crashed vehicle goroutine must rebuild its state from fresh telemetry, not from what the old goroutine last believed.
Separation assurance
Separation has two numbers: horizontal and vertical distance. A pair is separated while either one meets its minimum, here 10 m horizontally or 4 m vertically. Altitude layering gives each vehicle its own cruise altitude, so crossing routes are separated vertically by design, and climbs and descents between layers happen away from the crossings. The monitor works on reported positions, so the minimums must include position uncertainty (GPS horizontally, barometer vertically) plus the distance covered in one telemetry period and the reaction time. Track the closest approach per pair, alert before a minimum is lost, and log it: losses of separation are near misses that never appear in a crash count.
Three drones, three layers
The program adds bravo and charlie to the simulator's alpha and gives them routes that all cross (0, 30), at 20, 25 and 30 m. Each pilot goroutine sees only telemetry and answers only with commands. Every 0.2 s of simulated time the supervisor sends each pilot its vehicle's latest telemetry, collects one report from each, applies the commands in vehicle order and steps the simulation. The separation monitor uses GPS for the horizontal and barometric altitude for the vertical distance, as a real one would.
package main
import (
"context"
"fmt"
"log"
"math"
"sync"
"gopherforge.app/drone"
)
// Command is what a pilot goroutine asks the link to send to its vehicle.
type Command struct {
Kind string // "takeoff", "goto" or "land"
Target drone.Vec3
}
// Report is one telemetry cycle from a pilot: what it saw, what it wants.
type Report struct {
Drone int
Tel drone.Telemetry
Cmd *Command
}
// Route is one vehicle's job: climb to its layer, fly to a point, land.
type Route struct {
Layer float64
To drone.Vec3
}
// pilot runs in its own goroutine. It only sees telemetry and only
// answers with commands, exactly as it would over a radio link.
func pilot(ctx context.Context, id int, r Route, in <-chan drone.Telemetry, out chan<- Report) {
phase := "ground"
for {
select {
case <-ctx.Done():
return
case tel := <-in:
var cmd *Command
dest := drone.Vec3{X: r.To.X, Y: r.To.Y, Z: r.Layer}
switch {
case phase == "ground":
phase, cmd = "climb", &Command{Kind: "takeoff", Target: drone.Vec3{Z: r.Layer}}
case phase == "climb" && tel.Mode == drone.Hold:
phase, cmd = "cruise", &Command{Kind: "goto", Target: dest}
case phase == "cruise" && tel.GPS.Sub(dest).Horizontal().Len() < 3 && tel.Velocity.Len() < 1:
phase, cmd = "land", &Command{Kind: "land"}
}
select {
case out <- Report{Drone: id, Tel: tel, Cmd: cmd}:
case <-ctx.Done():
return
}
}
}
}
func apply(d *drone.Drone, c Command) error {
switch c.Kind {
case "takeoff":
if err := d.Arm(); err != nil {
return err
}
return d.TakeOff(c.Target.Z)
case "goto":
return d.GoTo(c.Target)
case "land":
return d.Land()
}
return fmt.Errorf("unknown command %q", c.Kind)
}
func main() {
sim := drone.New(drone.Config{Wind: drone.Vec3{X: 1.5, Y: -1}, Gust: 1, MaxSpeed: 6, Seed: 21})
sim.AddDrone("bravo", drone.Vec3{X: -20, Y: 30})
sim.AddDrone("charlie", drone.Vec3{X: 15, Y: 45})
drones := sim.Drones()
// Three routes that all cross (0, 30), one altitude layer each.
routes := []Route{
{Layer: 20, To: drone.Vec3{X: 0, Y: 60}},
{Layer: 25, To: drone.Vec3{X: 30, Y: 30}},
{Layer: 30, To: drone.Vec3{X: -30, Y: 0}},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
reports := make(chan Report, len(drones))
inboxes := make([]chan drone.Telemetry, len(drones))
var wg sync.WaitGroup
for i := range drones {
inboxes[i] = make(chan drone.Telemetry)
wg.Go(func() { pilot(ctx, i, routes[i], inboxes[i], reports) })
}
type pair struct{ min, minH, vAtMinH, t float64 }
pairs := map[[2]int]*pair{}
keys := [][2]int{{0, 1}, {0, 2}, {1, 2}}
for _, k := range keys {
pairs[k] = &pair{min: math.Inf(1), minH: math.Inf(1)}
}
violations := 0
// The supervisor: one telemetry cycle every 0.2 s of simulated time.
for sim.Time() < 120 {
for i, d := range drones {
inboxes[i] <- d.Telemetry()
}
batch := make([]Report, len(drones))
for range drones {
r := <-reports
batch[r.Drone] = r // fan-in arrives in any order; index it
}
for i, r := range batch { // act in a fixed order
if r.Cmd == nil {
continue
}
if err := apply(drones[i], *r.Cmd); err != nil {
cancel()
log.Fatalf("%s: %v", drones[i].Name, err)
}
what := r.Cmd.Kind
switch r.Cmd.Kind {
case "takeoff":
what = fmt.Sprintf("take off to the %.0f m layer", r.Cmd.Target.Z)
case "goto":
what = fmt.Sprintf("go to %v", r.Cmd.Target)
}
fmt.Printf("%5.1f s %-7s %s\n", sim.Time(), drones[i].Name, what)
}
for _, k := range keys {
a, b := batch[k[0]].Tel, batch[k[1]].Tel
if a.Time == 0 || drones[k[0]].State().Landed && drones[k[1]].State().Landed {
continue
}
h := a.GPS.Sub(b.GPS).Horizontal().Len()
v := math.Abs(a.BaroAlt - b.BaroAlt)
p := pairs[k]
if dist := math.Hypot(h, v); dist < p.min {
p.min, p.t = dist, a.Time
}
if h < p.minH {
p.minH, p.vAtMinH = h, v
}
if h < 10 && v < 4 {
violations++
}
}
landed := 0
for _, d := range drones {
if d.State().Landed {
landed++
}
}
if sim.Time() > 1 && landed == len(drones) {
break
}
sim.Run(0.2, nil)
}
cancel()
wg.Wait()
fmt.Println("separation (rule: 10 m horizontal or 4 m vertical)")
for _, k := range keys {
p := pairs[k]
fmt.Printf(" %-7s %-7s closest %4.1f m at %4.1f s; min horizontal %4.1f m with %3.1f m vertical\n",
drones[k[0]].Name, drones[k[1]].Name, p.min, p.t, p.minH, p.vAtMinH)
}
fmt.Printf(" samples breaking the rule: %d\n", violations)
if err := sim.Save(); err != nil {
log.Fatal(err)
}
}The commands appear in a fixed order because the supervisor indexes the reports by vehicle and acts in vehicle order, whatever order the goroutines answered in; the output is the same with any GOMAXPROCS and under the race detector. All three cross near (0, 30): alpha and bravo come within 2.0 m horizontally with 4.7 m vertical, alpha and charlie 4.2 m with 9.5 m, bravo and charlie 5.8 m with 4.7 m. No sample breaks the rule, but 4.7 m shows how little of the 5 m layer spacing is left once barometer noise and altitude-hold error are counted.
Deterministic simulation, concurrent reality
The simulator advances every drone together in one Step, so the program runs in lockstep: telemetry out, commands in, one step. That makes runs repeatable and lets a test assert exact separation figures. Real links are concurrent: telemetry arrives at different rates, packets are lost, one radio is slower than the others, and the supervisor must work with the latest timestamped sample per vehicle instead of waiting for a complete set. Design the production code for that case, with timestamps, staleness checks and no assumptions about order between vehicles, and keep lockstep as the test harness. PX4 and ArduPilot SITL can run several vehicle instances with distinct MAVLink system IDs for the next level of fleet testing.
Fly it in GopherForge
In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. The replay in Output shows the three drones with their trails crossing over (0, 30), and the altitude strip shows the three layers. Set every layer to 20 m and run again: the count of samples breaking the rule shows what the layering was buying.
TAKE THIS WITH YOU
Give every vehicle a goroutine that owns its link and state, fan telemetry into a supervisor tagged with the vehicle ID, stop everything through one context, and check separation pairwise with horizontal and vertical minimums that include position error. Keep the simulation lockstep and deterministic, and design the real code for concurrent, lossy links.
Check your understanding
Under a rule of 10 m horizontal or 4 m vertical separation, when are two drones in a fleet separated?
Go to the source
Progress stays in this browser. No account needed.