Operations: links, logs, rules and fleets in service · 7 MIN READ

Preflight checks as code: fence legs, height limits, obstacle clearance, link and energy with errors.Join

Validate a mission before take-off against a concave geofence leg by leg, the legal height limit with a margin, obstacle clearance, the planned link range and the energy reserve; collect every problem as a typed error with errors.Join, repair what is safe with errors.As, and fly the corrected plan.

Flight stacks check a mission when it is uploaded and again before it runs. A ground station or fleet backend should check it before it is ever uploaded, against things the autopilot does not know: the site survey's obstacles, the link range measured that morning, the pack that is actually fitted, the legal height where the flight happens. A check that stops at the first problem makes the operator fix one thing per round trip. One that returns all of them, each with a type the code can act on, turns planning into a short loop.

drones · A MAP OF THE IDEA

  1. Limits from rules and site
  2. Check every leg and point
  3. Join typed errors
  4. Auto-fix safe, ask the rest

Useful when

  • The operator sees every problem in one pass.
  • Typed errors let code repair only what is safe to repair.

Watch out

  • Sampling a leg can miss a corner thinner than the step.
  • A passing check is only as good as the site survey.

Implementation & operation cost: A check per limit over every leg, typed errors carrying the data to fix them, and a re-check after every edit.

01

What to check, and against what

Collect the limits first, from rules, the site and the aircraft. Height comes from the rules: EASA's open-category page tells pilots to stay below 120 m above ground level, and the FAA's Part 107 summary gives a maximum of 400 feet above the ground, higher only when the drone stays within 400 feet of a structure; recreational flyers in the US fly at or below 400 feet in uncontrolled airspace. These are summaries, not legal advice: check the current rules and any local restrictions where you fly. Plan a few metres under the limit for barometer error and overshoot, and set the autopilot's own fence and ceiling as a backstop. The site gives the geofence and the obstacles with their heights, the range test gives the link limit, and the energy-planning lesson's model gives the charge needed against the pack's charge and the reserve.

02

Every leg, not just the waypoints

The vehicle flies the lines between the waypoints, so check the lines. A concave fence is the classic trap: two waypoints in different arms of an L are both inside, and the straight leg between them cuts across the notch. Test each leg against every fence edge with a segment intersection, or sample it at a step smaller than your margin and test each point with the ray casting of the geofencing lesson, as the program does every metre. Obstacles also stand between waypoints: the horizontal gap from a cylinder to a leg comes from projecting its centre onto the segment, clamped to the ends; use the lower end's altitude to stay conservative. Add the leg nobody plans, the straight return home at the return altitude that a failsafe flies. The link limit is the one place where waypoints suffice, because distance from home along a straight leg is largest at one of its ends.

03

Collect, type and join errors

Give each kind of problem its own error type carrying the data a fix needs: the waypoint and its altitude, the leg and where it leaves the fence. Append every problem to a slice and return errors.Join(errs...), which is nil when the slice is empty, so callers keep the usual err != nil test. The joined error's message lists one problem per line, and it implements Unwrap() []error, so code can range over the individual problems. errors.As and errors.Is walk that tree: errors.As(err, &target) finds the first error of the target's type anywhere inside it, which is right for a question such as is there an energy problem at all. To act on every problem of a type, range over the unwrapped list and call errors.As on each.

go
err := Check(plan, battery) // errors.Join of typed problems, or nil
var low *EnergyError
if errors.As(err, &low) { // found anywhere inside the joined error
	fmt.Printf("fit a bigger pack: %.1f%% needed\n", low.Need)
}
for _, e := range err.(interface{ Unwrap() []error }).Unwrap() {
	var h *HeightError
	if errors.As(e, &h) {
		plan[h.WP-1].Z = h.Limit // every height problem, not just the first
	}
}
Read the code

The first errors.As answers a yes-or-no question about the whole set and fills low with the first *EnergyError it finds. The loop needs every *HeightError, so it ranges over the list that Unwrap returns and tests each element. The type assertion would panic on a nil error, so it belongs after an err != nil check, as in the program, where Fix only runs on a failed check.

04

Check, fix, check again, fly

