Missions, safety and fleets · 6 MIN READ
Testing drone software: seeded scenarios, invariants, SITL, HIL and CI
Build a deterministic, table-driven scenario matrix for a mission, check safety invariants and expected outcomes on every run, and place it in a test pyramid with software in the loop, hardware in the loop and continuous integration.
Drone software cannot be tested the way it fails: nobody crashes an aircraft to find out whether the fence works. Most of its behaviour can be tested on a laptop in milliseconds, provided the simulation is deterministic, the scenarios are a table and the pass criteria are invariants rather than golden logs. The same scenarios then run against the real flight stack in SITL, on the real board in HIL, and only after that in the field.
drones · A MAP OF THE IDEA
- Seed and fixed timestep
- Scenarios as table rows
- Check invariants per run
- SITL, HIL, then field
Useful when
- Hundreds of flights per second, reproducible to the last digit.
- A new world costs one table row; the invariants stay.
Watch out
- A simple model can pass what a real airframe fails.
- A harness that overrides failsafes tests the wrong program.
Implementation & operation cost: A deterministic simulator, a scenario table with expectations, an invariant checker and CI time for SITL runs.
Determinism first
A failure you cannot reproduce is a rumour. Make every source of variation an input: seed the random number generator, advance a fixed timestep instead of reading the clock, iterate slices rather than maps where order reaches the output, and keep goroutine scheduling out of the results, as the fleet supervisor did. A run then becomes a pure function of its scenario, and rerunning it must give the same final state to the last bit. The simulator used here is deterministic by construction, since time advances only in Step and all noise comes from the seeded source, which is what lets the program below print exact values and compare two runs with ==.
Scenarios as a table
Describe each world as a row: wind, gusts, battery, seed and what the mission is expected to do. Include the boring case, each stress on its own (crosswind, gusts, a storm, a wind beyond the airframe's top airspeed, a low battery) and then combinations. The expected outcome belongs to the row: with 30 percent in a 6 m/s wind the correct behaviour is an aborted survey that lands safely at home, and a test demanding completion there would test the wrong thing. Every row also runs the same invariants, so a new scenario costs one line. Never let the test harness override a failsafe: once the autopilot has switched to RTL or Land, the mission code must stop commanding, or the test exercises a program you would never fly. Here Arrived is true only while the autopilot holds the last target, within 1 m and nearly stopped, so the mission sends the next waypoint only after Arrived; a failsafe in command, or a vehicle that cannot hold position, stops the mission.
A scenario matrix
The program flies a 60 m survey square inside a fence that leaves 2 m around the corners, in eight worlds. A watch function records the highest horizontal speed, the furthest excursion outside the fence and the vertical speed just before touchdown; Check compares the result with the invariants (landed without crashing, never outside the fence, at most 10.5 m/s, touchdown at most 1.5 m/s, within 3 m of home, at least 10 percent left) and with the row's expected outcome. Then it flies the gusty row twice and compares the final states.
package main
import (
"fmt"
"log"
"math"
"strings"
"gopherforge.app/drone"
)
// The survey corners are at 30 m; the fence leaves a 2 m margin.
var fence = []drone.Vec3{{X: -32, Y: -32}, {X: 32, Y: -32}, {X: 32, Y: 32}, {X: -32, Y: 32}}
// Scenario is one row of the test matrix: the world the mission flies in
// and whether the mission is expected to finish or to be aborted safely.
type Scenario struct {
Name string
Wind drone.Vec3
Gust float64
Battery float64
Seed int64
Complete bool
}
// Result is what the run measured; invariants are checked against it.
type Result struct {
Waypoints int // survey corners reached
MaxSpeed float64 // horizontal, m/s
Outside float64 // furthest distance outside the fence, m
Touchdown float64 // vertical speed at touchdown, m/s
HomeDist float64 // landing distance from home, m
Battery float64 // at the end, %
Crashed bool
Final drone.State
}
// distance from p to the nearest fence edge
func edgeDistance(poly []drone.Vec3, p drone.Vec3) float64 {
best := math.Inf(1)
for i := range poly {
a, b := poly[i], poly[(i+1)%len(poly)]
ab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()
t := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/(ab.X*ab.X+ab.Y*ab.Y)))
best = math.Min(best, ap.Sub(ab.Scale(t)).Len())
}
return best
}
// Fly runs the survey mission in one scenario and measures it.
func Fly(sc Scenario) (*drone.Sim, Result) {
sim := drone.New(drone.Config{Wind: sc.Wind, Gust: sc.Gust, Battery: sc.Battery, MaxSpeed: 10, Geofence: fence, Seed: sc.Seed})
d := sim.Drone()
var r Result
prevVz := 0.0
watch := func() {
st := d.State()
r.MaxSpeed = math.Max(r.MaxSpeed, st.Vel.Horizontal().Len())
if !drone.Inside(fence, st.Pos) {
r.Outside = math.Max(r.Outside, edgeDistance(fence, st.Pos))
}
if !st.Landed {
prevVz = st.Vel.Z
}
}
until := func(limit float64, done func() bool) bool {
return sim.RunUntil(limit, func(float64) bool { watch(); return done() })
}
if err := d.Arm(); err != nil {
log.Fatalf("%s: %v", sc.Name, err)
}
d.TakeOff(15)
until(30, d.Arrived)
for _, p := range []drone.Vec3{{X: 30, Y: -30, Z: 15}, {X: 30, Y: 30, Z: 15}, {X: -30, Y: 30, Z: 15}, {X: -30, Y: -30, Z: 15}} {
// Arrived means the autopilot holds our last target. Otherwise a
// failsafe owns the vehicle or it cannot hold: never override it.
if !d.Arrived() {
break
}
d.GoTo(p)
until(90, func() bool { return d.State().Mode != drone.GoingTo })
if d.Arrived() {
r.Waypoints++
}
}
if d.Arrived() {
d.ReturnHome()
}
until(240, func() bool { s := d.State(); return s.Landed || s.Mode == drone.Crashed })
st := d.State()
r.Touchdown, r.HomeDist, r.Battery = -prevVz, st.Pos.Horizontal().Len(), st.Battery
r.Crashed, r.Final = st.Mode == drone.Crashed, st
return sim, r
}
// Check returns the invariants and expectations a run broke.
func Check(sc Scenario, r Result) []string {
var failed []string
if sc.Complete != (r.Waypoints == 4) {
failed = append(failed, "mission")
}
if r.Crashed || !r.Final.Landed {
failed = append(failed, "landed")
}
if r.Outside > 0 {
failed = append(failed, "fence")
}
if r.MaxSpeed > 10.5 {
failed = append(failed, "speed")
}
if r.Touchdown > 1.5 {
failed = append(failed, "touchdown")
}
if r.HomeDist > 3 {
failed = append(failed, "home")
}
if r.Battery < 10 {
failed = append(failed, "reserve")
}
return failed
}
func main() {
scenarios := []Scenario{
{Name: "calm", Battery: 100, Seed: 1, Complete: true},
{Name: "crosswind 5", Wind: drone.Vec3{Y: 5}, Battery: 100, Seed: 1, Complete: true},
{Name: "gusty 6+3", Wind: drone.Vec3{X: -6}, Gust: 3, Battery: 100, Seed: 2, Complete: true},
{Name: "storm 10+4", Wind: drone.Vec3{X: 10}, Gust: 4, Battery: 100, Seed: 3, Complete: true},
{Name: "gale 14+4", Wind: drone.Vec3{X: 14}, Gust: 4, Battery: 100, Seed: 3, Complete: true},
{Name: "wind 20", Wind: drone.Vec3{X: 20}, Battery: 100, Seed: 3, Complete: true},
{Name: "battery 40", Battery: 40, Seed: 4, Complete: true},
{Name: "battery 30 wind", Wind: drone.Vec3{X: 6}, Battery: 30, Seed: 5, Complete: false},
}
fmt.Printf("%-16s %-3s %4s %8s %5s %7s %6s %s\n", "scenario", "wps", "vmax", "outside", "touch", "home", "batt", "result")
var last *drone.Sim
for _, sc := range scenarios {
sim, r := Fly(sc)
verdict := "PASS"
if failed := Check(sc, r); len(failed) > 0 {
verdict = "FAIL " + strings.Join(failed, ",")
}
fmt.Printf("%-16s %d/4 %4.1f %6.2f m %5.1f %5.1f m %5.1f%% %s\n",
sc.Name, r.Waypoints, r.MaxSpeed, r.Outside, r.Touchdown, r.HomeDist, r.Battery, verdict)
last = sim
}
// Same seed, same inputs, same flight: bit for bit.
_, a := Fly(scenarios[2])
_, b := Fly(scenarios[2])
fmt.Printf("gusty run twice: identical final state %v (%v, %.4f%%)\n", a.Final == b.Final, a.Final.Pos, a.Final.Battery)
if err := last.Save(); err != nil {
log.Fatal(err)
}
}Six rows pass, and the battery column shows what wind costs: 85.7 percent left in calm air, 74.1 after the same survey in storm 10+4. In gale 14+4 the drone reaches the first corner, then wind and a gust push it 1.56 m past the east fence on the next leg; the fence failsafe brings it home and the row reports FAIL mission,fence. The fix belongs in the plan, a wider margin or a slower approach, not in the test. wind 20 beats the airframe's 18 m/s airspeed: after the climb the drone drifts east at 2.0 m/s, its top speed in the whole run, so Arrived never reports a hold and the mission never sends the first corner. It drifts out of the fence, RTL cannot make headway, the 10 percent forced landing puts it down 268.9 m downwind with 1.6 percent, and four checks fail. battery 40 completes with 25.7 percent; battery 30 wind is expected to abort, reaches 2 corners and lands 0.3 m from home with 15.8, so it passes. Touchdown is 0.9 m/s in every row. The gusty run twice ends in an identical state, battery 81.3682 percent, and the replay is the last row.
From a program to go test
In a repository the same table becomes a table-driven test: t.Run gives each scenario a name that go test -run can select, and t.Parallel is safe because every scenario builds its own simulator. Fuzzing extends the table: go test -fuzz can generate wind, gust and battery values and keeps any input that breaks an invariant as a regression case under testdata. For code with timeouts, such as a link-loss watchdog, testing/synctest runs the test in a bubble with a fake clock, so a 5 s timeout passes instantly and the same way every time.
func TestSurveyScenarios(t *testing.T) {
for _, sc := range scenarios {
t.Run(sc.Name, func(t *testing.T) {
t.Parallel() // each scenario builds its own Sim
_, r := Fly(sc)
for _, broken := range Check(sc, r) {
t.Errorf("%s: %+v", broken, r)
}
})
}
}Each row becomes a subtest named after its scenario, so go test -run 'TestSurveyScenarios/storm' reruns exactly one world. The subtests can run in parallel because Fly creates a new simulator per call, and every broken invariant is reported with the measured result instead of stopping at the first one.
SITL, HIL and CI
A Go simulator tests your ground-station and mission logic against a simplified vehicle. Software in the loop runs the real flight stack on your computer against a physics model: ArduPilot's SITL binary has built-in physics and sim_vehicle.py starts MAVProxy, which forwards MAVLink to ground stations on UDP port 14550, while PX4 runs in lockstep with Gazebo or its SIH model and can run faster than real time. Point your Go code at that MAVLink port and the same scenarios now exercise the real autopilot's mission handling and failsafes. Hardware in the loop runs the flight stack on the real flight controller with simulated sensors and catches timing and driver problems. In CI, run the Go scenarios on every commit, SITL on merges or nightly, HIL before releases, and field tests with a pilot ready to take over last.
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 console prints the matrix and Output replays the last scenario, the low-battery abort with its return home. The template's mission_test.go already shows the testing side; move the scenario table into a _test.go file as a table-driven test and tap Test to run it the way go test does.
TAKE THIS WITH YOU
Make the simulation a pure function of its inputs, describe worlds as table rows with expected outcomes, and check safety invariants on every run instead of comparing golden logs. Then climb the pyramid: Go scenarios on every commit, SITL with the real flight stack, HIL on the real board, and the field last.
Check your understanding
Your mission test compares the whole printed flight log with a golden file and breaks after every tuning change. What should it assert instead?
Go to the source
Progress stays in this browser. No account needed.