Missions, safety and fleets · 6 MIN READ

Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern

Model a mission as numbered MAVLink-style items with acceptance radii and hold times, explain how MISSION_COUNT, MISSION_REQUEST_INT, MISSION_ITEM_INT and MISSION_ACK move it to the vehicle with retries, and generate and fly a lawnmower survey.

An autonomous flight is a list of numbered mission items that the flight controller executes one after another: take off, fly to a point, wait, come back, land. The ground station builds that list, moves it onto the vehicle intact over a lossy radio link, and then watches progress. Each step has a classic failure: a waypoint that is never reached, an upload that leaves half of the old mission on board, a survey whose legs leave gaps between camera footprints.

drones · A MAP OF THE IDEA

  1. Generate mission items
  2. Upload on request
  3. Verify plan on board
  4. Fly and track progress

Useful when

  • Lost messages are repaired by re-requesting one sequence number.
  • A generated survey covers the area with a known overlap.

Watch out

  • Uploads may not be atomic; verify the stored plan before arming.
  • Acceptance radius trades corner cutting against slow arrivals.

Implementation & operation cost: A mission builder, an uploader with timeouts and retries, and a download-and-compare check before every flight.

01

Mission items and when they count as done

A MAVLink mission item is a MAV_CMD number with seven parameters, a frame and a sequence number. NAV commands move the vehicle: MAV_CMD_NAV_TAKEOFF (22) climbs to the altitude in param7, MAV_CMD_NAV_WAYPOINT (16) flies to a position with a hold time in param1 and an acceptance radius in param2, MAV_CMD_NAV_LOITER_TIME (19) stays for param1 seconds, and MAV_CMD_NAV_RETURN_TO_LAUNCH (20) and MAV_CMD_NAV_LAND (21) end the flight. DO commands, such as a camera trigger or a speed change, run between NAV commands. A waypoint is complete when the vehicle enters its acceptance radius; flight stacks differ in whether they honour param2 or use a vehicle-wide radius parameter, so check your autopilot's mission command list. A tiny radius makes the vehicle slow down and fight the wind to hit an exact point; a large one cuts corners, which matters next to a fence. Holds and loiters stop the vehicle, which suits a photo or a sensor reading, not a survey leg.

02

Moving a mission over a lossy link

The upload is driven by the vehicle. The ground station sends MISSION_COUNT; the vehicle answers MISSION_REQUEST_INT for seq 0; the ground station sends MISSION_ITEM_INT with seq 0; the vehicle asks for seq 1, and so on until it sends MISSION_ACK with MAV_MISSION_ACCEPTED or an error. Because the receiver asks for every item by number, a lost message is repaired by asking again. The MAVLink specification recommends resending after 1500 ms by default (250 ms for plan items) and giving up after 5 retries; out-of-sequence messages are recoverable, timeouts are not errors, and an error ACK ends the transfer and should leave the stored mission unaltered. Downloads run the same exchange the other way, starting with MISSION_REQUEST_LIST, and geofences and rally points use the same protocol with a different mission_type. Link, Item and the message types in the sketch stand in for a MAVLink library such as gomavlib.

go
func Upload(ctx context.Context, link Link, items []Item) error {
	last := Message(MissionCount{Count: uint16(len(items))})
	for retries := 0; retries <= 5; {
		if err := link.Send(last); err != nil {
			return err
		}
		// Receive returns only mission messages from this vehicle.
		msg, err := link.Receive(ctx, 1500*time.Millisecond)
		switch m := msg.(type) {
		case MissionRequestInt:
			if int(m.Seq) >= len(items) {
				return fmt.Errorf("vehicle asked for item %d of %d", m.Seq, len(items))
			}
			last, retries = items[m.Seq].Encode(m.Seq), 0
		case MissionAck:
			if m.Type != MavMissionAccepted {
				return fmt.Errorf("upload rejected: %v", m.Type)
			}
			return nil
		default:
			if !errors.Is(err, ErrTimeout) {
				return err
			}
			retries++ // silence: send the same message again
		}
	}
	return errors.New("mission upload: no answer after 5 retries")
}
Read the code

The loop always sends last: first the count, then whichever item the vehicle asked for. A timeout resends the same bytes, a repeated MISSION_REQUEST_INT for the same seq is answered with the same item from the same slice, and progress resets the retry counter. Any ACK other than MAV_MISSION_ACCEPTED, a request beyond the list, a cancelled context or five silent timeouts end the upload with an error.