The site has an L-shaped fence, a 45 m mast, a 250 m tested link range kept 40 m inside, the 120 m height limit kept 5 m under, 8 m of horizontal clearance (or 10 m above an obstacle) and a 25 percent reserve. Plan A is checked on a 60 percent pack. Fix repairs, by type, the two kinds of problem a program can safely repair, lowering waypoints and pulling them towards home, and the plan is checked again. The rest is the operator's: a detour, a turn inside the fence's corner and a full pack. Plan B is checked, then flown with the fence, the mast, the ceiling and the link in the simulator, and the flight is measured against the limits.

go
package main

import (
	"errors"
	"fmt"
	"log"
	"math"
	"slices"

	"gopherforge.app/drone"
)

const (
	legalMax  = 120.0 // m above ground: EASA open category (FAA Part 107: 400 ft, 121.9 m)
	heightPad = 5.0   // m under it for barometer error and overshoot
	hClear    = 8.0   // m horizontal clearance from an obstacle...
	vClear    = 10.0  // m ...unless the leg stays this far above its top
	linkRange = 250.0 // m, from a range test at this site
	linkPad   = 40.0  // m inside it
	reserve   = 25.0  // % left on the ground
)
const cruise, cruiseDrain, hoverDrain, climbCost, stop = 10.0, 0.34, 0.19, 0.10, 2.5 // energy-planning lesson

var (
	fence = []drone.Vec3{{X: -20, Y: -30}, {X: 220, Y: -30}, {X: 220, Y: 70}, {X: 90, Y: 70}, {X: 90, Y: 180}, {X: -20, Y: 180}}
	mast  = drone.Obstacle{Name: "mast", X: 100, Y: 6, Radius: 2, Height: 45}
)

type FenceError struct {
	Leg int
	At  drone.Vec3
}
type HeightError struct {
	WP         int
	Alt, Limit float64
}
type ObstacleError struct {
	Leg       int
	Miss, Alt float64
}
type LinkError struct {
	WP          int
	Dist, Limit float64
}
type EnergyError struct{ Need, Have float64 }

func (e *FenceError) Error() string { return fmt.Sprintf("leg %d leaves the fence at %v", e.Leg, e.At) }
func (e *HeightError) Error() string {
	return fmt.Sprintf("waypoint %d at %.0f m is above the %.0f m limit", e.WP, e.Alt, e.Limit)
}
func (e *ObstacleError) Error() string {
	return fmt.Sprintf("leg %d passes %.1f m from the mast at %.0f m", e.Leg, e.Miss, e.Alt)
}
func (e *LinkError) Error() string {
	return fmt.Sprintf("waypoint %d is %.1f m from home, over %.0f m", e.WP, e.Dist, e.Limit)
}
func (e *EnergyError) Error() string {
	return fmt.Sprintf("needs %.1f%% of a %.0f%% pack", e.Need, e.Have)
}

// legs are the lines flown: from take-off, through the waypoints, and RTL home.
func legs(plan []drone.Vec3) [][2]drone.Vec3 {
	pts := append(append([]drone.Vec3{{Z: plan[0].Z}}, plan...), drone.Vec3{Z: math.Max(plan[len(plan)-1].Z, 15)})
	var out [][2]drone.Vec3
	for i := 1; i < len(pts); i++ {
		out = append(out, [2]drone.Vec3{pts[i-1], pts[i]})
	}
	return out
}

// miss is the horizontal gap between a leg and the side of an obstacle.
func miss(o drone.Obstacle, a, b drone.Vec3) float64 {
	ab, t := b.Sub(a), 0.0
	if l2 := ab.X*ab.X + ab.Y*ab.Y; l2 > 0 {
		t = math.Max(0, math.Min(1, ((o.X-a.X)*ab.X+(o.Y-a.Y)*ab.Y)/l2))
	}
	return math.Hypot(a.X+ab.X*t-o.X, a.Y+ab.Y*t-o.Y) - o.Radius
}

