Operations: links, logs, rules and fleets in service · 6 MIN READ
Flight logs: fixed-rate records, events, CSV export, per-flight metrics and anomaly rules
Record state and telemetry at a fixed rate and mode changes as events, export the log as CSV without flooding the console, compute distance, maximum altitude, time per mode and battery per kilometre, and run anomaly rules for sudden battery drops, GPS divergence and mode flapping on a flight that has problems.
Every incident investigation starts with the log, and so does every improvement: the consumption model in the energy-planning lesson is fitted from logged flights. A log is only as good as what it recorded, at what rate, and the questions asked of it. Reading each log by hand does not scale past a handful of flights, so the useful part is automatic: a few metrics per flight to compare over time, and rules that flag the flights someone should look at.
drones · A MAP OF THE IDEA
- Sample at a fixed rate
- Log events when they occur
- Compute metrics per flight
- Run rules, test with faults
Useful when
- Rules check every flight, not just the ones that went wrong.
- Fixed-rate rows make windows and integrals simple.
Watch out
- A sampled mode column misses changes shorter than a row.
- Summing noisy GPS overstates the distance flown.
Implementation & operation cost: A logger in the flight loop, a CSV or binary writer, and a rule set whose thresholds are tested against injected faults.
Samples and events
Two kinds of record belong in a log. Samples are taken at a fixed rate: position, sensor readings, battery, mode. A fixed rate makes windows, rates and integrals simple, because each row covers the same time. Events are written when they happen: a mode change, a failsafe, a command, an arrival. A sampled mode column at 5 Hz cannot show a mode that lasts one 20 ms step, so the mode-change list is the only faithful record of what the autopilot did. Real flight stacks log far more, far faster. ArduPilot writes dataflash logs on the autopilot from the first arming, chooses what to record with LOG_BITMASK, and logs at up to the scheduler's loop rate, normally 400 Hz on Copter. PX4 writes ULog, a self-describing format that carries the format and uORB message types it logs, each message at its own rate with a timestamp. Analysis tools resample them onto a common timeline.
CSV for people, summaries for the console
CSV is the format every spreadsheet and plotting tool reads, and encoding/csv writes it correctly, quoting fields only when they need it. Give it a header row, fixed decimals and units in the column names or the documentation, and write mode names rather than numbers. Then write the file, but never print it: the 76 s flight in this lesson is already 383 rows and 22 kB at 5 Hz, and a log at hundreds of hertz reaches megabytes per flight, which is why flight stacks log in binary. The console gets a summary: the header, the first and last rows, and the size. CSV also loses types, so a reader has to parse every number back and agree on the column order; keep a version number or the header next to the data.
Metrics from one flight
A few numbers per flight, stored with the log, turn a pile of flights into trends: duration, distance, maximum altitude, time in each mode and battery used per kilometre. Compute them from the right column. Distance summed from raw GPS fixes is too long, because every noisy fix adds a little zigzag to the track; sum the autopilot's estimate, or smooth and decimate GPS first. Battery per kilometre over a whole flight includes the climb, the hovering and the landing, so compare it between similar missions, not with the cruise figure of a calibration. A pack whose battery per kilometre creeps up over weeks of similar flights is ageing before any failsafe notices.
A flight with two problems
The program flies a survey in a 4 m/s wind with mission code that has a bug: when the drone reports HOLD, it checks that the GPS fix is within 1 m of the waypoint, tighter than the GPS error, and sends the waypoint again if not. On the way home a GPS outage of 6 s begins, as under a bridge. The logger appends one row per 5 Hz report, with the position the autopilot flies on (the true state in the simulator, the EKF estimate in a real log), the GPS fix, the barometer, the battery and the mode, and appends a mode change whenever one happens. The program prints the CSV summary, the metrics and the findings of three rules, the vehicle's GPS events, and the battery rule run on a copy of the log with a fault injected.
package main
import (
"encoding/csv"
"fmt"
"log"
"math"
"strconv"
"strings"
"gopherforge.app/drone"
)
// Row is one fixed-rate sample: the position the autopilot flies on (the true
// state here, the EKF estimate in a real log) and what the sensors said.
type Row struct {
T float64
Pos, GPS drone.Vec3
Baro float64
Battery float64 // the battery monitor, %
Mode drone.Mode
}
// Change is a mode change, logged when it happens rather than sampled.
type Change struct {
T float64
From, To drone.Mode
}
type Log struct {
Rows []Row
Changes []Change
}
// CSV writes the rows for a spreadsheet or a plotting tool.
func (l *Log) CSV() (string, error) {
var b strings.Builder
w := csv.NewWriter(&b)
w.Write([]string{"t", "x", "y", "z", "gps_x", "gps_y", "gps_z", "baro", "battery", "mode"})
f := func(v float64) string { return strconv.FormatFloat(v, 'f', 2, 64) }
for _, r := range l.Rows {
w.Write([]string{f(r.T), f(r.Pos.X), f(r.Pos.Y), f(r.Pos.Z), f(r.GPS.X), f(r.GPS.Y), f(r.GPS.Z),
f(r.Baro), f(r.Battery), r.Mode.String()})
}
w.Flush()
return b.String(), w.Error()
}
// BatteryDrop flags a fall of more than 2 points within 1 s: the airframe
// cannot drain faster than about 1 %/s, so it is a cell, a connector or the sensor.
func BatteryDrop(l *Log) (out []string) {
last := -10.0
for i := 5; i < len(l.Rows); i++ {
if drop := l.Rows[i-5].Battery - l.Rows[i].Battery; drop > 2 && l.Rows[i].T-last > 5 {
last = l.Rows[i].T
out = append(out, fmt.Sprintf("%5.1f s battery fell %.1f points in 1 s", last, drop))
}
}
return out
}
// Divergence flags GPS more than 5 m from the position the autopilot uses.
func Divergence(l *Log) (out []string) {
start, worst := math.Inf(1), 0.0
for i, r := range l.Rows {
d := r.GPS.Sub(r.Pos).Horizontal().Len()
if d > 5 {
start, worst = math.Min(start, r.T), math.Max(worst, d)
}
if worst > 0 && (d <= 5 || i == len(l.Rows)-1) {
out = append(out, fmt.Sprintf("%5.1f s GPS off the position for %.1f s, up to %.1f m", start, r.T-start, worst))
start, worst = math.Inf(1), 0
}
}
return out
}
// Flapping flags 6 or more mode changes, each less than 5 s after the last.
func Flapping(l *Log) (out []string) {
c := l.Changes
for i := 0; i+5 < len(c); {
j := i
for j+1 < len(c) && c[j+1].T-c[j].T < 5 {
j++
}
if j-i+1 >= 6 {
out = append(out, fmt.Sprintf("%5.1f s %d mode changes in %.1f s, %s and %s", c[i].T, j-i+1, c[j].T-c[i].T, c[i].From, c[i].To))
}
i = j + 1
}
return out
}
func report(rule string, found []string) {
if len(found) == 0 {
fmt.Printf(" %-15s none\n", rule)
}
for _, f := range found {
fmt.Printf(" %-15s %s\n", rule, f)
}
}
func main() {
sim := drone.New(drone.Config{Wind: drone.Vec3{X: 4}, Gust: 1, MaxSpeed: 10, Seed: 2})
d := sim.Drone()
if err := d.Arm(); err != nil {
log.Fatal(err)
}
d.TakeOff(20)
wps := []drone.Vec3{{X: 60, Z: 20}, {X: 60, Y: 40, Z: 20}, {X: 0, Y: 40, Z: 20}, {X: 0, Y: 80, Z: 20}, {X: 60, Y: 80, Z: 20}, {Z: 20}}
var lg Log
i, sent, logged, mode, outage := -1, -10.0, -1.0, d.State().Mode, false
// The flight controller logs a mode change when it happens.
changed := func(t float64) {
if m := d.State().Mode; m != mode {
lg.Changes = append(lg.Changes, Change{t, mode, m})
mode = m
}
}
sim.RunUntil(300, func(t float64) bool {
changed(t)
st, tel := d.State(), d.Telemetry()
if tel.Time != logged { // one row per 5 Hz report
logged = tel.Time
lg.Rows = append(lg.Rows, Row{t, st.Pos, tel.GPS, tel.BaroAlt, st.Battery, st.Mode})
}
// The mission code, with a bug: when the drone reports HOLD it checks
// the GPS within 1 m of the waypoint, less than the GPS error, and
// sends the waypoint again if the check fails.
if tel.Mode == drone.Hold && t-sent >= 1 && i < len(wps) {
if i < 0 || tel.GPS.Sub(wps[i]).Horizontal().Len() < 1 {
i++
}
if i < len(wps) {
d.GoTo(wps[i])
} else {
d.Land()
}
sent = t
changed(t)
}
if !outage && i == len(wps)-1 && st.Pos.Horizontal().Len() < 45 {
outage = true
d.LoseGPS(6) // under a bridge
}
return st.Landed
})
text, err := lg.CSV()
if err != nil {
log.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(text), "\n")
fmt.Printf("log: %d rows at 5 Hz, %d mode changes, CSV %d bytes\n", len(lg.Rows), len(lg.Changes), len(text))
fmt.Printf(" %s\n %s\n ...\n %s\n", lines[0], lines[1], lines[len(lines)-1])
var dist, gpsDist, maxAlt float64
inMode := make([]float64, drone.Crashed+1)
for k, r := range lg.Rows {
if k > 0 {
dist += r.Pos.Sub(lg.Rows[k-1].Pos).Horizontal().Len()
gpsDist += r.GPS.Sub(lg.Rows[k-1].GPS).Horizontal().Len()
}
maxAlt = math.Max(maxAlt, r.Baro)
inMode[r.Mode] += 0.2
}
first, last := lg.Rows[0], lg.Rows[len(lg.Rows)-1]
used := first.Battery - last.Battery
fmt.Printf("metrics\n %.1f s, %.0f m flown (%.0f m by summing GPS), max altitude %.1f m (baro)\n", last.T, dist, gpsDist, maxAlt)
fmt.Print(" time per mode:")
for m, s := range inMode {
if s > 0 {
fmt.Printf(" %s %.1f s", drone.Mode(m), s)
}
}
fmt.Printf("\n battery used %.1f points, %.1f per km; landed %.1f m from home\n", used, used/(dist/1000), last.Pos.Horizontal().Len())
fmt.Println("anomalies")
report("battery drop", BatteryDrop(&lg))
report("GPS divergence", Divergence(&lg))
report("mode flapping", Flapping(&lg))
for _, e := range sim.Events() {
if strings.Contains(e.Text, "GPS") {
fmt.Printf(" vehicle event %5.1f s %s\n", e.T, e.Text)
}
}
// The simulator has no failing cells, so test the battery rule on a copy
// of the log with a fault injected.
bad := Log{Rows: append([]Row(nil), lg.Rows...)}
for k := 150; k < len(bad.Rows); k++ { // from 30 s on, at 5 rows a second
bad.Rows[k].Battery -= 6
}
fmt.Println("the same log with the battery reading 6 points low from 30 s")
report("battery drop", BatteryDrop(&bad))
if err := sim.Save(); err != nil {
log.Fatal(err)
}
}The log holds 383 rows and 30 mode changes; the CSV is 22142 bytes and only its header, the first row (0.00, TAKEOFF) and the last (76.40, LAND, battery 78.73) are printed. The drone flew 357 m, but summing GPS gives 523 m. Time per mode is TAKEOFF 8.4 s, HOLD 9.0 s, GOTO 45.4 s and LAND 13.8 s, and 21.3 points were used, 59.6 per km. The battery rule finds nothing. GPS divergence starts at 60.2 s and lasts 5.6 s, up to 32.4 m; the vehicle events explain it: 'GPS lost for 6 s' at 59.6 s, 'no GPS for 3 s: landing' at 62.6 s and 'GPS fix back' at 65.6 s, and the drone landed 16.2 m from home. Mode flapping at 16.2 s is 16 mode changes in 7.3 s between GOTO and HOLD at the first waypoint, each one a resend that the 5 Hz rows barely see. With 6 points removed from 30 s on, the battery rule fires at 30.0 s: battery fell 6.2 points in 1 s.
Anomaly rules and their thresholds
Base every threshold on physics or on the sensor's specification, not on what looked odd once. This airframe cannot drain more than about 1 percent per second, so a fall of more than 2 points in a second is a cell, a connector or the sensor. GPS more than 5 m from the estimate is several times the GPS error. Six mode changes, each within 5 s of the last, is not a pilot changing their mind. Report episodes, with a start, a duration and a worst value, not one finding per row. Test each rule with an injected fault, as the program does for the battery, because a rule that never fires may simply be broken. Then follow the findings to causes: here the flapping is a mission bug and the divergence an outage the failsafe handled. PX4's log analysis guide adds checks a real log allows: whether the controllers tracked their setpoints, vibration above about 2 to 3 m/s/s peak to peak, and a log that ends in the air, which points to a power failure or a hard fault.
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 the summary and the findings; Output replays flight.gfflight, with the waypoint markers piled up on the first corner where the mission kept resending it, and the landing short of home after the outage. Change the 1 m check to 3 m and run again: the flapping finding should disappear while the GPS divergence stays.
TAKE THIS WITH YOU
Log samples at a fixed rate and events when they happen, export CSV to files rather than the console, and compute a few metrics per flight from the estimate rather than raw GPS. Run anomaly rules with physically justified thresholds that report episodes, and test every rule with an injected fault before trusting its silence.
Check your understanding
Mission code resends a waypoint whenever the GPS fix is more than 1 m from it, and the log shows GOTO and HOLD alternating every second there. What is wrong?
Go to the source
Progress stays in this browser. No account needed.