03

Idempotent uploads and stale plans

Retries mean duplicates: the vehicle may request item 7 twice because your first answer arrived late, and an operator may press Upload again after a dropout. Make every step safe to repeat: build the item list once, encode it deterministically, serve every request from that immutable list, and treat a repeated request as normal. On the vehicle, the specification asks that a new mission be fully uploaded and accepted before the old one is replaced, but ArduPilot documents that its uploads are not atomic, so a failed upload can leave a mix of old and new items, and that it stores home in seq 0. Newer MAVLink adds an opaque_id to MISSION_ACK, MISSION_COUNT and MISSION_CURRENT, so a ground station can tell whether the plan on board is the one it uploaded. After an interrupted upload, download the mission and compare it before arming, with tolerances, because the vehicle may round coordinates.

04

A lawnmower survey, flown item by item

Mapping flights cover an area with parallel legs flown in alternating directions, the boustrophedon or lawnmower pattern. The camera sets the spacing: the ground footprint across track is 2 h tan(HFOV/2), and side overlap, typically 60 to 80 percent for photogrammetry, shrinks the spacing to footprint times (1 - overlap). The generator rounds the number of legs up so they divide the area evenly and the last leg lies on the far edge. The program builds a mission of a take-off, twelve survey waypoints with a 2 m acceptance radius, a 5 s LOITER_TIME over the centre and an RTL, executes it item by item in a 2 m/s wind with gusts and prints when each item completed, the speed at that moment and the battery.

go
package main

import (
	"fmt"
	"log"
	"math"

	"gopherforge.app/drone"
)

// Command is the MAV_CMD_NAV_* number a MAVLink mission item carries.
type Command int

const (
	CmdWaypoint   Command = 16 // MAV_CMD_NAV_WAYPOINT
	CmdLoiterTime Command = 19 // MAV_CMD_NAV_LOITER_TIME
	CmdRTL        Command = 20 // MAV_CMD_NAV_RETURN_TO_LAUNCH
	CmdLand       Command = 21 // MAV_CMD_NAV_LAND
	CmdTakeoff    Command = 22 // MAV_CMD_NAV_TAKEOFF
)

func (c Command) String() string {
	switch c {
	case CmdWaypoint:
		return "WAYPOINT"
	case CmdLoiterTime:
		return "LOITER_TIME"
	case CmdRTL:
		return "RTL"
	case CmdLand:
		return "LAND"
	case CmdTakeoff:
		return "TAKEOFF"
	}
	return fmt.Sprintf("CMD_%d", int(c))
}

// Item is one mission item: what to do, where, and when it counts as done.
type Item struct {
	Seq    int
	Cmd    Command
	Pos    drone.Vec3
	Accept float64 // acceptance radius, m
	Hold   float64 // seconds to stay at the point
}

// Footprint is the width of ground a camera sees across track.
func Footprint(alt, hfovDeg float64) float64 { return 2 * alt * math.Tan(hfovDeg/2*math.Pi/180) }

// Lawnmower covers the rectangle x0..x1, y0..y1 with legs parallel to X,
// alternating direction. The spacing is at most maxSpacing, reduced so the
// legs divide the area evenly and the last one lies on the far edge.
func Lawnmower(x0, y0, x1, y1, alt, maxSpacing float64) (pts []drone.Vec3, spacing float64) {
	legs := int(math.Ceil((y1-y0)/maxSpacing)) + 1
	spacing = (y1 - y0) / float64(legs-1)
	for i := 0; i < legs; i++ {
		y := y0 + float64(i)*spacing
		a, b := x0, x1
		if i%2 == 1 {
			a, b = x1, x0
		}
		pts = append(pts, drone.Vec3{X: a, Y: y, Z: alt}, drone.Vec3{X: b, Y: y, Z: alt})
	}
	return pts, spacing
}

// BuildMission turns survey points into a numbered mission.
func BuildMission(alt float64, survey []drone.Vec3) []Item {
	items := []Item{{Cmd: CmdTakeoff, Pos: drone.Vec3{Z: alt}}}
	for _, p := range survey {
		items = append(items, Item{Cmd: CmdWaypoint, Pos: p, Accept: 2})
	}
	centre := drone.Vec3{X: 0, Y: 30, Z: alt}
	items = append(items, Item{Cmd: CmdLoiterTime, Pos: centre, Accept: 1, Hold: 5})
	items = append(items, Item{Cmd: CmdRTL})
	for i := range items {
		items[i].Seq = i
	}
	return items
}