// energy is the charge the plan uses: take-off, legs, stops and the descent.
func energy(plan []drone.Vec3) float64 {
	use, ls := plan[0].Z*climbCost, legs(plan)
	for _, l := range ls {
		use += l[1].Sub(l[0]).Horizontal().Len()/cruise*cruiseDrain + math.Max(0, l[1].Z-l[0].Z)*climbCost + stop*hoverDrain
	}
	return use + ls[len(ls)-1][1].Z/2*hoverDrain // descent at about 2 m/s
}

// Check collects every problem with the plan instead of stopping at the first.
func Check(plan []drone.Vec3, battery float64) error {
	var errs []error
	for i, wp := range plan {
		if limit := legalMax - heightPad; wp.Z > limit {
			errs = append(errs, &HeightError{i + 1, wp.Z, limit})
		}
		if d, limit := wp.Horizontal().Len(), linkRange-linkPad; d > limit {
			errs = append(errs, &LinkError{i + 1, d, limit})
		}
	}
	for i, l := range legs(plan) {
		n := int(l[1].Sub(l[0]).Horizontal().Len()) + 1
		for k := 0; k <= n; k++ { // every metre of every leg: the fence is concave
			if p := l[0].Add(l[1].Sub(l[0]).Scale(float64(k) / float64(n))); !drone.Inside(fence, p) {
				errs = append(errs, &FenceError{i + 1, p})
				break
			}
		}
		if m, low := miss(mast, l[0], l[1]), math.Min(l[0].Z, l[1].Z); m < hClear && low < mast.Height+vClear {
			errs = append(errs, &ObstacleError{i + 1, m, low})
		}
	}
	if need := energy(plan) + reserve; need > battery {
		errs = append(errs, &EnergyError{need, battery})
	}
	return errors.Join(errs...)
}

// Fix repairs, by type, what a program can repair safely and leaves the
// rest to the operator.
func Fix(plan []drone.Vec3, err error) []drone.Vec3 {
	plan = slices.Clone(plan)
	for _, e := range err.(interface{ Unwrap() []error }).Unwrap() {
		var h *HeightError
		var l *LinkError
		switch {
		case errors.As(e, &h):
			plan[h.WP-1].Z = h.Limit
			fmt.Printf("  fixed: waypoint %d lowered to %.0f m\n", h.WP, h.Limit)
		case errors.As(e, &l):
			k := (l.Limit - 5) / l.Dist
			plan[l.WP-1].X, plan[l.WP-1].Y = plan[l.WP-1].X*k, plan[l.WP-1].Y*k
			fmt.Printf("  fixed: waypoint %d pulled in to %v\n", l.WP, plan[l.WP-1])
		}
	}
	return plan
}

func report(name string, err error) {
	list := err.(interface{ Unwrap() []error }).Unwrap() // what errors.Join returns
	fmt.Printf("%s: %d problems\n", name, len(list))
	for _, e := range list {
		fmt.Println("  -", e)
	}
}

func fly(plan []drone.Vec3, battery float64) *drone.Sim {
	sim := drone.New(drone.Config{Geofence: fence, Ceiling: legalMax, Obstacles: []drone.Obstacle{mast}, LinkRange: linkRange,
		Battery: battery, Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1, MaxSpeed: cruise, Seed: 5})
	d := sim.Drone()
	if err := d.Arm(); err != nil {
		log.Fatal(err)
	}
	top, gap, bad := 0.0, math.Inf(1), 0
	watch := func(float64) bool {
		s := d.State()
		top, gap = math.Max(top, s.Pos.Z), math.Min(gap, math.Hypot(s.Pos.X-mast.X, s.Pos.Y-mast.Y)-mast.Radius)
		if !drone.Inside(fence, s.Pos) || !d.Link() {
			bad++
		}
		return d.Arrived() || s.Landed || s.Mode == drone.Crashed
	}
	d.TakeOff(plan[0].Z)
	sim.RunUntil(60, watch)
	for _, wp := range plan {
		d.GoTo(wp)
		sim.RunUntil(120, watch)
	}
	d.ReturnHome()
	sim.RunUntil(180, watch)
	s := d.State()
	fmt.Printf("  flown: highest %.1f m, closest to the mast %.1f m, steps outside the fence or the link %d\n", top, gap, bad)
	fmt.Printf("  %s %.1f m from home; used %.1f%%, the plan said %.1f%%\n", s.Mode, s.Pos.Horizontal().Len(), battery-s.Battery, energy(plan))
	return sim
}