// Execute flies one item and reports whether it completed in time.
func Execute(sim *drone.Sim, d *drone.Drone, it Item) error {
	var err error
	switch it.Cmd {
	case CmdTakeoff:
		if err = d.Arm(); err == nil {
			err = d.TakeOff(it.Pos.Z)
		}
		if err == nil && !sim.RunUntil(60, func(float64) bool { return d.State().Mode == drone.Hold }) {
			err = fmt.Errorf("take-off timed out")
		}
	case CmdWaypoint, CmdLoiterTime:
		if err = d.GoTo(it.Pos); err != nil {
			return err
		}
		reached := func(float64) bool { return d.State().Pos.Sub(it.Pos).Len() < it.Accept }
		if !sim.RunUntil(90, reached) {
			return fmt.Errorf("item %d: not within %.0f m after 90 s", it.Seq, it.Accept)
		}
		if it.Hold > 0 {
			sim.Run(it.Hold, nil)
		}
	case CmdLand:
		err = d.Land()
		if err == nil && !sim.RunUntil(120, func(float64) bool { return d.State().Landed }) {
			err = fmt.Errorf("landing timed out")
		}
	case CmdRTL:
		err = d.ReturnHome()
		if err == nil && !sim.RunUntil(180, func(float64) bool { return d.State().Landed }) {
			err = fmt.Errorf("return timed out")
		}
	}
	return err
}

func main() {
	footprint := Footprint(20, 70) // 20 m up, 70 degree lens
	maxSpacing := footprint * (1 - 0.7)
	survey, spacing := Lawnmower(-30, 10, 30, 50, 20, maxSpacing)
	mission := BuildMission(20, survey)
	fmt.Printf("footprint %.1f m, 70%% sidelap: legs at most %.1f m apart\n", footprint, maxSpacing)
	fmt.Printf("survey 60 x 40 m at 20 m: %d legs %.1f m apart, %d mission items\n", len(survey)/2, spacing, len(mission))

	sim := drone.New(drone.Config{Wind: drone.Vec3{X: 2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 11})
	d := sim.Drone()
	fmt.Println("seq  command      target               done at  speed     battery")
	start := 0.0
	for _, it := range mission {
		if err := Execute(sim, d, it); err != nil {
			log.Fatal(err)
		}
		st := d.State()
		target := it.Pos.String()
		if it.Cmd == CmdRTL {
			target = "home " + d.Home().String()
		}
		fmt.Printf("%3d  %-11s  %-19s  %6.1f s  %3.1f m/s  %5.1f%%\n", it.Seq, it.Cmd, target, sim.Time(), st.Vel.Len(), st.Battery)
		if it.Cmd == CmdTakeoff {
			start = sim.Time()
		}
	}
	st := d.State()
	fmt.Printf("survey and return took %.0f s; landed %.1f m from home\n", sim.Time()-start, st.Pos.Horizontal().Len())
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

At 20 m a 70 degree lens sees a 28.0 m strip and 70 percent sidelap allows at most 8.4 m between legs, so the 40 m depth needs 6 legs exactly 8.0 m apart and the mission has 15 items. Take-off completes at 8.3 s. Every waypoint completes while the drone still moves at 4.0 to 4.7 m/s, because the 2 m radius starts the next leg before it stops. Each 60 m leg takes about 8 s, and the battery shows the wind: eastbound legs with the 2 m/s wind behind cost 1.9 to 2.1 percent, westbound legs into it 2.6 to 2.7, because drain grows with airspeed. The loiter completes at 80.5 s, stopped, after its hold, and RTL lands at 98.9 s with 74.3 percent, 0.2 m from home.

05

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go: its Square helper is unused here and does not clash. Tap Run to see the timeline in the console, then open Output: the replay of flight.gfflight draws the survey waypoints and the loiter point, the trail, the wind arrow and the altitude strip. Try 50 percent sidelap or a 5 m acceptance radius and compare the times and the corners in the replay.

TAKE THIS WITH YOU

A mission is a list of numbered items, each with a completion rule: an acceptance radius, a hold time or a landing. Upload it with the vehicle-driven MAVLink handshake, resend on timeouts, serve repeated requests from one immutable list, verify the stored plan before arming, and derive survey spacing from the camera footprint and overlap.

Check your understanding

In a MAVLink mission upload, which side asks for each item, and how?

Go to the source

Progress stays in this browser. No account needed.