func main() {
	fmt.Printf("limits: under %.0f m (%.0f m legal), within %.0f m (%.0f m link), %.0f m from the mast, %.0f%% reserve\n",
		legalMax-heightPad, legalMax, linkRange-linkPad, linkRange, hClear, reserve)
	planA := []drone.Vec3{{X: 180, Z: 40}, {X: 210, Y: 60, Z: 40}, {X: 60, Y: 150, Z: 40}, {X: 60, Y: 150, Z: 130}}
	err := Check(planA, 60)
	report("plan A on a 60% pack", err)
	fixed := Fix(planA, err)
	err = Check(fixed, 60)
	report("plan A, fixed", err)
	battery := 60.0
	var low *EnergyError
	if errors.As(err, &low) { // As finds it inside the joined error
		battery = 100 // the operator fits a full pack
	}
	// The operator's edits: a detour south of the mast and a turn inside the fence's corner.
	planB := slices.Insert(slices.Clone(fixed), 2, drone.Vec3{X: 75, Y: 55, Z: 40})
	planB = slices.Insert(planB, 0, drone.Vec3{X: 100, Y: -20, Z: 40})
	if err := Check(planB, battery); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("plan B on a %.0f%% pack: no problems, %d waypoints, needs %.1f%% with the reserve\n", battery, len(planB), energy(planB)+reserve)
	if err := fly(planB, battery).Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

The limits print as under 115 m, within 210 m, 8 m from the mast and a 25% reserve. Plan A has five problems: waypoint 2 is 218.4 m from home, over 210 m; waypoint 4 at 130 m is above the 115 m limit; leg 1 passes 4.0 m from the mast at 40 m; leg 3 leaves the fence at (192.9, 70.3, 40.0) although both its ends are inside; and it needs 72.6% of a 60% pack. Fix pulls waypoint 2 in to (197.1, 56.3, 40.0) and lowers waypoint 4 to 115 m. The re-check still finds the mast, the fence leg, now leaving at (176.6, 70.3, 40.0), and 69.1% of a 60% pack; errors.As finds the *EnergyError inside the joined error, so the operator fits a full pack. Plan B on a 100% pack has no problems, 6 waypoints, and needs 71.9% with the reserve. Flown, it climbs no higher than 114.7 m, comes no closer than 23.2 m to the mast, spends 0 steps outside the fence or the link, and lands at home having used 45.4% against the 46.9% planned.

05

What a program may fix, and what it may not

Some repairs only make a plan safer: lowering an altitude under a limit, pulling a waypoint towards home. A program may apply them and say so. Others are decisions: going around an obstacle or over it, rerouting inside a fence, swapping a pack, accepting a smaller margin. Hand those to the operator with the data from the typed error, and check again after every edit, since one fix can create another problem. The vehicle keeps its own checks. PX4 runs mission feasibility checks when a mission is uploaded and before it starts, for example for conflicts with a geofence or missing take-off and landing items, and will not start a mission that fails them. ArduPilot's pre-arm checks refuse to arm on problems such as a fence that needs a position the vehicle does not have yet, or a battery below its arming voltage. Your checks come first, theirs are the backstop, and neither replaces looking at the site.

06

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go, then tap Run. The console shows each round of checks; Output replays plan B in flight.gfflight with the L-shaped fence, the mast as a grey disc labelled with its height, the dashed link circle, the detour south of the mast and the climb to 115 m in the altitude strip. Lower hClear or linkPad and watch which problems disappear from the report, or move the mast onto the detour.

TAKE THIS WITH YOU

Check every leg, including the return home, against the fence, the legal and configured height with a margin, obstacle clearance, the tested link range and the energy reserve. Return all problems as typed errors joined with errors.Join, let code repair only what can only get safer, leave decisions to the operator, and check again after every change.

Check your understanding

Both ends of a mission leg are inside a concave, L-shaped geofence. Why can the leg still breach the fence?

Go to the source

Progress stays in this browser. No account needed.