{"guides":[],"hints":[{"hint":"Ask what happens to the aircraft if that loop misses its deadlines for 50 ms, or if the companion computer reboots in flight.","lessonID":"drones.architecture","nuance":"Companions send setpoints; the flight controller closes the rate, attitude and position loops on an RTOS and keeps flying, with a failsafe, if the companion stops. PX4 Offboard requires a steady 2 Hz setpoint stream for that reason."},{"hint":"A Fallback lists alternatives in priority order. When does trying the next alternative stop making sense?","lessonID":"drones.behaviour-trees","nuance":"Failure means this alternative does not apply, so the Fallback tries the next. Success or Running ends the tick there, which is why safety branches go first and halt the mission behind them."},{"hint":"In steady following the outer loop must command 3 m/s. With only P, what error produces that command?","lessonID":"drones.cascaded-control","nuance":"Steady wind is different: the velocity loop's integral cancels it, and the P hold stayed within 0.12 m. An outer integral also removes the lag, after a 4.29 m transient; feedforward stayed within 0.77 m."},{"hint":"Each second the velocity path pushes the estimate by b, and the barometer path pulls it back by the error divided by tau. Where do they balance?","lessonID":"drones.complementary-filter","nuance":"The program's tau 1 s row has a mean error of 0.12 m and tau 3 s has 0.30 m, close to 0.10 m/s times tau. Estimating the bias as a third state removes the offset."},{"hint":"List everything that lies between a point on the grid and a real surface: the airframe, what the controller and the map get wrong, and where inside a cell things can be.","lessonID":"drones.configuration-space","nuance":"The airframe alone leaves no room for gusts or map error. On a grid the obstacle can be anywhere in its cell, so measure to the cell's edge, and the drone anywhere in its own, so add half a diagonal."},{"hint":"ENU is x east, y north, z up; NED is x north, y east, z down. Swap the horizontal axes and flip one sign.","lessonID":"drones.coordinates","nuance":"Swapping x and y and negating z keeps both frames right-handed. Headings change too: NED heading runs clockwise from north and ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw."},{"hint":"Expand the airspeed squared on each leg and sum over the loop: what does the term with the wind direction add up to when you end where you started?","lessonID":"drones.energy-planning","nuance":"Airspeed squared is v squared minus 2v times u.w plus w squared; summed over a loop at constant ground speed the middle term is zero. A headwind leg capped at the top airspeed slows down and breaks the symmetry."},{"hint":"Ask what a single percentage threshold knows about where the vehicle is and which way the wind blows on the way back.","lessonID":"drones.failsafes","nuance":"The charge needed to get home grows with distance and headwind. A budget checked every second turns back earlier when the vehicle is far away or downwind, and later when it is close to home."},{"hint":"The first request may well have succeeded; only its response was lost. What must the retry get so that no second drone takes off?","lessonID":"drones.fleet-backend","nuance":"Same key and same body: replay the stored response. Same key with another body: 422. A retry while the first request is still running: 409. Only a new key creates a new mission."},{"hint":"Layered routes cross directly above each other. Which of the two distances still protects them at the crossing point?","lessonID":"drones.fleets","nuance":"Either distance is enough. At a crossing the horizontal distance falls to zero and the layer spacing carries the separation, so it must exceed the vertical minimum plus altitude error."},{"hint":"Compare the 1 m check with how far a GPS fix wanders from the true position while the drone holds still.","lessonID":"drones.flight-logs","nuance":"The autopilot holds on its own estimate and reports HOLD; a raw GPS fix within 1 m fails about half the time, and every resend flips the mode. Use the autopilot's arrival or a radius above the GPS error."},{"hint":"A table lists every allowed path. What does that imply for an event with no matching row, and what should the operator see?","lessonID":"drones.flight-modes","nuance":"Rejections matter as much as transitions in the log: they explain why the drone did not move. Guards add reasons to rows that exist; a missing row means the request is never valid in that state."},{"hint":"A sector is free when no beam in it hit anything. Compare the width of the drone with the gap those free beams passed through.","lessonID":"drones.gap-following","nuance":"Each reading must block every sector within asin((radius + margin) / d) of its bearing. Then a 0.6 m gap closes for a drone with a 0.3 m contact radius, and near obstacles block wide arcs."},{"hint":"Compare where the fence check triggers with how far a vehicle at 8 m/s travels while braking at about 4 m/s squared.","lessonID":"drones.geofencing","nuance":"Most fence actions trigger once the position is outside. At 8 m/s braking at 4 m/s2 the vehicle still covers about 8 m, so use a contingency boundary inside the fence or predict the breach from velocity."},{"hint":"The reports keep arriving on time, so look at what they say, not when they came. What would real GPS noise never do?","lessonID":"drones.gps-denied","nuance":"Message age checks the link, not the source. Telemetry can be fresh while its position is frozen, so check the receiver's fix flag and treat exactly repeated positions as a dead source."},{"hint":"Read is a blocking call on the connection itself. Does it know about any context.Context?","lessonID":"drones.ground-station","nuance":"net.Conn.Read never looks at a context. Close the connection, or set a read deadline in the past, and it returns an error. Cancel first so the other goroutines stop, then close, then wait."},{"hint":"Without a fix the drone cannot hold its position. Compare 7 m with how far a 6 m/s wind carries it before the failsafe gets it down.","lessonID":"drones.incident-analysis","nuance":"Stand-off must be measured along the wind, against the drift budget of an outage: about 44 m to touchdown here. Inspecting from the lee side turns the same drift away from the structure."},{"hint":"Ask what the controller measures: the distance from its GPS position to a point on the site plan, or the distance to the mast itself.","lessonID":"drones.inspection-orbit","nuance":"A GPS orbit flies a good circle around the wrong centre: a 3.9 m map error swung the standoff from 3.8 to 12.2 m while the controller believed it was within 0.6 m. A rangefinder measures the standoff itself."},{"hint":"Write K = P00 / (P00 + R). Which quantity shrinks as the filter converges, and which one comes from the sensor?","lessonID":"drones.kalman-filter","nuance":"With constant Q, R and sample rate the gain converges to a fixed value, 0.384 for altitude here, and the filter behaves like an alpha-beta filter. The covariance still drives gates and resets."},{"hint":"The time package says a ticker adjusts the interval or drops ticks to make up for slow receivers. How many ticks can be waiting at once?","lessonID":"drones.loop-timing","nuance":"Since Go 1.23 timer channels are unbuffered and Stop or Reset discard stale ticks, but a late receiver still gets one tick at once. Measure dt with the monotonic clock instead of assuming the period."},{"hint":"The CRC_EXTRA byte is never transmitted. Where does each side get it from, and what would make the two values differ?","lessonID":"drones.mavlink-frames","nuance":"CRC_EXTRA comes from the message name and its fields' types and names, so a receiver generated from other XML computes another CRC and drops the frame. It cannot detect forgery: anyone can compute a CRC; only signing helps."},{"hint":"Ask what happens to the vehicle if each one is lost: a slow heading drift, a small change of height, or a tilt it cannot correct.","lessonID":"drones.motor-mixing","nuance":"Clipping each motor separately is the worst option: in the program's last case it cut roll to +0.20 and added a pitch of +0.10 nobody asked for, coupling the axes."},{"hint":"Count how many misses of -0.4 it takes to undo 131 hits of +0.85, and then how many it takes from 3.5.","lessonID":"drones.occupancy-grid","nuance":"Unclamped, evidence piles up without limit: a cell hit 131 times needs 273 beams through it to read free. Clamping bounds both certainty and inertia, so the map can follow a site that changes."},{"hint":"Compare the Manhattan distance of one diagonal step with what that step actually costs on the grid.","lessonID":"drones.path-planning","nuance":"With diagonals allowed, Manhattan counts a diagonal step as 2 instead of 1.41. That overestimate makes A* trust a wrong ordering, so the first path to reach the goal is no longer guaranteed shortest."},{"hint":"Write error = setpoint - measurement and differentiate it. Which part changes instantly when a new altitude is commanded?","lessonID":"drones.pid-altitude","nuance":"While the setpoint is constant both forms give the same D term. They differ only at setpoint changes, where d(error)/dt contains the step divided by dt; noise still needs a low-pass filter either way."},{"hint":"Add up the pull towards the goal and the pushes from the three walls at the point where the drone stopped.","lessonID":"drones.potential-fields","nuance":"Inside the U the walls push back as hard as the goal pulls, so the gradient is zero away from the goal. No gain removes that; it takes an escape such as wall following, or a planner."},{"hint":"Think about what the gate already handles by pausing the descent, and what it cannot handle: no reading at all, or a reading that jumps far outside the gate low down.","lessonID":"drones.precision-landing","nuance":"A small error only pauses the descent until the drone is centred again. Losing the pad, or a jump far outside the gate near the ground, means the sensor or the wind has won, so climb back to where the pad is easy to see."},{"hint":"Draw an L-shaped fence, put one waypoint in each arm, and join them with a straight line.","lessonID":"drones.preflight-checks","nuance":"Being inside at both ends says nothing about a concave shape in between; test the segment against every edge or sample it finely. Obstacles stand between waypoints too, so check them along the legs."},{"hint":"Shrinking searches for the smallest world that still shows the bug. Which result of a re-flight tells you that a simplification removed nothing that mattered?","lessonID":"drones.property-testing","nuance":"Keep a change only if the same property still fails; a different failure is a different bug. Whatever survives, here one leg, one obstacle and a gust, points at the cause."},{"hint":"The vehicle keeps flying its last command while its own timer runs. Multiply the speed by the timeout, then add the braking.","lessonID":"drones.radio-link","nuance":"At 8 m/s a 5 s timeout carries it about 40 m past the edge before RTL even starts, plus a few metres of braking, so size the margin and check the way home for that overshoot, not for the edge."},{"hint":"Think about what the sensor reports when no pulse comes back, and what averaging 40 m into a real 18 m reading would do.","lessonID":"drones.rangefinders","nuance":"The maximum is a code for 'no echo', not a distance. OBSTACLE_DISTANCE uses max_distance + 1 for no obstacle and UINT16_MAX for unknown; averaging either with real ranges invents or hides obstacles."},{"hint":"Compare the 3 m threshold with v times the reaction time plus v squared over 2a at both speeds.","lessonID":"drones.reactive-avoidance","nuance":"At 8 m/s with 0.3 s and 5 m/s2 the drone needs 8.8 m to stop. Limiting speed so that this distance always fits in the free corridor, v = k (free - d_stop), keeps it safe at every speed."},{"hint":"The FAA's rule allows at most 1.0 s from measuring a position to broadcasting it. Compare the time mark with a clock you trust.","lessonID":"drones.remote-id","nuance":"A frame measured 3 s ago may be a delayed or replayed copy, and using it moves the track backwards. Drop it, count it, and keep showing the last fresh position with its age."},{"hint":"Ask which properties must hold in every world whatever the tuning: the fence, the landing, the speed, the reserve.","lessonID":"drones.simulation-testing","nuance":"Golden logs change with every harmless tweak. Invariants such as never leaving the fence and landing near home must always hold, and each row adds its expected outcome, such as a safe abort on low battery."},{"hint":"A corridor that crosses a survey area at the same height is harmless if the survey has already landed. Which dimensions must overlap together?","lessonID":"drones.strategic-deconfliction","nuance":"Overlap in one or two dimensions is not a conflict: a later window or a higher band separates the plans. Only when time, altitude band and buffered footprint all overlap can the drones meet."},{"hint":"Split the error into a constant part and a random part. Which of the two does averaging shrink?","lessonID":"drones.telemetry-noise","nuance":"Averaging shrinks independent noise by the square root of N but leaves the mean error untouched. Another sensor can estimate the offset only as well as its own error allows, and GPS altitude wanders by about a metre; EKFs model both."},{"hint":"time_boot_ms starts when the vehicle boots. How is it related to your clock, and what does it say about radio buffering?","lessonID":"drones.telemetry-streams","nuance":"time_boot_ms says when the estimate was made, on another clock that restarts at reboot and drifts. Ages, rates and gaps belong on your monotonic clock at receipt; keep time_boot_ms for ordering and reboot detection."},{"hint":"Think about how a lost item gets repaired: whoever asks for items by number can simply ask again.","lessonID":"drones.waypoint-missions","nuance":"The ground station sends only MISSION_COUNT unprompted; the vehicle then pulls items by sequence number, so a loss is fixed by asking again. MISSION_ACK comes once, at the end, with the result."}],"id":"drones","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"drones.architecture","designGuide":{"cautions":["Latency and jitter grow with every layer above the firmware.","Disabling a failsafe in shipped software moves risk to people on the ground."],"cost":"A clear contract per layer: which messages cross each link, at what rate, and what happens when they stop.","family":"drones","flow":["Firmware closes loops","Companion sends setpoints","GCS monitors and commands","Backend plans and stores"],"ratings":[],"strengths":["Each layer can fail without taking down the one below it.","Go fits the networked layers with one static binary per target."]},"hint":"Ask what happens to the aircraft if that loop misses its deadlines for 50 ms, or if the companion computer reboots in flight.","id":"drones.architecture","introduction":"A drone that flies itself is several computers that trust each other only so far. A microcontroller runs the flight controller firmware and keeps the aircraft upright hundreds of times a second; a Linux computer on board may run mission logic, cameras and networking; a ground control station shows the operator what is happening; and a backend may coordinate many vehicles. Go is a strong fit for the last three and a poor fit for the first, and the reasons explain most design choices in this course.","nuance":"Companions send setpoints; the flight controller closes the rate, attitude and position loops on an RTOS and keeps flying, with a failsafe, if the companion stops. PX4 Offboard requires a steady 2 Hz setpoint stream for that reason.","objective":"Place each piece of drone software on the right computer, explain why the inner control loops stay in real-time firmware, and fly a first simulated take-off, hold and landing from Go.","question":"A team wants to move the multicopter attitude and rate controllers from PX4 into a Go service on the Linux companion computer. Where should those loops run?","references":["https://docs.px4.io/main/en/companion_computer/","https://ardupilot.org/dev/docs/companion-computers.html","https://www.faa.gov/uas/getting_started/remote_id","https://www.easa.europa.eu/en/domains/drones-air-mobility/operating-drone/open-category-low-risk-civil-drones"],"reviewAnswer":"On the flight controller, in real-time firmware","reviewPrompt":"Where does the attitude loop run?","sections":[{"body":"The flight controller is a microcontroller board, such as a Pixhawk-class STM32, running PX4 on the NuttX RTOS or ArduPilot (on ChibiOS for most boards), written in C and C++. It samples the IMU at hundreds of hertz to kilohertz, runs the state estimator (an EKF), the rate, attitude and position controllers and the motor mixer, and owns the failsafes. The companion computer is a Linux single-board computer, such as a Raspberry Pi or an NVIDIA Jetson, wired to the flight controller by a fast serial or Ethernet link and speaking MAVLink (or uXRCE-DDS for ROS 2 with PX4); it runs vision, mission logic, video and the connection to the outside world, often through a MAVLink router. The ground control station, such as QGroundControl or Mission Planner, talks MAVLink over a telemetry radio or IP. A fleet backend collects telemetry and logs from many vehicles and plans their work. Deadlines go from microseconds in the firmware to minutes in the backend.","title":"Four computers, four time scales"},{"body":"A multicopter is unstable: if the rate loop misses its deadlines for a few tens of milliseconds, the aircraft can tip over. Flight firmware runs on an RTOS with fixed priorities, no paging and no garbage collector, with the IMU on a short SPI bus next to the processor. A Go process on Linux adds scheduler jitter, garbage-collection pauses that are usually short but have no hard bound, and milliseconds of serial or USB latency; and if the companion crashes or reboots, something must still be flying the aircraft. So companions send setpoints (a position, a velocity, an attitude) and let the flight controller close the loops. PX4 makes the contract explicit: Offboard mode requires a continuous proof-of-life stream of at least 2 Hz and triggers the configured failsafe when it stops for longer than COM_OF_LOSS_T. Every layer should survive the failure of the layer above it.","title":"Why the inner loops stay in firmware"},{"body":"The program plays the companion computer: it sends high-level commands and watches the mode, while the simulator plays the flight controller that runs the loops and decides when a manoeuvre is complete. It first asks for a take-off before arming, then arms, climbs to 10 m, holds for five seconds in a 5 m/s wind with 2 m/s gusts and lands. A watch function prints every mode change with the simulated time, the altitude and the armed flag, and sim.Save writes the recording for the replay.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// A first flight. This program plays the companion computer: it sends\n// high-level commands (arm, take off, land) and watches the mode. The\n// simulator plays the flight controller: it runs the control loops, decides\n// when a manoeuvre is finished and changes the mode itself.\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 5}, Gust: 2, Seed: 1})\n\td := sim.Drone()\n\n\tlast := d.State().Mode\n\tfmt.Printf(\"t=%6.2f s  mode %s\\n\", sim.Time(), last)\n\twatch := func() {\n\t\tst := d.State()\n\t\tif st.Mode != last {\n\t\t\tfmt.Printf(\"t=%6.2f s  mode %-7s -> %-7s alt %5.2f m  armed=%t\\n\",\n\t\t\t\tsim.Time(), last, st.Mode, st.Pos.Z, st.Armed)\n\t\t\tlast = st.Mode\n\t\t}\n\t}\n\n\t// The flight controller is the authority: it refuses unsafe commands.\n\tif err := d.TakeOff(10); errors.Is(err, drone.ErrNotArmed) {\n\t\tfmt.Println(\"take-off before arming refused:\", err)\n\t}\n\n\tmust(d.Arm())\n\twatch()\n\tmust(d.TakeOff(10))\n\twatch()\n\tclimbed := sim.RunUntil(30, func(float64) bool {\n\t\twatch()\n\t\treturn d.State().Mode == drone.Hold\n\t})\n\tif !climbed {\n\t\tlog.Fatalf(\"did not reach 10 m: %+v\", d.State())\n\t}\n\n\t// Hold for five seconds in a 5 m/s wind with 2 m/s gusts: the position\n\t// loop tilts into the wind and pulls the drone back after each gust.\n\tdrift := 0.0\n\tsim.Run(5, func(float64) {\n\t\twatch()\n\t\tdrift = max(drift, d.State().Pos.Horizontal().Len())\n\t})\n\tfmt.Printf(\"held 5 s at %.2f m, largest drift %.2f m\\n\", d.State().Pos.Z, drift)\n\n\tmust(d.Land())\n\twatch()\n\tlanded := sim.RunUntil(60, func(float64) bool {\n\t\twatch()\n\t\treturn d.State().Landed\n\t})\n\tif !landed {\n\t\tlog.Fatalf(\"did not land: %+v\", d.State())\n\t}\n\n\tst := d.State()\n\tfmt.Printf(\"flight %.2f s, battery %.1f%%, %.2f m from home\\n\",\n\t\tsim.Time(), st.Battery, st.Pos.Horizontal().Len())\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A first flight from Go","walkthrough":"The early TakeOff returns \"drone: not armed\": the autopilot, not the caller, enforces preconditions. Arm and TakeOff change the mode at t=0.00 s; the autopilot itself switches TAKEOFF -> HOLD at t=4.64 s with the altitude at 9.72 m, because it ends the climb within 0.3 m of the target, and the hold settles at 10.00 m; the gusts never push it more than 0.16 m from home, because the position loop tilts into the wind and pulls it back. LAND starts at 9.64 s and LANDED follows at 19.18 s with armed=false, because the autopilot disarms on touchdown. The flight used 4.4% of the battery and touched down 0.27 m from home, and the last line is sim.Save reporting flight.gfflight."},{"body":"This is not legal advice; rules differ by country and change, so check your national aviation authority before flying. The common principles: keep the aircraft in visual line of sight (VLOS) unless you hold an authorisation for more; stay below the altitude limit, 120 m above the ground in the EU open category and 400 ft under the US Part 107 rules; register where required; and broadcast Remote ID where required. In the US, drones that must be registered have to comply with the Remote ID rule through built-in broadcast, a broadcast module, or by flying at an FAA-recognized identification area; in the EU many class-marked drones must broadcast direct remote identification. Controlled airspace near airports and published geographical zones need permission or are closed. For software this means geofences, altitude ceilings, link-loss and low-battery failsafes are requirements, not options: never ship code that disables them, and test in simulation, then with propellers removed, then in an open field.","title":"Safety and the rules, as principles"},{"body":"Go suits the layers that are mostly networking and concurrency. On the companion computer a single static binary, cross-compiled with GOOS=linux GOARCH=arm64, can read MAVLink from the flight controller, forward telemetry, run mission logic and talk to the cloud, with a goroutine per link. github.com/bluenviron/gomavlib implements MAVLink in Go and powers the mavp2p router; Gobot drives small drones such as the Tello. Ground-station services, telemetry pipelines and fleet backends are ordinary Go servers. The flight controller is the exception: TinyGo can run on microcontrollers, but the flight stacks people actually fly are C and C++ with years of flight testing, and your Go code should treat them as the authority.","title":"Where Go fits"},{"body":"In the app, choose New project > Robotics and simulation > Drone flight. Replace main.go with this lesson's program and keep mission.go: this program does not call Square, and the file still compiles next to it. Tap Run to see the mode changes in the console, then open Output: the replay of flight.gfflight shows the climb, the hold and the landing on the altitude strip, the wind arrow and the HUD with mode and battery.","title":"Fly it in GopherForge"}],"takeaway":"Keep the loops that hold the aircraft in the air on the flight controller, where an RTOS meets every deadline. Put Go where it is strong: companion computers, ground stations and fleet backends that send setpoints and missions, watch modes and telemetry, and survive being disconnected.","title":"Drone software architecture: flight controller, companion computer, ground station and fleet backend","unitID":"drones-foundations","wrongAnswers":["In the Go service, with GOGC tuned to avoid pauses","On the ground station, which has the most CPU"]},{"conceptTag":"drones.mavlink-frames","designGuide":{"cautions":["A CRC detects accidents, not attackers; sign links that matter.","Without a definition a receiver cannot validate a message."],"cost":"A generated dialect or a small hand-written codec per message, plus key management if you enable signing.","family":"drones","flow":["Order fields by size","Trim trailing zeros","CRC with CRC_EXTRA","Validate, zero-extend"],"ratings":[],"strengths":["Small fixed headers suit slow, lossy serial radios.","CRC_EXTRA catches mismatched message definitions."]},"hint":"The CRC_EXTRA byte is never transmitted. Where does each side get it from, and what would make the two values differ?","id":"drones.mavlink-frames","introduction":"MAVLink is the protocol PX4, ArduPilot, QGroundControl and most drone tooling speak. It is deliberately small: a 10-byte header, a payload of fixed-size little-endian fields and a 2-byte checksum, designed for slow and lossy serial radios. Building a frame by hand once is the best way to understand what every library does for you, and why one wrong byte or a mismatched message definition makes frames silently disappear.","nuance":"CRC_EXTRA comes from the message name and its fields' types and names, so a receiver generated from other XML computes another CRC and drops the frame. It cannot detect forgery: anyone can compute a CRC; only signing helps.","objective":"Encode and decode a MAVLink v2 HEARTBEAT in pure Go with encoding/binary, compute the CRC-16/MCRF4XX checksum seeded with CRC_EXTRA, and watch corruption and mismatched definitions get rejected.","question":"Intact frames of one message type fail the CRC at a receiver while every other message passes. What does the CRC_EXTRA seed reveal here?","references":["https://mavlink.io/en/guide/serialization.html","https://mavlink.io/en/guide/message_signing.html","https://mavlink.io/en/messages/common.html","https://pkg.go.dev/encoding/binary"],"reviewAnswer":"Sender and receiver using different message definitions","reviewPrompt":"What does CRC_EXTRA detect?","sections":[{"body":"A MAVLink v2 frame starts with the magic byte 0xFD, then len (the payload length after truncation), incompat_flags (flags a receiver must understand or drop the frame; 0x01 means signed), compat_flags (flags it may ignore), seq (a per-sender counter that wraps at 255 and reveals lost frames), sysid (the system, such as vehicle 1 or a ground station, often 255), compid (the component: 1 is the autopilot, 190 the mission planner), and a 24-bit message id, little-endian. The payload follows, up to 255 bytes, then the checksum low byte first, then an optional 13-byte signature. A frame is 12 to 280 bytes. MAVLink 1 frames start with 0xFE and have an 8-bit message id; most stacks still accept them, but new code should send v2.","title":"The frame, byte by byte"},{"body":"The XML definition lists fields in a readable order, but on the wire they are sorted by type size, largest first, keeping the declared order among equal sizes; extension fields come last in declared order. That is why HEARTBEAT's uint32 custom_mode comes before type and autopilot although it is declared after them. Everything is little-endian. MAVLink 2 then removes trailing zero bytes from the payload (the first byte is always kept) and the receiver zero-extends to the full size. Truncation is byte-wise, not field-wise: the high zero bytes of a small int32 go too. A Go struct whose fields follow the wire order maps straight onto the payload with binary.Append and binary.Decode, which never insert padding.","title":"Payload: reordered, little-endian, truncated"},{"body":"The checksum is CRC-16/MCRF4XX, which MAVLink's documentation and code call X.25: the reflected polynomial 0x1021, an initial value of 0xFFFF and no final XOR. It covers every byte after the magic byte through the end of the payload, and then one more byte that is never sent: CRC_EXTRA, an 8-bit value the code generator derives from the message name and the types and names of its base fields. If the receiver was generated from a different definition (a renamed field, a changed type or array length), its CRC differs and the frame is dropped rather than misread. It also means a receiver cannot validate a message it has no definition for: a router that forwards such messages has to pass them on unchecked.","title":"CRC-16/MCRF4XX and CRC_EXTRA"},{"body":"The program checks the CRC function against the published check value, encodes the HEARTBEAT of an armed ArduPilot quadrotor in GUIDED mode (custom mode 4 in ArduCopter's numbering) as system 1, component 1, decodes it back, flips the armed bit to show the CRC rejecting it, recomputes the checksum with a wrong CRC_EXTRA, and encodes a hovering GLOBAL_POSITION_INT to show truncation.","code":"package main\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n)\n\n// MAVLink v2 frame layout:\n//\n//\t0xFD len incompat compat seq sysid compid msgid(3, LE) payload crc(2, LE) [signature(13)]\nconst (\n\tmagicV2    = 0xFD\n\theaderLen  = 10\n\tflagSigned = 0x01 // incompat flag: a 13-byte signature follows the CRC\n)\n\n// Message ids and their CRC_EXTRA seeds, generated from the XML definitions.\nconst (\n\tmsgHeartbeat         = 0\n\tmsgGlobalPositionInt = 33\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}\n\n// Heartbeat is HEARTBEAT (#0). Fields are in wire order: larger types first.\ntype Heartbeat struct {\n\tCustomMode     uint32\n\tType           uint8 // MAV_TYPE: 2 = quadrotor, 6 = GCS\n\tAutopilot      uint8 // MAV_AUTOPILOT: 3 = ArduPilot, 12 = PX4, 8 = invalid\n\tBaseMode       uint8 // MAV_MODE_FLAG bits: 0x80 = safety armed, 0x01 = custom mode\n\tSystemStatus   uint8 // MAV_STATE: 3 = standby, 4 = active\n\tMavlinkVersion uint8\n}\n\n// GlobalPositionInt is GLOBAL_POSITION_INT (#33), 28 bytes on the wire.\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32 // degE7\n\tAlt, RelativeAlt int32 // mm\n\tVx, Vy, Vz       int16 // cm/s, north, east, down\n\tHdg              uint16\n}\n\ntype Frame struct {\n\tSeq, SysID, CompID uint8\n\tMsgID              uint32\n\tPayload            []byte // as received: possibly truncated\n}\n\n// crcAccumulate adds one byte to a CRC-16/MCRF4XX checksum (MAVLink calls it X.25).\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\n// crc16 starts at 0xFFFF and has no final XOR.\nfunc crc16(data []byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crc\n}\n\n// frameCRC covers every byte after the magic byte, then the message's CRC_EXTRA.\nfunc frameCRC(data []byte, extra byte) uint16 {\n\treturn crcAccumulate(crc16(data), extra)\n}\n\n// Encode serializes a message into a MAVLink v2 frame.\nfunc Encode(seq, sysID, compID uint8, msgID uint32, msg any) ([]byte, error) {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1] // trailing zeros are not sent; the first byte always is\n\t}\n\tbuf := []byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}\n\tbuf = append(buf, payload...)\n\tcrc := frameCRC(buf[1:], crcExtra[msgID])\n\treturn binary.LittleEndian.AppendUint16(buf, crc), nil\n}\n\nvar errBadCRC = errors.New(\"bad CRC\")\n\n// Decode parses one frame from the start of buf and validates its checksum.\nfunc Decode(buf []byte) (Frame, error) {\n\tif len(buf) < headerLen+2 || buf[0] != magicV2 {\n\t\treturn Frame{}, errors.New(\"not a MAVLink v2 frame\")\n\t}\n\tn := int(buf[1])\n\tif buf[2]&^flagSigned != 0 {\n\t\treturn Frame{}, fmt.Errorf(\"unknown incompat flags %#x\", buf[2])\n\t}\n\tsize := headerLen + n + 2\n\tif buf[2]&flagSigned != 0 {\n\t\tsize += 13\n\t}\n\tif len(buf) < size {\n\t\treturn Frame{}, errors.New(\"short frame\")\n\t}\n\tf := Frame{Seq: buf[4], SysID: buf[5], CompID: buf[6],\n\t\tMsgID: uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16}\n\textra, ok := crcExtra[f.MsgID]\n\tif !ok {\n\t\treturn Frame{}, fmt.Errorf(\"message %d: no CRC_EXTRA, cannot validate\", f.MsgID)\n\t}\n\tgot := binary.LittleEndian.Uint16(buf[headerLen+n:])\n\tif want := frameCRC(buf[1:headerLen+n], extra); got != want {\n\t\treturn Frame{}, fmt.Errorf(\"%w: got %#04x, want %#04x\", errBadCRC, got, want)\n\t}\n\tf.Payload = buf[headerLen : headerLen+n]\n\treturn f, nil\n}\n\n// Unmarshal zero-extends a truncated payload and decodes it into msg.\nfunc Unmarshal(payload []byte, msg any) error {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\t_, err := binary.Decode(full, binary.LittleEndian, msg)\n\treturn err\n}\n\nfunc main() {\n\tfmt.Printf(\"CRC-16/MCRF4XX check value: %#04x\\n\", crc16([]byte(\"123456789\")))\n\n\thb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}\n\tframe, err := Encode(0, 1, 1, msgHeartbeat, hb)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"HEARTBEAT frame (%d bytes): % x\\n\", len(frame), frame)\n\n\tf, err := Decode(frame)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar got Heartbeat\n\tif err := Unmarshal(f.Payload, &got); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"decoded: seq %d sys %d comp %d msg %d %+v\\n\", f.Seq, f.SysID, f.CompID, f.MsgID, got)\n\n\t// One bit flips in transit: base_mode 0x81 (armed) becomes 0x01 (disarmed).\n\tbad := append([]byte(nil), frame...)\n\tbad[headerLen+6] ^= 0x80\n\t_, err = Decode(bad)\n\tfmt.Println(\"flipped bit:\", err, \"| rejected:\", errors.Is(err, errBadCRC))\n\n\t// A receiver generated from a different HEARTBEAT definition has another\n\t// CRC_EXTRA, so the same intact bytes fail its check.\n\tsent := binary.LittleEndian.Uint16(frame[len(frame)-2:])\n\tfmt.Printf(\"receiver with CRC_EXTRA 51 computes %#04x, frame carries %#04x\\n\",\n\t\tframeCRC(frame[1:len(frame)-2], 51), sent)\n\n\t// Hovering, heading north: the last 8 bytes (vx, vy, vz, hdg) are zero.\n\tpos := GlobalPositionInt{TimeBootMs: 125000, Lat: 473977419, Lon: 85455938, Alt: 498300, RelativeAlt: 10000}\n\tframe, err = Encode(1, 1, 1, msgGlobalPositionInt, pos)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tf, err = Decode(frame)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar back GlobalPositionInt\n\tif err := Unmarshal(f.Payload, &back); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"GLOBAL_POSITION_INT: payload %d bytes, sent %d, frame %d bytes, round trip equal: %t\\n\",\n\t\tbinary.Size(pos), len(f.Payload), len(frame), back == pos)\n}","language":"go","title":"Encode, decode and corrupt a HEARTBEAT","walkthrough":"0x6f91 is the catalogued check value of CRC-16/MCRF4XX for \"123456789\". The frame is 21 bytes: fd, len 09, two zero flag bytes, seq 00, sysid 01, compid 01, msgid 00 00 00, the payload with custom_mode 04 00 00 00 first, then type 02, autopilot 03, base_mode 81, system_status 04 and version 03, and the CRC 0x5603 sent as 03 56. Flipping the armed bit makes the receiver compute 0x7b6d instead, so the frame is dropped rather than reported as disarmed. A receiver with CRC_EXTRA 51 computes 0x478a and rejects even the intact frame. The hovering GLOBAL_POSITION_INT sends 18 of its 28 payload bytes: the zero velocities and heading and the two zero high bytes of relative_alt (10000 mm) are trimmed, and zero-extension restores an identical struct."},{"body":"A CRC detects accidental corruption, not tampering: anyone can compute a valid checksum. MAVLink 2 signing sets incompat flag 0x01 and appends 13 bytes: a link id, a 48-bit timestamp in 10-microsecond units since 1 January 2015 that must increase on each link, and a 48-bit signature, the first six bytes of SHA-256 over a 32-byte secret key followed by the header, payload, CRC, link id and timestamp. Receivers reject bad signatures and stale timestamps, which blocks forged and replayed commands. The key is shared out of band, typically over a wired connection, and signing does not encrypt: telemetry remains readable to anyone listening on the link.","title":"What the CRC does not protect"},{"body":"This program uses only the standard library. In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay), and tap Run; there is no replay because it never calls sim.Save. To feed it simulator data, fly a drone in a sim.Run loop and, each time d.Telemetry().Time changes, build a GLOBAL_POSITION_INT from the report (latitude and longitude from the position as in the coordinates lesson, velocity in cm/s north, east and down) and encode one frame per report.","title":"Fly it in GopherForge"}],"takeaway":"A MAVLink v2 frame is a 10-byte header, a payload of size-ordered little-endian fields with trailing zeros removed, and a CRC-16/MCRF4XX that ends with the message's CRC_EXTRA. Corrupted bytes and mismatched definitions both fail the CRC; only signing protects against forgery.","title":"MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing","unitID":"drones-foundations","wrongAnswers":["A forged frame from an attacker on the link","A payload whose trailing zeros were truncated"]},{"conceptTag":"drones.telemetry-streams","designGuide":{"cautions":["A heartbeat-only monitor misses a stalled data stream.","Vehicle timestamps reset on reboot and drift from yours."],"cost":"A small record per message type (count, last receipt, expected interval) and a periodic check that turns ages into alarms.","family":"drones","flow":["Stamp frames on receipt","Rate and gap per message","Timeout per stream","Heartbeat for link loss"],"ratings":[],"strengths":["Stale data is flagged even while heartbeats still arrive.","Receipt timestamps expose radio buffering and bursts."]},"hint":"time_boot_ms starts when the vehicle boots. How is it related to your clock, and what does it say about radio buffering?","id":"drones.telemetry-streams","introduction":"A vehicle does not answer questions about its position; it streams messages at configured rates and the ground station keeps the latest value of each. That design is efficient on a narrow radio link, but it means the newest value you hold may be seconds old. A ground station that shows a position without knowing its age, or calls a link healthy because heartbeats still arrive, is behind many confusing incidents.","nuance":"time_boot_ms says when the estimate was made, on another clock that restarts at reboot and drifts. Ages, rates and gaps belong on your monotonic clock at receipt; keep time_boot_ms for ordering and reboot detection.","objective":"Decode a recorded MAVLink stream, measure per-message rates and gaps on the ground station's clock, interpret GLOBAL_POSITION_INT's scaled integers, and flag stale streams and a lost link.","question":"A ground station shows how old the vehicle position is. Which clock should it use to measure that age?","references":["https://mavlink.io/en/messages/common.html","https://mavlink.io/en/mavgen_python/howto_requestmessages.html","https://mavlink.io/en/guide/packet_loss.html","https://ardupilot.org/dev/docs/mavlink-requesting-data.html"],"reviewAnswer":"The ground station's own clock, stamped on receipt","reviewPrompt":"Which clock measures staleness?","sections":[{"body":"An autopilot streams a default set of messages on each link. To change a rate, send MAV_CMD_SET_MESSAGE_INTERVAL in a COMMAND_LONG with param1 the message id and param2 the interval in microseconds (-1 disables the stream, 0 restores the default) and wait for its COMMAND_ACK. To ask for the current rate, send MAV_CMD_REQUEST_MESSAGE with param1 244 and param2 the message id; the reply is MESSAGE_INTERVAL with message_id and interval_us, where -1 means disabled and 0 not available. ArduPilot also has per-port stream-rate parameters such as SR1_POSITION, and PX4 sets default rate profiles per MAVLink instance. Rates compete for bandwidth: a 57600-baud telemetry radio moves only a few kilobytes per second, so ask for what each consumer needs, not everything at 50 Hz.","title":"Streams and their rates"},{"body":"GLOBAL_POSITION_INT (#33) is the flight controller's fused position estimate, not raw GPS (GPS_RAW_INT carries the receiver's own solution). time_boot_ms is the vehicle's clock since boot; lat and lon are int32 in degE7, 1e-7 degree or about 1.1 cm; alt is millimetres above mean sea level and relative_alt millimetres above home; vx, vy and vz are int16 centimetres per second north, east and down, so a climb is a negative vz; hdg is centidegrees from 0 to 35999, with 65535 meaning unknown. Scaled integers keep full resolution in few bytes, and they are where bugs hide: millimetres treated as metres, vz read as climb, or lat and lon swapped.","title":"GLOBAL_POSITION_INT, field by field"},{"body":"time_boot_ms says when the vehicle made the estimate, on a clock that starts at boot, restarts after a reboot and drifts against yours. It cannot tell you how old the value is now, because radios buffer, retry and deliver in bursts. Stamp every frame with your own monotonic clock when it is complete (in Go, time.Now carries a monotonic reading and time.Since uses it) and compute ages, rates and gaps from those stamps. Keep time_boot_ms for ordering samples and for spotting a reboot, when it jumps backwards. The seq byte, counted per sender, shows frames lost on the link.","title":"Timestamp on receipt"},{"body":"vehicleLink builds what a radio delivers over 8.45 s: a MESSAGE_INTERVAL reply confirming GLOBAL_POSITION_INT at 200000 microseconds, HEARTBEAT at 1 Hz, ATTITUDE at 10 Hz and GLOBAL_POSITION_INT at 5 Hz, with three noise bytes, a radio that holds 0.6 s of frames and delivers them in a burst, one corrupted ATTITUDE frame, a position stream that stops at 6 s and silence after 8.45 s. The parser resynchronises on 0xFD, each stream records its count, receipt times and largest gaps, and five checks compare ages with per-stream timeouts: three expected intervals for data, five seconds of missing heartbeats for the link.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"time\"\n)\n\nconst (\n\tmagicV2   = 0xFD\n\theaderLen = 10\n\n\tmsgHeartbeat         = 0\n\tmsgAttitude          = 30\n\tmsgGlobalPositionInt = 33\n\tmsgMessageInterval   = 244\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgAttitude: 39, msgGlobalPositionInt: 104, msgMessageInterval: 95}\n\ntype Heartbeat struct {\n\tCustomMode                                              uint32\n\tType, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8\n}\n\ntype Attitude struct {\n\tTimeBootMs                                        uint32\n\tRoll, Pitch, Yaw, RollSpeed, PitchSpeed, YawSpeed float32\n}\n\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32  // degE7\n\tAlt, RelativeAlt int32  // mm (MSL, above home)\n\tVx, Vy, Vz       int16  // cm/s north, east, down\n\tHdg              uint16 // cdeg, 65535 = unknown\n}\n\ntype MessageInterval struct {\n\tIntervalUs int32 // wire order: the int32 comes before the uint16\n\tMessageID  uint16\n}\n\ntype Frame struct {\n\tSeq     uint8\n\tMsgID   uint32\n\tPayload []byte\n\tRx      time.Duration // ground-station clock when the frame was complete\n}\n\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\nfunc frameCRC(data []byte, extra byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crcAccumulate(crc, extra)\n}\n\nfunc encode(seq uint8, msgID uint32, msg any) []byte {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1]\n\t}\n\tbuf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, 1, 1,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}, payload...)\n\treturn binary.LittleEndian.AppendUint16(buf, frameCRC(buf[1:], crcExtra[msgID]))\n}\n\nfunc unmarshal(payload []byte, msg any) {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\tif _, err := binary.Decode(full, binary.LittleEndian, msg); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n// Parser cuts a byte stream into valid frames and resynchronises on the next\n// 0xFD after junk or a frame that fails its CRC.\ntype Parser struct {\n\tbuf             []byte\n\tBadCRC, Skipped int\n}\n\nfunc (p *Parser) Feed(data []byte, rx time.Duration) []Frame {\n\tp.buf = append(p.buf, data...)\n\tvar out []Frame\n\tfor {\n\t\ti := bytes.IndexByte(p.buf, magicV2)\n\t\tif i < 0 {\n\t\t\ti = len(p.buf)\n\t\t}\n\t\tp.Skipped += i\n\t\tp.buf = p.buf[i:]\n\t\tif len(p.buf) < headerLen {\n\t\t\treturn out\n\t\t}\n\t\tn := int(p.buf[1])\n\t\tif len(p.buf) < headerLen+n+2 {\n\t\t\treturn out\n\t\t}\n\t\tid := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16\n\t\textra, known := crcExtra[id]\n\t\tgot := binary.LittleEndian.Uint16(p.buf[headerLen+n:])\n\t\tif !known || got != frameCRC(p.buf[1:headerLen+n], extra) {\n\t\t\tp.BadCRC++\n\t\t\tp.Skipped++\n\t\t\tp.buf = p.buf[1:] // not a frame after all: hunt for the next 0xFD\n\t\t\tcontinue\n\t\t}\n\t\tpayload := append([]byte(nil), p.buf[headerLen:headerLen+n]...)\n\t\tout = append(out, Frame{Seq: p.buf[4], MsgID: id, Payload: payload, Rx: rx})\n\t\tp.buf = p.buf[headerLen+n+2:]\n\t}\n}\n\n// Stream is what the ground station knows about one message type.\ntype Stream struct {\n\tName         string\n\tID           uint32\n\tTimeout      time.Duration\n\tCount        int\n\tFirst, Last  time.Duration\n\tMaxGap       time.Duration\n\tlastBoot     uint32\n\tMaxBootGap   time.Duration\n\thasBootStamp bool\n}\n\nfunc (s *Stream) Add(f Frame, boot uint32, hasBoot bool) {\n\tif s.Count == 0 {\n\t\ts.First = f.Rx\n\t} else {\n\t\ts.MaxGap = max(s.MaxGap, f.Rx-s.Last)\n\t\tif hasBoot {\n\t\t\ts.MaxBootGap = max(s.MaxBootGap, time.Duration(boot-s.lastBoot)*time.Millisecond)\n\t\t}\n\t}\n\ts.Count++\n\ts.Last, s.lastBoot, s.hasBootStamp = f.Rx, boot, hasBoot\n}\n\nfunc (s *Stream) Rate() float64 {\n\tif s.Count < 2 {\n\t\treturn 0\n\t}\n\treturn float64(s.Count-1) / (s.Last - s.First).Seconds()\n}\n\ntype chunk struct {\n\trx   time.Duration\n\tdata []byte\n}\n\n// vehicleLink builds what a radio delivers: HEARTBEAT at 1 Hz, ATTITUDE at\n// 10 Hz and GLOBAL_POSITION_INT at 5 Hz. The radio holds frames sent between\n// 3.0 and 3.6 s and delivers them at 3.65 s; GLOBAL_POSITION_INT stops at\n// 6 s; one ATTITUDE frame is corrupted; the link dies after 8.45 s.\nfunc vehicleLink() []chunk {\n\tconst bootAtStart = 125000 // the vehicle booted 125 s before we started listening\n\tvar out []chunk\n\tvar seq uint8\n\trx := time.Duration(0)\n\tsend := func(sent int, data []byte) {\n\t\tseq++\n\t\tarrive := time.Duration(sent+8+sent%7) * time.Millisecond // a few ms of latency\n\t\tif sent >= 3000 && sent < 3600 {\n\t\t\tarrive = 3650 * time.Millisecond\n\t\t}\n\t\trx = max(rx, arrive) // a serial link is first in, first out\n\t\tout = append(out, chunk{rx, data})\n\t}\n\tout = append(out, chunk{0, []byte{0x55, 0x00, 0xAA}}) // noise before the first frame\n\tsend(0, encode(seq, msgMessageInterval, MessageInterval{IntervalUs: 200000, MessageID: msgGlobalPositionInt}))\n\tlon := int32(85455938)\n\tfor ms := 0; ms <= 8450; ms += 50 {\n\t\tboot := uint32(bootAtStart + ms)\n\t\tif ms%1000 == 0 {\n\t\t\tsend(ms, encode(seq, msgHeartbeat, Heartbeat{CustomMode: 3, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}))\n\t\t}\n\t\tif ms%100 == 0 {\n\t\t\tf := encode(seq, msgAttitude, Attitude{TimeBootMs: boot, Yaw: math.Pi / 2})\n\t\t\tif ms == 5000 {\n\t\t\t\tf[12] ^= 0x10 // a bit error the radio's own checks missed\n\t\t\t}\n\t\t\tsend(ms, f)\n\t\t}\n\t\tif ms%200 == 0 && ms < 6000 {\n\t\t\tlon += 106 // 4 m/s east is about 106e-7 degrees of longitude per 0.2 s here\n\t\t\tsend(ms, encode(seq, msgGlobalPositionInt, GlobalPositionInt{TimeBootMs: boot, Lat: 473977419,\n\t\t\t\tLon: lon, Alt: 508300, RelativeAlt: 20150, Vy: 400, Hdg: 9000}))\n\t\t}\n\t}\n\treturn out\n}\n\nfunc main() {\n\tstreams := []*Stream{\n\t\t{Name: \"HEARTBEAT\", ID: msgHeartbeat, Timeout: 5 * time.Second}, // five missed heartbeats\n\t\t{Name: \"ATTITUDE\", ID: msgAttitude, Timeout: 300 * time.Millisecond},\n\t\t{Name: \"GLOBAL_POSITION_INT\", ID: msgGlobalPositionInt},\n\t}\n\tbyID := map[uint32]*Stream{}\n\tfor _, s := range streams {\n\t\tbyID[s.ID] = s\n\t}\n\tvar p Parser\n\tvar lastPos GlobalPositionInt\n\tvar nextSeq uint8\n\tframes, lost := 0, 0\n\n\tcheck := func(at time.Duration) {\n\t\thb := streams[0]\n\t\tstate := \"link up  \"\n\t\tif hb.Count == 0 || at-hb.Last > hb.Timeout {\n\t\t\tstate = \"LINK LOST\"\n\t\t}\n\t\tline := fmt.Sprintf(\"t=%5.1fs  HEARTBEAT %.2fs %s\", at.Seconds(), (at - hb.Last).Seconds(), state)\n\t\tfor _, s := range streams[1:] {\n\t\t\tage := at - s.Last\n\t\t\tmark := \"ok\"\n\t\t\tif age > s.Timeout {\n\t\t\t\tmark = \"STALE\"\n\t\t\t}\n\t\t\tline += fmt.Sprintf(\"  %s %.2fs %s\", s.Name, age.Seconds(), mark)\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\tchecks := []time.Duration{2 * time.Second, 3500 * time.Millisecond, 7 * time.Second, 11 * time.Second, 14 * time.Second}\n\n\tfor _, c := range vehicleLink() {\n\t\tfor len(checks) > 0 && checks[0] < c.rx {\n\t\t\tcheck(checks[0])\n\t\t\tchecks = checks[1:]\n\t\t}\n\t\tfor _, f := range p.Feed(c.data, c.rx) {\n\t\t\tif frames > 0 {\n\t\t\t\tlost += int(f.Seq - nextSeq) // uint8 arithmetic wraps at 256\n\t\t\t}\n\t\t\tframes, nextSeq = frames+1, f.Seq+1\n\t\t\tswitch f.MsgID {\n\t\t\tcase msgMessageInterval:\n\t\t\t\tvar mi MessageInterval\n\t\t\t\tunmarshal(f.Payload, &mi)\n\t\t\t\tfmt.Printf(\"MESSAGE_INTERVAL: message %d every %d us (%.1f Hz)\\n\", mi.MessageID, mi.IntervalUs, 1e6/float64(mi.IntervalUs))\n\t\t\t\tif s := byID[uint32(mi.MessageID)]; s != nil && mi.IntervalUs > 0 {\n\t\t\t\t\ts.Timeout = 3 * time.Duration(mi.IntervalUs) * time.Microsecond\n\t\t\t\t}\n\t\t\tcase msgHeartbeat:\n\t\t\t\tbyID[f.MsgID].Add(f, 0, false)\n\t\t\tcase msgAttitude:\n\t\t\t\tvar a Attitude\n\t\t\t\tunmarshal(f.Payload, &a)\n\t\t\t\tbyID[f.MsgID].Add(f, a.TimeBootMs, true)\n\t\t\tcase msgGlobalPositionInt:\n\t\t\t\tunmarshal(f.Payload, &lastPos)\n\t\t\t\tbyID[f.MsgID].Add(f, lastPos.TimeBootMs, true)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, at := range checks {\n\t\tcheck(at)\n\t}\n\n\tfmt.Printf(\"frames %d, failed CRC %d, bytes skipped %d, lost by sequence %d\\n\", frames, p.BadCRC, p.Skipped, lost)\n\tfmt.Println(\"message              count  rx rate  max gap (rx)  max gap (vehicle clock)\")\n\tfor _, s := range streams {\n\t\tvehicle := \"-\"\n\t\tif s.hasBootStamp {\n\t\t\tvehicle = s.MaxBootGap.String()\n\t\t}\n\t\tfmt.Printf(\"%-19s  %5d  %4.1f Hz  %12s  %s\\n\", s.Name, s.Count, s.Rate(), s.MaxGap, vehicle)\n\t}\n\tg := lastPos\n\tfmt.Printf(\"last position: %.7f, %.7f  alt %.2f m MSL, %.2f m above home\\n\",\n\t\tfloat64(g.Lat)/1e7, float64(g.Lon)/1e7, float64(g.Alt)/1000, float64(g.RelativeAlt)/1000)\n\tfmt.Printf(\"velocity: north %.2f, east %.2f, climb %.2f m/s, heading %.2f deg\\n\",\n\t\tfloat64(g.Vx)/100, float64(g.Vy)/100, float64(-g.Vz)/100, float64(g.Hdg)/100)\n}","language":"go","title":"Rates, gaps and staleness from a recorded stream","walkthrough":"At 2.0 s everything is fresh. At 3.5 s, inside the radio hold, the heartbeat is 1.49 s old and the link is up, yet ATTITUDE (0.59s) and GLOBAL_POSITION_INT (0.69s) are STALE. At 7.0 s only GLOBAL_POSITION_INT is stale (1.19s) while heartbeats arrive: the case a heartbeat-only monitor misses. At 11.0 s the link has been dead for 2.5 s but the heartbeat is 2.99 s old, so it still says link up; at 14.0 s it reaches 5.99s and reports LINK LOST. The summary shows 124 frames, 1 failed CRC, 31 skipped bytes (3 noise bytes and the 28-byte corrupted frame) and 1 frame lost by sequence. Receipt gaps of 740ms and 842ms reveal the burst that the vehicle clock (200ms) hides. The last position decodes to 47.3977419, 8.5459118 at 20.15 m above home, 4.00 m/s east on heading 90.00 deg."},{"body":"Give every consumer a maximum age it tolerates: a map can show a 2 s old position with a warning, a geofence monitor may need data younger than half a second, and a command that depends on the vehicle's mode should check that the mode is fresh. Show the age next to each value and grey out stale ones. Declare link loss from missed heartbeats (on radio links the MAVLink documentation describes 1 Hz heartbeats and four or five missed before disconnecting), but alarm on stale data first, because a heartbeat comes from a different code path than the estimator and can keep arriving while position does not. When a link returns, the first frames may be old ones from a buffer: check that time_boot_ms moves forward before trusting them.","title":"Decide per stream, not per link"},{"body":"The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To feed it simulator data, fly in a sim.Run loop and, each time d.Telemetry().Time changes, encode a GLOBAL_POSITION_INT from the report (GPS position converted to degE7 around a home point, BaroAlt in millimetres as relative_alt, velocity in cm/s north, east and down) and pass the frame to Parser.Feed with the simulated time as the receipt time. Stop encoding for a few seconds and watch the checks turn STALE; add sim.Save for a replay.","title":"Fly it in GopherForge"}],"takeaway":"Treat every telemetry value as a sample with an age. Stamp frames on receipt with your own clock, measure rates and gaps per message, keep time_boot_ms for ordering and reboot detection, and alarm on stale data streams before the heartbeat timeout declares the link lost.","title":"Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection","unitID":"drones-foundations","wrongAnswers":["time_boot_ms in the message, since the vehicle stamps it","The heartbeat timer, since heartbeats prove the link is up"]},{"conceptTag":"drones.coordinates","designGuide":{"cautions":["Flat-plane error grows with distance and latitude.","Axis swaps and sign flips between ENU and NED fail silently."],"cost":"A reference point per mission and two small conversion functions, tested at high latitude and across the antimeridian.","family":"drones","flow":["Keep WGS84 on the wire","Pick a reference point","Wrap dlon, scale by cos","Re-base for long legs"],"ratings":[],"strengths":["A local plane turns geometry into plain vector maths.","degE7 integers keep centimetre resolution on the wire."]},"hint":"ENU is x east, y north, z up; NED is x north, y east, z down. Swap the horizontal axes and flip one sign.","id":"drones.coordinates","introduction":"GPS reports latitude, longitude and altitude on the WGS84 ellipsoid; controllers work in metres in a local frame; MAVLink and the flight stacks use NED while ROS and this simulator use ENU. Every drone codebase converts between them, and a swapped axis, a wrong sign or a missing cos(latitude) produces a vehicle that flies confidently to the wrong place. The conversions are short; knowing their error budget is the real skill.","nuance":"Swapping x and y and negating z keeps both frames right-handed. Headings change too: NED heading runs clockwise from north and ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw.","objective":"Convert mission waypoints between WGS84 latitude and longitude and local metres, compute great-circle distance and bearing, and know where the flat-plane approximation and spherical formulas stop being good enough.","question":"The simulator reports a position in ENU as (x, y, z). How do you express it in NED for a MAVLink LOCAL_POSITION_NED message?","references":["https://en.wikipedia.org/wiki/World_Geodetic_System","https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates","https://en.wikipedia.org/wiki/Haversine_formula","https://en.wikipedia.org/wiki/Equirectangular_projection"],"reviewAnswer":"North = y, east = x, down = -z","reviewPrompt":"ENU (x, y, z) to NED?","sections":[{"body":"WGS84 defines the reference ellipsoid (semi-major axis 6378137 m, flattening 1/298.257223563) and the frame GPS positions are expressed in. Heights come in two kinds: GNSS receivers measure height above the ellipsoid, while GLOBAL_POSITION_INT's alt is above mean sea level (the geoid), and the two differ by up to about 100 m depending on where you are. Local frames are tangent to the Earth at a reference point. ENU has x east, y north and z up; ROS and this simulator use it. NED has x north, y east and z down; aviation, PX4, ArduPilot and MAVLink messages such as LOCAL_POSITION_NED use it. Converting is north = y, east = x, down = -z, and headings change too: NED heading runs clockwise from north, ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw.","title":"WGS84, ENU and NED"},{"body":"The haversine formula gives the great-circle distance on a sphere and stays accurate for short distances, where the spherical law of cosines loses precision. With the mean Earth radius of 6371008.8 m its error against the WGS84 ellipsoid is a few tenths of a percent at most, and the program shows why: at 47.4 degrees north the sphere's metre per degree is 0.015% long north-south and 0.293% short east-west. The initial bearing is the direction to set off in; along a great circle it changes except on meridians and the equator. For survey-grade work use an ellipsoidal geodesic (Karney's algorithm, as in GeographicLib) or convert through Earth-centred coordinates (ECEF) to ENU.","title":"Haversine distance and initial bearing"},{"body":"Plane is a local tangent plane at home with the equirectangular approximation: x = R * dlon * cos(lat0) and y = R * dlat, with the longitude difference wrapped into [-180, 180). The program compares metres per degree on the sphere and on WGS84, converts four survey waypoints into simulator ENU and NED vectors and checks them against haversine, sends a simulator position through degE7 integers and back, compares degE7 with float32 degrees, measures how the flat-plane error grows with distance at two latitudes, and crosses the antimeridian.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// earthRadius is the mean Earth radius in metres. Spherical formulas with it\n// are within a few tenths of a percent of the WGS84 ellipsoid.\nconst earthRadius = 6371008.8\n\n// WGS84 ellipsoid: semi-major axis and flattening.\nconst (\n\twgs84A = 6378137.0\n\twgs84F = 1 / 298.257223563\n)\n\ntype LatLon struct{ Lat, Lon float64 } // degrees, WGS84\n\nfunc rad(d float64) float64 { return d * math.Pi / 180 }\nfunc deg(r float64) float64 { return r * 180 / math.Pi }\n\n// wrap180 brings a longitude difference into [-180, 180).\nfunc wrap180(d float64) float64 { return math.Mod(math.Mod(d+180, 360)+360, 360) - 180 }\n\n// Distance is the haversine great-circle distance in metres.\nfunc Distance(a, b LatLon) float64 {\n\tp1, p2 := rad(a.Lat), rad(b.Lat)\n\tdp, dl := p2-p1, rad(b.Lon-a.Lon)\n\th := math.Sin(dp/2)*math.Sin(dp/2) + math.Cos(p1)*math.Cos(p2)*math.Sin(dl/2)*math.Sin(dl/2)\n\treturn 2 * earthRadius * math.Asin(math.Sqrt(h))\n}\n\n// Bearing is the initial great-circle bearing, degrees clockwise from north.\nfunc Bearing(a, b LatLon) float64 {\n\tp1, p2, dl := rad(a.Lat), rad(b.Lat), rad(b.Lon-a.Lon)\n\ty := math.Sin(dl) * math.Cos(p2)\n\tx := math.Cos(p1)*math.Sin(p2) - math.Sin(p1)*math.Cos(p2)*math.Cos(dl)\n\treturn math.Mod(deg(math.Atan2(y, x))+360, 360)\n}\n\n// Destination walks dist metres from a along an initial bearing on the sphere.\nfunc Destination(a LatLon, bearing, dist float64) LatLon {\n\tp1, l1, th, d := rad(a.Lat), rad(a.Lon), rad(bearing), dist/earthRadius\n\tp2 := math.Asin(math.Sin(p1)*math.Cos(d) + math.Cos(p1)*math.Sin(d)*math.Cos(th))\n\tl2 := l1 + math.Atan2(math.Sin(th)*math.Sin(d)*math.Cos(p1), math.Cos(d)-math.Sin(p1)*math.Sin(p2))\n\treturn LatLon{deg(p2), wrap180(deg(l2))}\n}\n\n// Plane is a local tangent plane at Ref with the equirectangular\n// approximation: X east and Y north in metres, like the simulator's ENU.\ntype Plane struct{ Ref LatLon }\n\nfunc (pl Plane) ToLocal(p LatLon) (x, y float64) {\n\tx = earthRadius * rad(wrap180(p.Lon-pl.Ref.Lon)) * math.Cos(rad(pl.Ref.Lat))\n\ty = earthRadius * rad(p.Lat-pl.Ref.Lat)\n\treturn x, y\n}\n\nfunc (pl Plane) ToLatLon(x, y float64) LatLon {\n\tlat := pl.Ref.Lat + deg(y/earthRadius)\n\tlon := pl.Ref.Lon + deg(x/(earthRadius*math.Cos(rad(pl.Ref.Lat))))\n\treturn LatLon{lat, wrap180(lon)}\n}\n\nfunc main() {\n\thome := LatLon{47.397742, 8.545594}\n\tplane := Plane{Ref: home}\n\n\t// Metres per degree at home: sphere against the WGS84 ellipsoid.\n\te2 := wgs84F * (2 - wgs84F)\n\ts2 := math.Pow(math.Sin(rad(home.Lat)), 2)\n\tm := wgs84A * (1 - e2) / math.Pow(1-e2*s2, 1.5) // meridian radius of curvature\n\tn := wgs84A / math.Sqrt(1-e2*s2)                // prime vertical radius\n\tnorthS, northE := rad(earthRadius), rad(m)\n\teastS, eastE := rad(earthRadius)*math.Cos(rad(home.Lat)), rad(n)*math.Cos(rad(home.Lat))\n\tfmt.Printf(\"1 deg north: sphere %.1f m, WGS84 %.1f m (%+.3f%%)\\n\", northS, northE, (northS-northE)/northE*100)\n\tfmt.Printf(\"1 deg east:  sphere %.1f m, WGS84 %.1f m (%+.3f%%)\\n\", eastS, eastE, (eastS-eastE)/eastE*100)\n\n\tfmt.Println(\"mission waypoints, 15 m above home:\")\n\twps := []LatLon{{47.398200, 8.546300}, {47.398200, 8.547400}, {47.397300, 8.547400}, {47.397300, 8.546300}}\n\tfor i, wp := range wps {\n\t\tx, y := plane.ToLocal(wp)\n\t\tdist, brg := Distance(home, wp), Bearing(home, wp)\n\t\tflatDist := math.Hypot(x, y)\n\t\tflatBrg := math.Mod(deg(math.Atan2(x, y))+360, 360) // atan2(east, north): clockwise from north\n\t\tfmt.Printf(\"  wp%d ENU (%.2f, %.2f, 15)  NED (%.2f, %.2f, -15)  %.2f m at %.2f deg  flat %+.1f mm %+.4f deg\\n\",\n\t\t\ti+1, x, y, y, x, dist, brg, (flatDist-dist)*1000, flatBrg-brg)\n\t}\n\n\t// Back: a simulator position to GLOBAL_POSITION_INT integers and back.\n\tsimX, simY := 61.37, -40.21\n\tp := plane.ToLatLon(simX, simY)\n\tlatE7, lonE7 := int32(math.Round(p.Lat*1e7)), int32(math.Round(p.Lon*1e7))\n\tbx, by := plane.ToLocal(LatLon{float64(latE7) / 1e7, float64(lonE7) / 1e7})\n\tfmt.Printf(\"sim (%.2f, %.2f) -> lat %d lon %d (degE7) -> (%.4f, %.4f): error %.1f mm\\n\",\n\t\tsimX, simY, latE7, lonE7, bx, by, math.Hypot(bx-simX, by-simY)*1000)\n\tulp := func(v float64) float64 { f := float32(v); return float64(math.Nextafter32(f, 1e9) - f) }\n\tfmt.Printf(\"resolution here: degE7 %.2f cm north, %.2f cm east; float32 degrees %.2f cm north, %.2f cm east\\n\",\n\t\trad(1e-7)*earthRadius*100, rad(1e-7)*earthRadius*math.Cos(rad(p.Lat))*100,\n\t\trad(ulp(p.Lat))*earthRadius*100, rad(ulp(p.Lon))*earthRadius*math.Cos(rad(p.Lat))*100)\n\n\tfmt.Println(\"flat-plane range error against haversine, bearing 45 deg:\")\n\tfor _, site := range []struct {\n\t\tname string\n\t\tat   LatLon\n\t}{{\"lat 47.4\", home}, {\"lat 78.2\", LatLon{78.2, 15.6}}} {\n\t\tline := \"  \" + site.name + \":\"\n\t\tfor _, d := range []float64{100, 1000, 10000, 100000} {\n\t\t\tq := Destination(site.at, 45, d)\n\t\t\tx, y := Plane{Ref: site.at}.ToLocal(q)\n\t\t\tline += fmt.Sprintf(\"  %gkm %+.3f%%\", d/1000, (math.Hypot(x, y)-d)/d*100)\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\n\ta, b := LatLon{-16.5, 179.9995}, LatLon{-16.5, -179.9995}\n\traw := earthRadius * rad(b.Lon-a.Lon) * math.Cos(rad(a.Lat))\n\tx, _ := Plane{Ref: a}.ToLocal(b)\n\tfmt.Printf(\"across the antimeridian: east %.1f km without wrapping, %.1f m wrapped; haversine %.1f m\\n\",\n\t\traw/1000, x, Distance(a, b))\n}","language":"go","title":"Waypoints to local metres and back","walkthrough":"The first two lines put the sphere at +0.015% north-south and -0.293% east-west against WGS84, so on wp2's 136 m eastward offset the spherical model is about 0.4 m short: at field scale that, not the flat plane, is the larger error. wp2 becomes ENU (135.93, 50.93, 15) and NED (50.93, 135.93, -15), and every flat range and bearing differs from haversine by under a millimetre and 0.001 degree. The simulator position (61.37, -40.21) survives degE7 with a 4.0 mm error; degE7 resolves 1.11 cm north and 0.75 cm east, float32 degrees only 42.42 cm and 7.18 cm. The flat plane is 0.003% off at 1 km and 0.308% at 100 km at latitude 47.4, but already 0.134% at 10 km at latitude 78.2. Without wrapping, two points 106.6 m apart across the antimeridian appear 38381.7 km apart."},{"body":"The equirectangular plane uses cos(lat0) for every point, so its error grows with distance from the reference and faster at high latitude, where the cosine changes quickly; it is undefined at the poles. It also ignores curvature in height: 10 km away the ground lies about 7.8 m below the tangent plane. For a field, a farm or a city block it is excellent; for long routes, re-base the plane per leg or use an exact ECEF-to-ENU rotation. Flight stacks do the same thing at mission scale: ArduPilot scales longitude differences by the cosine of the two points' mean latitude, and PX4 projects around a reference point with an azimuthal equidistant projection. Send waypoints to the autopilot as latitude and longitude (MISSION_ITEM_INT carries them as degE7) and let it project them; use local metres only inside your own planning and display code.","title":"Where the flat plane breaks"},{"body":"The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To fly the mission, copy the four ENU vectors into a GoTo loop like the one the template's main.go runs over Square (keep mission.go), call sim.Save at the end and open Output for the replay; inside the loop, convert d.State().Pos back with ToLatLon to print latitude and longitude as the drone flies.","title":"Fly it in GopherForge"}],"takeaway":"Keep WGS84 latitude and longitude (as degE7 integers) on the wire and in missions, and use a local ENU or NED plane in metres for control, with the longitude difference wrapped and scaled by cos(latitude). The flat plane is excellent for a field and wrong for a country.","title":"Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes","unitID":"drones-foundations","wrongAnswers":["North = x, east = y, down = z","North = y, east = -x, down = z"]},{"conceptTag":"drones.ground-station","designGuide":{"cautions":["Read ignores contexts; only Close or a deadline unblocks it.","A heartbeat that outlives the station misleads the vehicle."],"cost":"Two goroutines and a WaitGroup per link, plus a timeout chosen for the radio you actually fly.","family":"drones","flow":["Reader goroutine decodes","Heartbeat tied to ctx","Select frames and timer","Cancel, close, wait"],"ratings":[],"strengths":["One owner per piece of state needs no locks.","A resettable timer turns silence into a typed error."]},"hint":"Read is a blocking call on the connection itself. Does it know about any context.Context?","id":"drones.ground-station","introduction":"A ground station is a small concurrent system: bytes arrive whenever the radio delivers them, heartbeats must go out on time whether or not anything arrives, operator commands interleave with both, and the link can vanish at any moment. Goroutines, channels, select and context map onto that shape directly. The hard parts are deciding who owns what and making sure every goroutine stops when the link or the program ends.","nuance":"net.Conn.Read never looks at a context. Close the connection, or set a read deadline in the past, and it returns an error. Cancel first so the other goroutines stop, then close, then wait.","objective":"Structure a MAVLink ground station with a reader goroutine, a periodic heartbeat, a channel of decoded frames, a select loop with a resettable link-loss timer and a context that shuts everything down cleanly.","question":"A ground station cancels its context on shutdown, but the reader goroutine never exits: it is blocked in conn.Read. What makes Read return?","references":["https://github.com/bluenviron/gomavlib","https://pkg.go.dev/github.com/bluenviron/gomavlib/v4","https://mavlink.io/en/services/heartbeat.html","https://pkg.go.dev/net#Pipe"],"reviewAnswer":"Closing the connection or setting a read deadline","reviewPrompt":"What unblocks a stuck conn.Read?","sections":[{"body":"The reader goroutine owns conn.Read and the parser, and sends decoded frames on a small buffered channel. The heartbeat goroutine owns periodic writes and the sequence counter. Run's loop owns the state (latest values, the log) and is the only goroutine that touches it, so no mutex is needed. net.Conn allows concurrent calls, but keep a single writer per link anyway, so sequence numbers stay ordered and frames never interleave on transports that split large writes; operator commands would go through that writer too. The reader reports its final error on a channel with a buffer of one, so it can always exit even if nobody is listening any more.","title":"One owner per job"},{"body":"On radio links components usually send HEARTBEAT at 1 Hz and treat four or five missing ones as a disconnection. A ground station identifies itself with type MAV_TYPE_GCS (6), autopilot MAV_AUTOPILOT_INVALID (8) and usually system id 255; the vehicle uses those heartbeats for its own ground-station failsafe (FS_GCS_ENABLE in ArduPilot, the data-link-loss action NAV_DLL_ACT in PX4). Link loss on the station side is a time.Timer reset on every valid frame; since Go 1.23, with a go.mod that says go 1.23 or later, Reset and Stop guarantee that no stale value is received afterwards, so the old drain-before-reset idiom is unnecessary. The MAVLink documentation also warns against sending heartbeats from a thread that does not know the state of the rest of the component: tie the heartbeat to the same context so it stops when the station stops.","title":"Heartbeats and link loss"},{"body":"main connects the GroundStation to a simulated vehicle through net.Pipe, an in-memory, synchronous, full-duplex connection where each Write waits for the other side to read. The vehicle streams four HEARTBEAT and GLOBAL_POSITION_INT pairs 20 ms apart, then its radio goes quiet while its reader keeps draining heartbeats. The station sends a heartbeat every 100 ms and declares link loss after 500 ms without a valid frame, both scaled down from flight values so the program finishes in under a second. It prints only what the protocol orders: the station's log in stream order, the error Run returned and the first heartbeat the vehicle saw, never how many heartbeats were sent, which depends on scheduling.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tmagicV2              = 0xFD\n\theaderLen            = 10\n\tmsgHeartbeat         = 0\n\tmsgGlobalPositionInt = 33\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}\n\ntype Heartbeat struct {\n\tCustomMode                                              uint32\n\tType, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8\n}\n\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32\n\tAlt, RelativeAlt int32\n\tVx, Vy, Vz       int16\n\tHdg              uint16\n}\n\ntype Frame struct {\n\tSeq, SysID, CompID uint8\n\tMsgID              uint32\n\tPayload            []byte\n}\n\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\nfunc frameCRC(data []byte, extra byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crcAccumulate(crc, extra)\n}\n\nfunc Encode(seq, sysID, compID uint8, msgID uint32, msg any) []byte {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\tpanic(err) // only fixed-size structs are passed in\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1]\n\t}\n\tbuf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}, payload...)\n\treturn binary.LittleEndian.AppendUint16(buf, frameCRC(buf[1:], crcExtra[msgID]))\n}\n\nfunc Unmarshal(payload []byte, msg any) error {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\t_, err := binary.Decode(full, binary.LittleEndian, msg)\n\treturn err\n}\n\n// Parser cuts a byte stream into frames that pass their CRC (lesson 3).\ntype Parser struct{ buf []byte }\n\nfunc (p *Parser) Feed(data []byte) []Frame {\n\tp.buf = append(p.buf, data...)\n\tvar out []Frame\n\tfor {\n\t\ti := bytes.IndexByte(p.buf, magicV2)\n\t\tif i < 0 {\n\t\t\ti = len(p.buf)\n\t\t}\n\t\tp.buf = p.buf[i:]\n\t\tif len(p.buf) < headerLen || len(p.buf) < headerLen+int(p.buf[1])+2 {\n\t\t\treturn out\n\t\t}\n\t\tn := int(p.buf[1])\n\t\tid := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16\n\t\textra, known := crcExtra[id]\n\t\tif !known || binary.LittleEndian.Uint16(p.buf[headerLen+n:]) != frameCRC(p.buf[1:headerLen+n], extra) {\n\t\t\tp.buf = p.buf[1:]\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, Frame{Seq: p.buf[4], SysID: p.buf[5], CompID: p.buf[6], MsgID: id,\n\t\t\tPayload: append([]byte(nil), p.buf[headerLen:headerLen+n]...)})\n\t\tp.buf = p.buf[headerLen+n+2:]\n\t}\n}\n\nvar ErrLinkLost = errors.New(\"link lost\")\n\n// GroundStation owns one link. Run starts a reader and a heartbeat goroutine\n// and handles decoded frames in its own loop until the link or ctx ends.\ntype GroundStation struct {\n\tConn        net.Conn\n\tHeartbeat   time.Duration // 1 s on a real link\n\tLinkTimeout time.Duration // several missed heartbeats on a real link\n\tLog         []string      // written only by Run's goroutine\n\tseq         uint8\n}\n\nfunc (g *GroundStation) Run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tframes := make(chan Frame, 16)\n\treadErr := make(chan error, 1)\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo func() { defer wg.Done(); readErr <- g.readLoop(ctx, frames) }()\n\tgo func() { defer wg.Done(); g.heartbeatLoop(ctx) }()\n\tdefer func() {\n\t\tcancel()       // stops the heartbeat: never advertise a dead ground station\n\t\tg.Conn.Close() // unblocks a Read or Write in progress\n\t\twg.Wait()\n\t}()\n\n\ttimer := time.NewTimer(g.LinkTimeout)\n\tdefer timer.Stop()\n\tfor {\n\t\tselect {\n\t\tcase f := <-frames:\n\t\t\tg.handle(f)\n\t\t\ttimer.Reset(g.LinkTimeout)\n\t\tcase <-timer.C:\n\t\t\treturn fmt.Errorf(\"%w: no frame for %v\", ErrLinkLost, g.LinkTimeout)\n\t\tcase err := <-readErr:\n\t\t\treturn err\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) readLoop(ctx context.Context, out chan<- Frame) error {\n\tvar p Parser\n\tbuf := make([]byte, 512)\n\tfor {\n\t\tn, err := g.Conn.Read(buf)\n\t\tfor _, f := range p.Feed(buf[:n]) {\n\t\t\tselect {\n\t\t\tcase out <- f:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) heartbeatLoop(ctx context.Context) {\n\ttick := time.NewTicker(g.Heartbeat)\n\tdefer tick.Stop()\n\tfor {\n\t\t// MAV_TYPE_GCS (6), MAV_AUTOPILOT_INVALID (8), MAV_STATE_ACTIVE (4)\n\t\thb := Heartbeat{Type: 6, Autopilot: 8, SystemStatus: 4, MavlinkVersion: 3}\n\t\tif _, err := g.Conn.Write(Encode(g.seq, 255, 190, msgHeartbeat, hb)); err != nil {\n\t\t\treturn\n\t\t}\n\t\tg.seq++\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-tick.C:\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) handle(f Frame) {\n\tswitch f.MsgID {\n\tcase msgHeartbeat:\n\t\tvar hb Heartbeat\n\t\tif Unmarshal(f.Payload, &hb) == nil {\n\t\t\tg.Log = append(g.Log, fmt.Sprintf(\"seq %d  HEARTBEAT from %d/%d: type %d, autopilot %d, armed %t, custom mode %d\",\n\t\t\t\tf.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot, hb.BaseMode&0x80 != 0, hb.CustomMode))\n\t\t}\n\tcase msgGlobalPositionInt:\n\t\tvar p GlobalPositionInt\n\t\tif Unmarshal(f.Payload, &p) == nil {\n\t\t\tg.Log = append(g.Log, fmt.Sprintf(\"seq %d  GLOBAL_POSITION_INT: %.7f, %.7f, %.2f m above home\",\n\t\t\t\tf.Seq, float64(p.Lat)/1e7, float64(p.Lon)/1e7, float64(p.RelativeAlt)/1000))\n\t\t}\n\t}\n}\n\n// vehicle plays the autopilot at the other end of the link: it streams four\n// rounds of telemetry, then its radio goes quiet. Its reader keeps draining\n// the ground station's heartbeats until the link closes.\nfunc vehicle(conn net.Conn, wg *sync.WaitGroup, firstGCS *string) {\n\twg.Add(2)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar p Parser\n\t\tbuf := make([]byte, 512)\n\t\tfor {\n\t\t\tn, err := conn.Read(buf)\n\t\t\tfor _, f := range p.Feed(buf[:n]) {\n\t\t\t\tvar hb Heartbeat\n\t\t\t\tif *firstGCS == \"\" && f.MsgID == msgHeartbeat && Unmarshal(f.Payload, &hb) == nil {\n\t\t\t\t\t*firstGCS = fmt.Sprintf(\"seq %d HEARTBEAT from %d/%d, type %d, autopilot %d\", f.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar seq uint8\n\t\tfor i := range 4 {\n\t\t\thb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}\n\t\t\tpos := GlobalPositionInt{TimeBootMs: uint32(60000 + 20*i), Lat: 473977419, Lon: 85455938 + 27*int32(i),\n\t\t\t\tAlt: 498300, RelativeAlt: 10000 + 50*int32(i), Vy: 100, Hdg: 9000}\n\t\t\tfor _, frame := range [][]byte{Encode(seq, 1, 1, msgHeartbeat, hb), Encode(seq+1, 1, 1, msgGlobalPositionInt, pos)} {\n\t\t\t\tif _, err := conn.Write(frame); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tseq += 2\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\t\t}\n\t}()\n}\n\nfunc main() {\n\tgcsEnd, vehicleEnd := net.Pipe() // in memory, synchronous, like a socket pair\n\tvar vehicleWG sync.WaitGroup\n\tvar firstGCS string\n\tvehicle(vehicleEnd, &vehicleWG, &firstGCS)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tgcs := &GroundStation{Conn: gcsEnd, Heartbeat: 100 * time.Millisecond, LinkTimeout: 500 * time.Millisecond}\n\terr := gcs.Run(ctx)\n\tvehicleWG.Wait() // Run closed the link, so both vehicle goroutines have returned\n\n\tfor _, line := range gcs.Log {\n\t\tfmt.Println(\"gcs:\", line)\n\t}\n\tfmt.Println(\"gcs stopped:\", err, \"| link lost:\", errors.Is(err, ErrLinkLost))\n\tfmt.Println(\"vehicle saw:\", firstGCS)\n}","language":"go","title":"A ground station over net.Pipe","walkthrough":"The eight gcs lines arrive in sequence order 0 to 7: HEARTBEATs from 1/1 with type 2, autopilot 3, armed true and custom mode 4, interleaved with GLOBAL_POSITION_INT reports whose longitude moves from 8.5455938 to 8.5456019 and whose altitude rises from 10.00 to 10.15 m above home. Then the timer fires and Run returns \"link lost: no frame for 500ms\"; errors.Is finds the wrapped ErrLinkLost, so the caller can tell a lost link from a cancelled context. The vehicle saw \"seq 0 HEARTBEAT from 255/190, type 6, autopilot 8\", the station's first heartbeat, sent before any telemetry arrived. Run's deferred function cancels the context, closes the connection to unblock the reader and waits for both goroutines."},{"body":"Order matters. cancel() makes the heartbeat loop return at its next select and lets a reader blocked on the frames channel give up. Close on the connection is what unblocks a goroutine sitting in Read or Write, because neither looks at a context; on network sockets SetReadDeadline is the other way to wake a reader. Only then does wg.Wait() return. Cancelling without closing leaves the reader blocked in Read for ever, and closing without cancelling leaves the heartbeat loop waiting for its next tick to discover the closed link. Run the program under go run -race and in tests that start and stop many stations: a leaked goroutine per reconnect is a slow memory leak on a companion computer that stays up for months.","title":"Shutdown without leaks"},{"body":"In production, github.com/bluenviron/gomavlib (v4) supplies the codec, dialects generated from the official XML such as common and ardupilotmega, endpoints for serial ports, UDP (server, client, broadcast), TCP and custom transports, automatic heartbeats, signing and routing; the mavp2p router is built on it. A Node takes Endpoints, a Dialect, OutVersion and OutSystemID; Initialize starts it, and Events delivers frames, channel openings and parse errors on one channel. EndpointUDPServer on :14550 receives what most vehicles and simulators send to the conventional ground-station port.","code":"import (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/bluenviron/gomavlib/v4\"\n\t\"github.com/bluenviron/gomavlib/v4/pkg/dialects/common\"\n)\n\nfunc listen() {\n\tnode := &gomavlib.Node{\n\t\tEndpoints: []gomavlib.Endpoint{\n\t\t\t&gomavlib.EndpointUDPServer{Address: \":14550\"},\n\t\t},\n\t\tDialect:         common.Dialect,\n\t\tOutVersion:      gomavlib.V2,\n\t\tOutSystemID:     255,\n\t\tHeartbeatPeriod: time.Second, // the library default is 5 s\n\t}\n\tif err := node.Initialize(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer node.Close()\n\n\tfor evt := range node.Events() {\n\t\tfrm, ok := evt.(*gomavlib.EventFrame)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch msg := frm.Message().(type) {\n\t\tcase *common.MessageHeartbeat:\n\t\t\tlog.Printf(\"system %d: type %d, custom mode %d\", frm.SystemID(), msg.Type, msg.CustomMode)\n\t\tcase *common.MessageGlobalPositionInt:\n\t\t\tlog.Printf(\"%.7f, %.7f, %.2f m above home\",\n\t\t\t\tfloat64(msg.Lat)/1e7, float64(msg.Lon)/1e7, float64(msg.RelativeAlt)/1000)\n\t\t}\n\t}\n}","language":"go","title":"The same with gomavlib","walkthrough":"The node owns the sockets, the codec and its own heartbeat goroutine, and hands frames to one loop, which stays the single owner of state as in the program above. HeartbeatPeriod is set because gomavlib sends one every 5 s by default, slower than the 1 Hz most radio links expect. Staleness checks and a link-loss timer still belong around this loop: the library tells you what arrived, not what stopped arriving."},{"body":"The program uses only the standard library, and net.Pipe needs no network, so it runs in the app's sandbox: choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To put the simulator behind the link, replace the vehicle's four fixed rounds with a sim.Run loop that encodes a GLOBAL_POSITION_INT from d.Telemetry() each time its Time changes and writes it to vehicleEnd, then call sim.Save at the end so Output shows the flight the ground station watched.","title":"Fly it in GopherForge"}],"takeaway":"Give each job one goroutine and each piece of state one owner: a reader that decodes into a channel, a heartbeat tied to the same context, and a loop that selects on frames, a resettable link-loss timer and cancellation. Shut down by cancelling, closing the connection and waiting.","title":"A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts","unitID":"drones-foundations","wrongAnswers":["Cancelling the context passed to the reader goroutine","Draining the frames channel the reader sends on"]},{"conceptTag":"drones.telemetry-noise","designGuide":{"cautions":["Slowly wandering GPS error survives averaging and looks like bias.","Pairing a report with truth from another instant inflates the error."],"cost":"A recording loop that pairs each report with the true state, and three running sums per axis.","family":"drones","flow":["Pair report with truth","Error = measured - true","Bias, RMSE, max per axis","Fuse complementary sensors"],"ratings":[],"strengths":["Simulation gives exact truth to grade every sensor against.","Bias and RMSE separate systematic from random error."]},"hint":"Split the error into a constant part and a random part. Which of the two does averaging shrink?","id":"drones.telemetry-noise","introduction":"Every number a drone reports is an estimate built from imperfect sensors. GPS wanders by metres, a barometer measures altitude changes finely but drifts with the weather, and an IMU measures motion hundreds of times a second but drifts when integrated. Simulation gives you what real flights never do, the truth, so you can measure exactly how wrong each sensor is and in which way.","nuance":"Averaging shrinks independent noise by the square root of N but leaves the mean error untouched. Another sensor can estimate the offset only as well as its own error allows, and GPS altitude wanders by about a metre; EKFs model both.","objective":"Compare simulated telemetry with the true state over a flight, compute bias and RMSE per sensor, and explain why smoothing one sensor fails and sensor fusion is needed.","question":"A barometer reads 1.5 m high because the air pressure changed after take-off. Will averaging more barometer samples remove that error?","references":["https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf","https://ardupilot.org/copter/docs/common-apm-navigation-extended-kalman-filter-overview.html","https://en.wikipedia.org/wiki/Root_mean_square_deviation","https://en.wikipedia.org/wiki/Sensor_fusion"],"reviewAnswer":"No: it cuts noise only; bias needs another reference","reviewPrompt":"Can averaging remove a bias?","sections":[{"body":"GNSS gives absolute position and velocity at 5 to 10 Hz; a standalone receiver is good to a metre or a few horizontally and worse vertically, and its errors are correlated over seconds to minutes because they come from multipath, the atmosphere and satellite geometry. RTK with a base station brings that to centimetres. Receivers also measure velocity from Doppler shifts, often to better than 0.1 m/s, with errors that do not wander like position. A barometer turns pressure into altitude with fine resolution, but drifts as the weather and temperature change and is disturbed by propeller wash, ground effect and airspeed. The IMU's accelerometers and gyroscopes run at hundreds of hertz to kilohertz and are excellent over short times, but their biases integrate: velocity error grows with time and position error with its square, and vibration makes it worse. The magnetometer gives heading and is disturbed by motor currents and nearby steel. Each sensor is good where another is weak.","title":"What each sensor gives you"},{"body":"Define error as measured minus true. The bias is the mean error, the systematic part; the RMSE is the square root of the mean squared error and includes both parts, since RMSE squared equals bias squared plus the variance. The maximum error matters for safety margins such as the buffer between a geofence and the boundary it protects. Horizontal error is the length of a 2D vector: with independent noise of sigma per axis its RMSE is sigma times the square root of 2. An error that wanders more slowly than your measurement window looks like bias: over one short flight its mean is not zero, even though it averages out over hours. Datasheets quote CEP, 2DRMS or 95% figures; know which one you are reading before comparing receivers.","title":"Bias, RMSE and maximum error"},{"body":"The program takes off to 20 m, hovers for 60 s, flies three legs (one climbing to 30 m) in a wind of about 3 m/s with 1.5 m/s gusts, and returns home. Before every step, record pairs the telemetry report with State() when the report is stamped with the current time, the only moment when truth and measurement describe the same instant. It prints the mean error, RMSE and maximum error of GPS position, barometer and velocity; averages N GPS samples in the hover and compares the result with what independent noise would give; measures a 1 s average while moving; integrates velocity from the first GPS fix; and estimates a 1.5 m weather offset added to the baro from GPS altitude.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// errStats accumulates measurement errors (measured minus true).\ntype errStats struct {\n\tn               int\n\tsum, sumSq, max float64\n}\n\nfunc (s *errStats) add(e float64) {\n\ts.n++\n\ts.sum += e\n\ts.sumSq += e * e\n\ts.max = max(s.max, math.Abs(e))\n}\n\nfunc (s *errStats) bias() float64 { return s.sum / float64(s.n) }\nfunc (s *errStats) rmse() float64 { return math.Sqrt(s.sumSq / float64(s.n)) }\n\n// sample is one telemetry report next to the truth at the same instant.\ntype sample struct {\n\tt          float64\n\ttruth, gps drone.Vec3\n\tvel, trueV drone.Vec3\n\tbaro       float64\n\tmoving     bool\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1.5, Seed: 7})\n\td := sim.Drone()\n\n\tvar samples []sample\n\tlastTel := -1.0\n\t// record runs before every step. Telemetry is refreshed at 5 Hz inside\n\t// Step, so a report stamped with the current time pairs with State().\n\trecord := func() {\n\t\ttel, st := d.Telemetry(), d.State()\n\t\tif tel.Time != lastTel && tel.Time == sim.Time() && !st.Landed {\n\t\t\tlastTel = tel.Time\n\t\t\tsamples = append(samples, sample{tel.Time, st.Pos, tel.GPS, tel.Velocity, st.Vel,\n\t\t\t\ttel.BaroAlt, st.Vel.Horizontal().Len() > 1})\n\t\t}\n\t}\n\tfly := func(limit float64, done func() bool) {\n\t\tif !sim.RunUntil(limit, func(float64) bool { record(); return done() }) {\n\t\t\tlog.Fatalf(\"leg not finished: %+v\", d.State())\n\t\t}\n\t}\n\n\tmust(d.Arm())\n\tmust(d.TakeOff(20))\n\tfly(30, func() bool { return d.State().Mode == drone.Hold })\n\tsim.Mark(\"hover 60 s\")\n\tfirst := len(samples)\n\tsim.Run(60, func(float64) { record() })\n\thover := samples[first:]\n\tfor _, wp := range []drone.Vec3{{X: 80, Y: 0, Z: 20}, {X: 80, Y: 80, Z: 30}, {X: 0, Y: 80, Z: 30}} {\n\t\tmust(d.GoTo(wp))\n\t\tfly(90, d.Arrived)\n\t}\n\tmust(d.ReturnHome())\n\tfly(120, func() bool { return d.State().Landed })\n\n\tvar gpsH, gpsE, gpsN, gpsV, baro, velH, velE, velN errStats\n\tfor _, s := range samples {\n\t\te := s.gps.Sub(s.truth)\n\t\tgpsH.add(e.Horizontal().Len())\n\t\tgpsE.add(e.X)\n\t\tgpsN.add(e.Y)\n\t\tgpsV.add(e.Z)\n\t\tbaro.add(s.baro - s.truth.Z)\n\t\tv := s.vel.Sub(s.trueV)\n\t\tvelH.add(v.Horizontal().Len())\n\t\tvelE.add(v.X)\n\t\tvelN.add(v.Y)\n\t}\n\tfmt.Printf(\"%d telemetry samples at 5 Hz over %.0f s of flight\\n\", len(samples), samples[len(samples)-1].t-samples[0].t)\n\tfmt.Println(\"sensor               mean error              RMSE       max |err|\")\n\trow := func(name, bias, unit string, s errStats) {\n\t\tfmt.Printf(\"%-20s %-22s %5.2f %-4s %5.2f %s\\n\", name, bias, s.rmse(), unit, s.max, unit)\n\t}\n\trow(\"GPS horizontal\", fmt.Sprintf(\"e %+.2f n %+.2f m\", gpsE.bias(), gpsN.bias()), \"m\", gpsH)\n\trow(\"GPS vertical\", fmt.Sprintf(\"%+.2f m\", gpsV.bias()), \"m\", gpsV)\n\trow(\"barometer\", fmt.Sprintf(\"%+.2f m\", baro.bias()), \"m\", baro)\n\trow(\"velocity horizontal\", fmt.Sprintf(\"e %+.3f n %+.3f m/s\", velE.bias(), velN.bias()), \"m/s\", velH)\n\n\t// Averaging N samples in the hover. Independent noise would shrink by the\n\t// square root of N; an error that wanders for tens of seconds does not.\n\tfmt.Println(\"GPS horizontal error of an N-sample average, 60 s hover:\")\n\tvar one float64\n\tfor _, n := range []int{1, 5, 25, 100} {\n\t\tvar s errStats\n\t\tfor i := n; i <= len(hover); i++ {\n\t\t\tvar avg drone.Vec3\n\t\t\tfor _, h := range hover[i-n : i] {\n\t\t\t\tavg = avg.Add(h.gps.Sub(h.truth).Scale(1 / float64(n)))\n\t\t\t}\n\t\t\ts.add(avg.Horizontal().Len())\n\t\t}\n\t\tif n == 1 {\n\t\t\tone = s.rmse()\n\t\t}\n\t\tfmt.Printf(\"  N=%3d (%4.1f s): RMSE %.2f m, independent noise would give %.2f m\\n\",\n\t\t\tn, float64(n)/5, s.rmse(), one/math.Sqrt(float64(n)))\n\t}\n\n\t// In motion an average also lags: it reports where the drone was.\n\tvar lag errStats\n\tfor i := 4; i < len(samples); i++ {\n\t\tif !samples[i].moving {\n\t\t\tcontinue\n\t\t}\n\t\tvar avg drone.Vec3\n\t\tfor _, s := range samples[i-4 : i+1] {\n\t\t\tavg = avg.Add(s.gps.Scale(0.2))\n\t\t}\n\t\tlag.add(avg.Sub(samples[i].truth).Horizontal().Len())\n\t}\n\tfmt.Printf(\"GPS 1 s average while moving: RMSE %.2f m over %d samples\\n\", lag.rmse(), lag.n)\n\n\t// Velocity measures change, not position: integrated from the first GPS\n\t// fix it is smooth, but it keeps that fix's error and slowly adds its own.\n\tvar dr errStats\n\tp := samples[0].gps\n\tfor i := 1; i < len(samples); i++ {\n\t\ta, b := samples[i-1], samples[i]\n\t\tp = p.Add(a.vel.Add(b.vel).Scale((b.t - a.t) / 2)) // trapezoid rule\n\t\tdr.add(p.Sub(b.truth).Horizontal().Len())\n\t}\n\tfmt.Printf(\"velocity integrated from the first GPS fix: start error %.2f m, RMSE %.2f m, final %.2f m\\n\",\n\t\tsamples[0].gps.Sub(samples[0].truth).Horizontal().Len(), dr.rmse(),\n\t\tp.Sub(samples[len(samples)-1].truth).Horizontal().Len())\n\n\t// Calibrating one sensor against another inherits the other's error: a\n\t// baro offset estimated from GPS altitude over this flight.\n\tconst weather = 1.5 // pressure fell after take-off: the baro reads 1.5 m high\n\tvar offset float64\n\tfor _, s := range samples {\n\t\toffset += (s.baro + weather - s.gps.Z) / float64(len(samples))\n\t}\n\tfmt.Printf(\"baro offset estimated from GPS altitude: %+.2f m (true %+.2f m)\\n\", offset, weather)\n\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Measure the simulator's sensors","walkthrough":"609 samples over 122 s confirm 5 Hz. GPS RMSE is 1.20 m horizontally and 1.51 m vertically, and over this one flight the mean errors are not zero (e -0.25, n +0.29 m, vertical +1.13 m): an error that wanders for about 20 s does not average out in two minutes, so it looks like bias. The barometer (0.30 m, mean +0.00 m) and velocity (0.14 m/s, means of a few mm/s) carry independent noise. In the hover, averages of 5, 25 and 100 GPS samples are still 1.09, 1.04 and 1.00 m off, where independent noise would fall to 0.57, 0.26 and 0.13 m. While moving, the 1 s average is 4.35 m off because it reports where the drone was 0.4 s earlier. Integrated velocity follows the path but stays as wrong as its first fix: the error is 1.56 m at the start, 1.81 m at the end and 1.85 m RMS. The baro offset estimated from GPS is +0.37 m instead of +1.50 m: the true offset minus GPS altitude's own +1.13 m mean error."},{"body":"The sensors fail in different ways. GPS position is absolute but wanders, so averaging it buys little and lags in motion. Velocity, from GNSS Doppler or an integrated IMU, follows motion precisely over seconds but only measures change, so integrating it inherits the starting error and slowly drifts. The barometer resolves small height changes but its offset moves with the weather, and calibrating it against GPS altitude imports GPS's own wander. A fusion filter predicts with the fast, smooth sensors and corrects with the absolute ones, weighting each by an error model that includes how its error evolves over time. PX4's EKF2 and ArduPilot's EKF3 predict with the IMU, correct with GNSS, barometer, magnetometer and other sensors, and estimate sensor biases as extra states. The simulator still leaves things out: it has no IMU signals and no barometer drift (the program adds the 1.5 m offset itself), and its autopilot flies on the true state, while a real vehicle holds its own estimate and wanders with it. The next unit builds complementary and Kalman filters on these measurements.","title":"Why fusion is needed"},{"body":"In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go. Tap Run to print the tables, then open Output: the replay shows the climb, the 60 s hover mark, the three waypoints and the return home. Change Seed or GPSNoise in drone.Config and run again: the RMSE scales with GPSNoise, the mean errors change sign and size from flight to flight because the error wanders, and the N-sample averages stay stuck near the single-sample error.","title":"Fly it in GopherForge"}],"takeaway":"Measure sensors against truth before trusting them: bias is the mean error and RMSE combines bias and noise. Averaging removes only fast, independent noise, lags in motion and leaves slow GPS wander and bias in place; fusing sensors with complementary errors, as an EKF does, is how flight controllers get estimates good enough to fly on.","title":"Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias","unitID":"drones-foundations","wrongAnswers":["Yes: averaging N samples divides every error by the root of N","Yes, once the averaging window is at least 1 s long"]},{"conceptTag":"drones.pid-altitude","designGuide":{"cautions":["An integral without clamping turns saturation into overshoot.","D differentiates noise; feed it a filtered rate, not raw altitude."],"cost":"A few lines of code and a tuning session per airframe, repeated whenever mass, propellers or battery change.","family":"drones","flow":["Feedforward hover thrust","P on altitude error","I clamped, frozen at limit","D from climb rate"],"ratings":[],"strengths":["Three gains cover most single-axis loops on a multicopter.","Each term maps to a measurable symptom: offset, ringing, overshoot."]},"hint":"Write error = setpoint - measurement and differentiate it. Which part changes instantly when a new altitude is commanded?","id":"drones.pid-altitude","introduction":"SetThrust hands the program the collective thrust: about 0.5 hovers, more climbs, less sinks, and nothing else holds the altitude. Thrust sets vertical acceleration while you care about position, so the plant is a double integrator with a little drag, the simplest plant on which a naive controller rings. This lesson builds the PID found in every flight stack's inner loops, flies four variants of it through the same 10 m step on identical simulators, and measures what each term buys.","nuance":"While the setpoint is constant both forms give the same D term. They differ only at setpoint changes, where d(error)/dt contains the step divided by dt; noise still needs a low-pass filter either way.","objective":"Close an altitude loop through SetThrust with a PID controller that takes its derivative from the measurement, clamps its integral and saturates its output, and judge each variant by rise time, overshoot, settling time and steady-state error.","question":"Why do flight controllers usually compute the PID derivative term from the measured altitude instead of from the error?","references":["https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller","https://en.wikipedia.org/wiki/Integral_windup","https://docs.px4.io/main/en/config_mc/pid_tuning_guide_multicopter.html"],"reviewAnswer":"No derivative kick when the setpoint jumps","reviewPrompt":"Why take D on the measurement?","sections":[{"body":"In this simulator the vertical motion in manual thrust is z'' = 2g(u - 0.5) - 0.3 z': thrust u above 0.5 accelerates upward, below 0.5 downward, and a weak drag is the only damping. The proportional term pushes in proportion to the present error, which on a double integrator acts like a spring with almost no damper, so P alone overshoots and rings. A feedforward bias, the controller's estimate of hover thrust, does most of the holding; when that estimate is wrong (a payload, a sagging battery, a different propeller) a P-only loop needs a standing error to make up the difference, (true hover - bias) / Kp. The integral term accumulates past error until it supplies that missing thrust. The derivative term opposes the rate of change, adding the damping the plant lacks. Each term has a symptom you can measure: offset without I, ringing without D, overshoot when I is allowed to wind up.","title":"Three terms, three jobs"},{"body":"The program climbs to 5 m on the autopilot, waits 2 s, then hands thrust to a controller and commands 15 m for 40 s at 50 Hz. Every controller uses a hover guess of 0.45 while the true hover thrust is 0.50, and reads the true altitude so that only the controller differs (the next lessons replace it with an estimate). Rise time is the time from 10% to 90% of the step, overshoot is the peak beyond 15 m as a share of the 10 m step, settling time is the last moment the altitude was outside a band of 2% of the step (0.2 m), mean err and ripple cover the last 10 s, and sat is the share of steps with thrust at 0 or 1. The PID flight is landed and saved for the replay.","code":"package main\n\n// PID altitude control: the program owns the collective thrust and must\n// climb from 5 m to 15 m and stay there. Four controllers fly the same\n// step on identical simulators; the PID flight is saved for the replay.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// PID computes a thrust command from an altitude error.\ntype PID struct {\n\tKp, Ki, Kd float64\n\tBias       float64 // feedforward: our estimate of hover thrust\n\tMin, Max   float64 // actuator limits\n\tIMax       float64 // limit on the integral's contribution\n\tAntiWindup bool    // clamp the integral and freeze it while saturated\n\n\tintegral float64\n\tprevMeas float64\n\tprimed   bool\n}\n\n// Update runs one control step. The derivative acts on the measurement,\n// not on the error, so a setpoint change does not kick the output.\nfunc (c *PID) Update(setpoint, meas, dt float64) float64 {\n\terr := setpoint - meas\n\tderiv := 0.0\n\tif c.primed {\n\t\tderiv = -(meas - c.prevMeas) / dt\n\t}\n\tc.prevMeas, c.primed = meas, true\n\n\tcandidate := c.integral + c.Ki*err*dt\n\traw := c.Bias + c.Kp*err + candidate + c.Kd*deriv\n\tout := clamp(raw, c.Min, c.Max)\n\tpushingPastLimit := raw != out && (raw > out) == (err > 0)\n\tif !c.AntiWindup || !pushingPastLimit {\n\t\tc.integral = candidate\n\t}\n\tif c.AntiWindup {\n\t\tc.integral = clamp(c.integral, -c.IMax, c.IMax)\n\t}\n\treturn out\n}\n\ntype metrics struct {\n\trise, overshoot, settle float64\n\tsettled                 bool\n\tmeanErr, ripple, sat    float64\n}\n\nconst start, goal, window = 5.0, 15.0, 40.0\n\n// fly climbs to 5 m on the autopilot, then hands thrust to the controller\n// for a 10 m step and measures the response on the true altitude.\nfunc fly(name string, c *PID) (metrics, *drone.Sim) {\n\tsim := drone.New(drone.Config{Seed: 1})\n\td := sim.Drone()\n\td.Arm()\n\td.TakeOff(start)\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n\tsim.Run(2, nil)\n\tsim.Mark(name + \": step to 15 m\")\n\n\tstep := goal - start\n\tt0 := sim.Time()\n\tvar t10, t90, lastOut, sum float64\n\tpeak, lo, hi := start, math.Inf(1), math.Inf(-1)\n\tvar n, satSteps, steps int\n\tsim.Run(window, func(t float64) {\n\t\tz := d.State().Pos.Z\n\t\tu := c.Update(goal, z, sim.Dt())\n\t\td.SetThrust(u)\n\t\tel := t - t0\n\t\tif t10 == 0 && z >= start+0.1*step {\n\t\t\tt10 = el\n\t\t}\n\t\tif t90 == 0 && z >= start+0.9*step {\n\t\t\tt90 = el\n\t\t}\n\t\tpeak = math.Max(peak, z)\n\t\tif math.Abs(goal-z) > 0.02*step {\n\t\t\tlastOut = el\n\t\t}\n\t\tif el >= window-10 {\n\t\t\tsum += goal - z\n\t\t\tlo, hi = math.Min(lo, z), math.Max(hi, z)\n\t\t\tn++\n\t\t}\n\t\tif u == c.Min || u == c.Max {\n\t\t\tsatSteps++\n\t\t}\n\t\tsteps++\n\t})\n\treturn metrics{\n\t\trise:      t90 - t10,\n\t\tovershoot: math.Max(0, peak-goal) / step * 100,\n\t\tsettle:    lastOut,\n\t\tsettled:   lastOut < window-10,\n\t\tmeanErr:   sum / float64(n),\n\t\tripple:    hi - lo,\n\t\tsat:       float64(satSteps) / float64(steps) * 100,\n\t}, sim\n}\n\nfunc main() {\n\tgains := func(kp, ki, kd float64, antiWindup bool) *PID {\n\t\treturn &PID{Kp: kp, Ki: ki, Kd: kd, Bias: 0.45, Min: 0, Max: 1, IMax: 0.1, AntiWindup: antiWindup}\n\t}\n\truns := []struct {\n\t\tname string\n\t\tc    *PID\n\t}{\n\t\t{\"P\", gains(0.10, 0, 0, true)},\n\t\t{\"PI\", gains(0.10, 0.03, 0, true)},\n\t\t{\"PID\", gains(0.10, 0.03, 0.12, true)},\n\t\t{\"PID no anti-windup\", gains(0.10, 0.03, 0.12, false)},\n\t}\n\n\tfmt.Println(\"step 5 m -> 15 m, hover guess 0.45 (true hover 0.50), 50 Hz\")\n\tfmt.Printf(\"%-19s %6s %9s %8s %9s %7s %5s\\n\", \"controller\", \"rise\", \"overshoot\", \"settle\", \"mean err\", \"ripple\", \"sat\")\n\tvar keep *drone.Sim\n\tfor _, r := range runs {\n\t\tm, sim := fly(r.name, r.c)\n\t\tsettle := \"never\"\n\t\tif m.settled {\n\t\t\tsettle = fmt.Sprintf(\"%.1f s\", m.settle)\n\t\t}\n\t\tfmt.Printf(\"%-19s %4.1f s %8.0f%% %8s %7.2f m %5.2f m %4.0f%%\\n\",\n\t\t\tr.name, m.rise, m.overshoot, settle, m.meanErr, m.ripple, m.sat)\n\t\tif r.name == \"PID\" {\n\t\t\tkeep = sim\n\t\t}\n\t}\n\n\td := keep.Drone()\n\td.Land()\n\tkeep.RunUntil(60, func(float64) bool { return d.State().Landed })\n\tkeep.Save()\n}\n\nfunc clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }","language":"go","title":"Four controllers, one step","walkthrough":"P rises fastest (1.0 s) but overshoots 55%, never enters the 0.2 m band and settles at a mean error of 0.50 m, exactly (0.50 - 0.45) / 0.10. PI removes that offset on average but adds lag to a loop that had almost no damping: 60% overshoot and a ripple of 7.25 m still swinging after 30 s. PID rises in 2.0 s with 4% overshoot, settles in 7.7 s and ends at 0.00 m error. The same gains without anti-windup reach 25% overshoot and settle in 9.5 s, because the integral grew during the climb and had to unwind past the target. The last line is the saved PID flight: landed, battery 90%."},{"body":"Because error = setpoint - measurement, its derivative equals minus the measurement's derivative whenever the setpoint is constant. The two differ only when the setpoint changes: a 10 m step differentiated over one 0.02 s sample is 500 m/s, which times Kd = 0.12 asks for a thrust of 60 for one step, a derivative kick that slams the motors. Taking D from the measurement keeps all the damping and drops the kick. The derivative also amplifies noise: differencing a barometer with 0.3 m of noise at 50 Hz gives a rate noise of about 21 m/s. Real controllers therefore take the rate from the estimator (or the gyro, for the rate loop) and low-pass filter the D path, as PX4 does in its rate controller.","code":"// Derivative on error: kicks when the setpoint jumps.\ndErr := (err - c.prevErr) / dt\n\n// Derivative on measurement: equal while the setpoint is constant,\n// and no kick when it changes.\ndMeas := -(meas - c.prevMeas) / dt\n\n// Better: the estimator's climb rate, low-pass filtered (tauD seconds).\nc.dFilt += (-climbRate - c.dFilt) * dt / (tauD + dt)\nd := c.Kd * c.dFilt","language":"go","title":"Derivative on measurement, not on error","walkthrough":"The first form differentiates the setpoint too. The second is what the program's Update method does. The third avoids differencing a noisy altitude at all: an estimator already provides the climb rate, and a first-order low-pass with time constant tauD trims what noise remains before the gain multiplies it."},{"body":"Thrust is limited to 0..1, so for part of a large step the controller asks for more than the motors can give. An integral that keeps accumulating during that time stores error the plant could never act on, and it must be paid back as overshoot after the target is reached. The program uses two common defences together: it clamps the integral's contribution to 0.1 of thrust (twice the expected hover error), and it freezes integration while the output is saturated in the direction the error pushes. Back-calculation, which bleeds the integral by the amount the output was clipped, is a third. Also reset or preload the integral when a mode hands control to the loop, so the first output continues the previous thrust instead of jumping, and saturate the output yourself rather than trusting the next layer to do it.","title":"Windup, clamping and saturation"},{"body":"Create the project with New project > Robotics and simulation > Drone flight, replace main.go with this lesson's program (mission.go can stay; this program does not use it) and tap Run. The table appears in the console; open Output to watch the replay of the PID flight: the take-off to 5 m, the marked step to 15 m with its small overshoot in the altitude strip, and the landing. Then change the gains in main, for example Kd to 0 or AntiWindup to false, and compare the tables and replays.","title":"Fly it in GopherForge"}],"takeaway":"On a thrust-to-altitude loop, P alone leaves an offset and rings, I removes the offset but adds lag, and D supplies the damping. Take D from the measurement, clamp the integral and freeze it while the output saturates, and judge a tune by rise time, overshoot, settling time and steady-state error.","title":"PID altitude control: P, I and D on the collective thrust","unitID":"drones-control","wrongAnswers":["It removes the steady-state error that P leaves","It stops the integral from winding up"]},{"conceptTag":"drones.cascaded-control","designGuide":{"cautions":["An outer loop nearly as fast as the inner one oscillates.","Noise in the target velocity passes straight through feedforward.","A lost setpoint stream makes PX4 leave offboard mode."],"cost":"One small controller per axis, a fixed-rate loop, and a setpoint stream the autopilot can rely on.","family":"drones","flow":["Target pos and velocity","P + feedforward -> vel","SetVelocity PI loop","Attitude and rate in FC"],"ratings":[],"strengths":["Each loop is simple and is tuned on its own, inside out.","Go closes only the slow outer loop; the firmware keeps the fast ones."]},"hint":"In steady following the outer loop must command 3 m/s. With only P, what error produces that command?","id":"drones.cascaded-control","introduction":"No flight stack controls position with one big loop. PX4 and ArduPilot nest them: position error becomes a velocity setpoint, velocity error an acceleration and tilt, attitude error a body rate, rate error a torque for the mixer. Each loop only has to control something that already responds quickly, because the loop inside it made it so. A companion computer running Go usually sits at the top of this cascade and sends position or velocity setpoints; this lesson writes that outer loop, holds a point in a 4 m/s wind and then follows a target that moves into the wind.","nuance":"Steady wind is different: the velocity loop's integral cancels it, and the P hold stayed within 0.12 m. An outer integral also removes the lag, after a 4.29 m transient; feedforward stayed within 0.77 m.","objective":"Build an outer position loop that sends velocity setpoints through SetVelocity, explain why inner loops must be faster and where the integrator belongs, and compare P, PI and velocity feedforward when holding a point in wind and following a moving target.","question":"An outer P position loop with Kp 0.5 follows a target moving steadily at 3 m/s, over a velocity loop that tracks well. How far behind does the drone settle, and what removes the lag?","references":["https://docs.px4.io/main/en/flight_stack/controller_diagrams.html","https://docs.px4.io/main/en/flight_modes/offboard.html","https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller"],"reviewAnswer":"v / Kp = 6 m behind; feedforward removes it","reviewPrompt":"P loop follows 3 m/s, Kp 0.5: lag?","sections":[{"body":"PX4's multicopter controller is documented as a standard cascade: a P position loop (MPC_XY_P) produces a velocity setpoint, a PID velocity loop produces an acceleration, which becomes a thrust vector and attitude setpoint, a P attitude loop produces body rates, and a PID rate loop produces torques for control allocation. The rate loop runs at the gyro rate in the firmware, far faster than the position loop. The rule of thumb is that each inner loop should be several times, often five to ten times, faster in bandwidth than the loop around it, so the outer loop can treat it as nearly instant. In this simulator SetVelocity's loop is a PI loop on ground velocity that tilts the thrust by up to 35 degrees; its proportional gain of 2.5 per second gives a time constant of about 0.4 s, and it is stepped at 50 Hz. The program's position loop runs at 10 Hz with Kp = 0.5, a time constant of 2 s, five times slower. An outer gain close to the inner loop's bandwidth sees the inner loop's lag as phase loss and oscillates.","title":"The cascade and its rates"},{"body":"The program takes off to 10 m in a 4 m/s wind from the west with 1.5 m/s gusts. It first sends velocity zero with no position loop for 20 s, then holds the point with a P loop (Kp 0.5) for 20 s. Then the target starts moving west, into the wind, at 3 m/s, and three outer loops follow it for 30 s each: P alone, PI with Ki 0.1 (integral limited to 5 m/s and frozen while the command is at its limit), and P plus velocity feedforward. Before each of the last two runs the target stops for 15 s, so every run starts from a hover. The position loop runs on every fifth 50 Hz step; altitude has its own P term. Each row reports the largest horizontal distance from the target, and the mean east offset and mean east velocity command over the last 10 s.","code":"package main\n\n// Cascaded control: the program closes a position loop at 10 Hz and sends\n// velocity setpoints to the autopilot's faster velocity loop (SetVelocity).\n// A 4 m/s wind from the west with 1.5 m/s gusts pushes the drone east.\n// The drone first holds a point, then follows a target moving upwind.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// PositionLoop turns a position error into a velocity setpoint.\ntype PositionLoop struct {\n\tKp, Ki      float64\n\tFeedForward bool    // add the target's own velocity to the command\n\tMaxSpeed    float64 // limit on the commanded horizontal speed\n\tMaxI        float64 // limit on the integral's contribution, m/s\n\n\tintegral drone.Vec3\n}\n\nfunc (c *PositionLoop) Update(target, targetVel, pos drone.Vec3, dt float64) drone.Vec3 {\n\terr := target.Sub(pos).Horizontal()\n\tcmd := err.Scale(c.Kp)\n\tif c.FeedForward {\n\t\tcmd = cmd.Add(targetVel.Horizontal())\n\t}\n\tif c.Ki > 0 {\n\t\tif cmd.Add(c.integral).Len() < c.MaxSpeed { // integrate only while not limited\n\t\t\tc.integral = clampLen(c.integral.Add(err.Scale(c.Ki*dt)), c.MaxI)\n\t\t}\n\t\tcmd = cmd.Add(c.integral)\n\t}\n\treturn clampLen(cmd, c.MaxSpeed)\n}\n\ntype phase struct {\n\tname   string\n\tloop   *PositionLoop // nil: no position loop, velocity setpoint zero\n\tfollow bool          // the target moves upwind at 3 m/s\n\tsecs   float64\n\tquiet  bool // a pause between runs: the target stops, nothing is printed\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 4}, Gust: 1.5, Seed: 2})\n\td := sim.Drone()\n\td.Arm()\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\ttarget := d.State().Pos\n\ttargetVel := drone.Vec3{X: -3} // west, into the wind\n\tsim.Waypoint(target)\n\n\tconst outerEvery = 5 // physics runs at 50 Hz, the position loop at 10 Hz\n\touterDt := outerEvery * sim.Dt()\n\tpause := phase{\"target stops\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 15, true}\n\tphases := []phase{\n\t\t{\"velocity 0, no position loop\", nil, false, 20, false},\n\t\t{\"hold, P Kp 0.5\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 20, false},\n\t\t{\"follow, P Kp 0.5\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, true, 30, false},\n\t\tpause,\n\t\t{\"follow, PI Ki 0.1\", &PositionLoop{Kp: 0.5, Ki: 0.1, MaxSpeed: 10, MaxI: 5}, true, 30, false},\n\t\tpause,\n\t\t{\"follow, P + feedforward\", &PositionLoop{Kp: 0.5, FeedForward: true, MaxSpeed: 10}, true, 30, false},\n\t}\n\tfmt.Printf(\"wind (4.0, 0.0) m/s, gusts 1.5 m/s; position loop %.0f Hz over SetVelocity\\n\", 1/outerDt)\n\tfmt.Println(\"means over the last 10 s; x off > 0: east of the target, downwind and behind\")\n\tfmt.Printf(\"%-28s %8s %10s %12s\\n\", \"phase\", \"max off\", \"mean x off\", \"mean cmd vx\")\n\tfor _, p := range phases {\n\t\tsim.Mark(p.name)\n\t\tvar cmd drone.Vec3\n\t\tvar maxOff, sumOff, sumCmd float64\n\t\tvar n, step int\n\t\tt0 := sim.Time()\n\t\tsim.Run(p.secs, func(t float64) {\n\t\t\tif p.follow {\n\t\t\t\ttarget = target.Add(targetVel.Scale(sim.Dt()))\n\t\t\t}\n\t\t\tpos := d.State().Pos\n\t\t\tif step%outerEvery == 0 {\n\t\t\t\tcmd = drone.Vec3{}\n\t\t\t\tif p.loop != nil {\n\t\t\t\t\tv := drone.Vec3{}\n\t\t\t\t\tif p.follow {\n\t\t\t\t\t\tv = targetVel\n\t\t\t\t\t}\n\t\t\t\t\tcmd = p.loop.Update(target, v, pos, outerDt)\n\t\t\t\t}\n\t\t\t\tcmd.Z = 0.8 * (target.Z - pos.Z) // altitude: a plain P loop\n\t\t\t\td.SetVelocity(cmd, 0)\n\t\t\t}\n\t\t\tstep++\n\t\t\tmaxOff = math.Max(maxOff, pos.Sub(target).Horizontal().Len())\n\t\t\tif t-t0 >= p.secs-10 {\n\t\t\t\tsumOff += pos.X - target.X // positive: east, downwind of the target\n\t\t\t\tsumCmd += cmd.X\n\t\t\t\tn++\n\t\t\t}\n\t\t})\n\t\tif !p.quiet {\n\t\t\tfmt.Printf(\"%-28s %6.2f m %8.2f m %8.2f m/s\\n\", p.name, maxOff, sumOff/float64(n), sumCmd/float64(n))\n\t\t}\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(float64) bool { return d.State().Landed })\n\tsim.Save()\n}\n\nfunc clampLen(v drone.Vec3, limit float64) drone.Vec3 {\n\tif l := v.Len(); l > limit {\n\t\treturn v.Scale(limit / l)\n\t}\n\treturn v\n}","language":"go","title":"Hold a point, then follow a target","walkthrough":"Velocity zero without any position loop stays within 0.18 m: the autopilot's velocity loop has an integral that learned the tilt against the 4 m/s wind during the take-off, and the gusts change slowly enough for it to follow. The P hold stays within 0.12 m with a mean command of 0.00 m/s, so the outer loop never sees the steady wind. Following the target, P alone settles 5.99 m behind while commanding -3.00 m/s: a P loop commands speed only in proportion to error, and 3 / 0.5 = 6 m. PI removes the lag (-0.03 m) after a 4.29 m transient. Feedforward removes it from the start and never falls more than 0.77 m behind."},{"body":"A steady disturbance is best cancelled by the loop it enters. Wind is a force, it shows up first as a velocity error, and an integral in the velocity loop learns the tilt that cancels it. PX4 is built this way, with a P position loop over a PID velocity loop, so a position setpoint is held in steady wind with no position integral; that is what the hold rows show. A moving reference is different: an outer P loop needs a standing error to command a speed, error = v / Kp. An outer integral removes that lag, but slowly, with overshoot and windup, and it can fight the inner integral in gusts. Feedforward is the better tool: send the target's velocity directly and let P correct only the residual, as PX4's position controller does with the velocity of a trajectory setpoint. Keep an outer integral for errors the inner loop cannot see, such as a target whose velocity you cannot measure.","code":"// Observe estimates the target's velocity from its reported positions,\n// low-passed so that position noise does not reach the feedforward.\nfunc (f *Follower) Observe(p drone.Vec3, t float64) {\n\tif f.seen && t > f.lastT {\n\t\traw := p.Sub(f.last).Scale(1 / (t - f.lastT))\n\t\tf.vel = f.vel.Add(raw.Sub(f.vel).Scale(f.Alpha))\n\t}\n\tf.last, f.lastT, f.seen = p, t, true\n}\n\n// Command feeds the velocity forward; P corrects only what is left.\nfunc (f *Follower) Command(pos drone.Vec3, now float64) drone.Vec3 {\n\tahead := f.last.Add(f.vel.Scale(now - f.lastT)) // where it is now\n\terr := ahead.Sub(pos).Horizontal()\n\treturn clampLen(f.vel.Horizontal().Add(err.Scale(f.Kp)), f.MaxSpeed)\n}","language":"go","title":"Where the integrator belongs","walkthrough":"On a real vehicle the target's velocity comes from its own reports or from a camera tracker. Differencing positions amplifies their noise, so the estimate is low-passed with Alpha between 0 and 1, and the last report is extrapolated to the present so that report latency does not become lag. Whatever noise remains in the feedforward goes straight into the velocity setpoint."},{"body":"On a real vehicle the Go program sends setpoints over MAVLink (SET_POSITION_TARGET_LOCAL_NED, which carries position, velocity and acceleration fields, so feedforward travels with the position) or ROS 2 (TrajectorySetpoint), typically at 10 to 50 Hz. PX4 requires a continuous stream of at least 2 Hz before it enters offboard mode and leaves offboard mode when the stream stops for longer than COM_OF_LOSS_T, so the loop must keep sending even when nothing changes. MAVLink local frames are NED while this simulator is ENU: north is the simulator's Y, east its X, and down is minus Z. Prefer sending position setpoints and letting the tuned firmware loops do the work; write your own outer loop when the task needs it, such as following a moving target or centring over a landing pad seen by a camera.","title":"Setpoints from a companion computer"},{"body":"Use New project > Robotics and simulation > Drone flight, replace main.go with this program (keep mission.go; it is not used here) and Run. Open Output: the replay shows the wind arrow, the waypoint above the take-off point, the hold, and the three runs heading west with a timeline mark for each phase. Try Kp 1.0 and the P lag shrinks to about 3 m; raise the gusts in drone.Config, or move the position loop to 2 Hz by changing outerEvery to 25, and watch the offsets grow.","title":"Fly it in GopherForge"}],"takeaway":"Nest loops so that each controls a quantity the faster loop inside it has already made responsive, and put the integrator where the disturbance enters: the velocity loop's integral cancels steady wind, so a P position loop holds a point. To follow a moving target, feed its velocity forward; a P loop alone lags by v / Kp.","title":"Cascaded control: a position loop on top of a velocity loop","unitID":"drones-control","wrongAnswers":["No lag: the velocity loop's integral removes it","3 m behind; a faster velocity loop removes it"]},{"conceptTag":"drones.complementary-filter","designGuide":{"cautions":["A sensor bias leaves a steady error of bias times tau.","An alpha computed for one rate but applied at another changes tau."],"cost":"One state and one parameter per signal, plus a bias state when the fast sensor drifts.","family":"drones","flow":["Integrate fast signal","Blend with alpha","Correct on baro sample","Score RMSE vs truth"],"ratings":[],"strengths":["A few multiplications per step, no matrices, easy to reason about.","Real motion passes without lag; each sensor's error is cut where it is large."]},"hint":"Each second the velocity path pushes the estimate by b, and the barometer path pulls it back by the error divided by tau. Where do they balance?","id":"drones.complementary-filter","introduction":"Sensors on a drone are either fast and smooth but drifting, or absolute but noisy and slow. Integrating an inertial vertical velocity gives a clean altitude that walks away over time; the barometer never walks away but jumps by tens of centimetres from sample to sample. A complementary filter takes the high frequencies from the first and the low frequencies from the second, with one parameter, the crossover time constant. It costs a few multiplications per step and is the right first estimator to write before a Kalman filter.","nuance":"The program's tau 1 s row has a mean error of 0.12 m and tau 3 s has 0.30 m, close to 0.10 m/s times tau. Estimating the bias as a third state removes the offset.","objective":"Estimate altitude by integrating a biased vertical velocity at 50 Hz and correcting it with the 5 Hz barometer, choose the time constant tau and alpha = tau / (tau + dt), and measure the result as RMSE against the true altitude.","question":"A complementary filter integrates a vertical velocity with a constant bias b and corrects it with a barometer using time constant tau. What altitude error remains in steady flight?","references":["https://en.wikipedia.org/wiki/Low-pass_filter","https://en.wikipedia.org/wiki/Alpha_beta_filter","https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf.html"],"reviewAnswer":"A steady altitude offset of about b times tau","reviewPrompt":"Bias b, time constant tau: error?","sections":[{"body":"The filter is z = alpha * (z + v * dt) + (1 - alpha) * baro with alpha = tau / (tau + dt), where dt is the period at which the blend runs. Seen from the velocity path it is a high-pass filter, seen from the barometer a low-pass filter, both with time constant tau, and the two transfer functions add up to exactly one. A real altitude change therefore passes through without lag, while each sensor's error is suppressed where it is large: barometer noise faster than tau, velocity bias slower than tau. Two consequences follow directly. A constant velocity bias b leaves a steady altitude error of b * tau. White barometer noise of sigma passes with a standard deviation of about sigma * sqrt((1 - alpha) / (1 + alpha)).","title":"High-pass plus low-pass equals one"},{"body":"The program flies a take-off to 20 m, three waypoints at 32, 12 and 26 m and a return home. Its velocity sensor is the true climb rate plus a 0.10 m/s bias and 0.10 m/s of noise at 50 Hz, a stand-in for an inertial vertical velocity. The simulator's Telemetry().Velocity is noisy too (0.15 m/s vertically, at 5 Hz) but has no bias, and bias is what makes integration drift, so the lesson models its own sensor. Five filters with different tau run side by side on the same data: each integrates the velocity every step and blends in each new barometer sample with alpha = tau / (tau + 0.2). All estimates are scored at every barometer sample against the true altitude.","code":"package main\n\n// A complementary filter for altitude: a 50 Hz vertical-velocity signal\n// with a bias (fast, smooth, drifts when integrated) fused with the 5 Hz\n// barometer (no drift, 0.3 m of noise). Several time constants run side by\n// side on the same flight and are scored against the true altitude.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/rand/v2\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Complementary blends a prediction from velocity with a measurement.\ntype Complementary struct {\n\tTau float64 // time constant, s: below it trust the baro, above it the velocity\n\tZ   float64\n}\n\n// Predict integrates the velocity signal over one step.\nfunc (f *Complementary) Predict(vz, dt float64) { f.Z += vz * dt }\n\n// Correct blends in a barometer sample that arrives every period seconds.\nfunc (f *Complementary) Correct(baro, period float64) {\n\talpha := f.Tau / (f.Tau + period)\n\tf.Z = alpha*f.Z + (1-alpha)*baro\n}\n\ntype score struct{ sumSq, maxAbs, sum float64 }\n\nfunc (s *score) add(err float64) {\n\ts.sumSq += err * err\n\ts.sum += err\n\ts.maxAbs = math.Max(s.maxAbs, math.Abs(err))\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Seed: 3})\n\td := sim.Drone()\n\tnoise := rand.New(rand.NewPCG(3, 33))\n\tconst bias, sigma = 0.10, 0.10 // velocity sensor: m/s bias, m/s noise\n\tconst baroPeriod = 0.2\n\n\ttaus := []float64{0.1, 0.3, 1, 3, 10}\n\tfilters := make([]*Complementary, len(taus))\n\tfor i, tau := range taus {\n\t\tfilters[i] = &Complementary{Tau: tau}\n\t}\n\tdeadReckoned := 0.0\n\tscores := make([]score, len(taus)+2) // baro, dead reckoning, filters\n\tvar lastBaro float64\n\tvar samples int\n\n\testimate := func(float64) {\n\t\tst := d.State()\n\t\tvz := st.Vel.Z + bias + sigma*noise.NormFloat64()\n\t\tdt := sim.Dt()\n\t\tdeadReckoned += vz * dt\n\t\tfor _, f := range filters {\n\t\t\tf.Predict(vz, dt)\n\t\t}\n\t\ttel := d.Telemetry()\n\t\tif tel.Time > lastBaro { // a new barometer sample\n\t\t\tlastBaro = tel.Time\n\t\t\ttruth := st.Pos.Z\n\t\t\tscores[0].add(tel.BaroAlt - truth)\n\t\t\tscores[1].add(deadReckoned - truth)\n\t\t\tfor i, f := range filters {\n\t\t\t\tf.Correct(tel.BaroAlt, baroPeriod)\n\t\t\t\tscores[i+2].add(f.Z - truth)\n\t\t\t}\n\t\t\tsamples++\n\t\t}\n\t}\n\n\td.Arm()\n\td.TakeOff(20)\n\tsim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })\n\tfor _, wp := range []drone.Vec3{{X: 40, Z: 32}, {X: 40, Y: 40, Z: 12}, {Y: 40, Z: 26}} {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })\n\n\tfmt.Printf(\"%.0f s flight, %d baro samples; velocity bias %.2f m/s\\n\", sim.Time(), samples, bias)\n\tfmt.Printf(\"%-23s %8s %8s %8s\\n\", \"estimate\", \"RMSE\", \"max\", \"mean\")\n\tnames := []string{\"raw baro\", \"integrated velocity\"}\n\tfor _, tau := range taus {\n\t\talpha := tau / (tau + baroPeriod)\n\t\tnames = append(names, fmt.Sprintf(\"tau %4.1f s, alpha %.3f\", tau, alpha))\n\t}\n\tfor i, s := range scores {\n\t\tn := float64(samples)\n\t\tfmt.Printf(\"%-23s %6.2f m %6.2f m %6.2f m\\n\", names[i], math.Sqrt(s.sumSq/n), s.maxAbs, s.sum/n)\n\t}\n\tsim.Save()\n}","language":"go","title":"Five time constants on one flight","walkthrough":"The raw barometer has an RMSE of 0.31 m, close to its specified 0.3 m, with a worst sample 0.87 m off. Integrated velocity alone drifts to an RMSE of 2.93 m and a mean of 2.55 m, the 0.10 m/s bias accumulating over the 51 s flight. tau 0.1 s still passes much of the barometer noise (0.22 m); tau 1.0 s is best at 0.15 m, with a mean error of 0.12 m, close to b * tau = 0.10 m. Longer constants trade noise for bias: tau 3.0 s has a mean of 0.30 m and tau 10.0 s 0.82 m, still on its way to 1.0 m when the flight ends."},{"body":"Choose tau where the two error sources cross: shorter than the time over which the fast sensor drifts noticeably, longer than the period over which the slow sensor's noise averages out. Logged flights make this concrete: replay the log through several values, as the program does, and pick the bottom of the curve. If the bias can be estimated, tau can grow. With an accelerometer as the fast sensor, a third-order complementary filter integrates acceleration to velocity and velocity to altitude, and feeds the barometer error back into all three states, including a bias estimate, which removes the b * tau offset.","code":"// Accelerometer-driven altitude filter with a bias estimate.\n// Choosing K1 = 3/tau, K2 = 3/tau^2, K3 = 1/tau^3 puts all three\n// error poles at -1/tau.\nfunc (f *Alt3) Predict(accZ, dt float64) {\n\tf.V += (accZ - f.Bias) * dt\n\tf.Z += f.V * dt\n}\n\nfunc (f *Alt3) Correct(baro, period float64) {\n\te := baro - f.Z\n\tf.Z += f.K1 * e * period\n\tf.V += f.K2 * e * period\n\tf.Bias -= f.K3 * e * period\n}","language":"go","title":"Choosing tau, and removing the bias","walkthrough":"If the accelerometer reads high, the predicted altitude climbs above the barometer, e turns negative, and the bias estimate grows until the prediction stops running away. The error dynamics have the characteristic polynomial s^3 + K1 s^2 + K2 s + K3, so the suggested gains make it critically damped with one time constant."},{"body":"Small flight controllers have long used complementary filters for attitude (gyro plus accelerometer) and altitude; PX4 and ArduPilot now run extended Kalman filters (EKF2, EKF3), but the complementary filter remains the tool of choice in companion and ground code: smoothing a rangefinder with inertial velocity, blending visual odometry with GPS for display, cleaning telemetry plots. Typical bugs: alpha computed for one rate and applied at another (computed for 50 Hz but applied per 5 Hz sample makes tau ten times longer); blending a held, stale sample at every fast step; starting the state at zero instead of the first absolute sample; mixing a sea-level altitude with a take-off-relative one; and forgetting that propeller wash and ground effect bias a barometer near the ground.","title":"Where complementary filters live, and how they fail"},{"body":"Start from New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go may stay) and Run. The console prints the RMSE table; Output replays the flight with its climbs and descents in the altitude strip. Change the bias, the noise or the list of taus at the top of main and watch the best time constant move: with a smaller bias the optimum shifts to longer tau, with more barometer noise as well.","title":"Fly it in GopherForge"}],"takeaway":"A complementary filter trusts the fast sensor above 1/tau and the absolute sensor below it, so real motion passes without lag while barometer noise and velocity drift are both suppressed. Pick tau between the two error sources, and remember that a velocity bias b costs a steady error of b times tau.","title":"Complementary filter: fusing a fast drifting signal with a slow noisy one","unitID":"drones-control","wrongAnswers":["None: the barometer correction removes any bias","An error that grows without limit, as in dead reckoning"]},{"conceptTag":"drones.kalman-filter","designGuide":{"cautions":["An overconfident filter gates out good data and diverges.","Q is a modelling knob; a wrong model cannot be tuned away entirely."],"cost":"A small state vector, a covariance update per step, and log-driven tuning of Q, R and the gates.","family":"drones","flow":["Predict x and P each step","Gate the innovation","Update with K = P/(P+R)","Reset after many rejects"],"ratings":[],"strengths":["Weights sensors by their noise and adapts the gain as it converges.","Estimates unmeasured states such as climb rate, with an uncertainty."]},"hint":"Write K = P00 / (P00 + R). Which quantity shrinks as the filter converges, and which one comes from the sensor?","id":"drones.kalman-filter","introduction":"A complementary filter has a fixed blend. A Kalman filter computes the blend at every step from its own uncertainty: right after start-up it trusts the measurements almost completely, once it has converged it leans on its model, and it weighs a 1.2 m GPS altitude against a 0.3 m barometer by their variances. It also estimates states it does not measure, such as the climb rate from altitude samples alone, fuses a direct measurement of them when one exists, and says how surprising each sample is, which is the basis for rejecting glitches. PX4's EKF2 and ArduPilot's EKF3 run the same predict-update cycle with many more states.","nuance":"With constant Q, R and sample rate the gain converges to a fixed value, 0.384 for altitude here, and the filter behaves like an alpha-beta filter. The covariance still drives gates and resets.","objective":"Write a 1-D constant-velocity Kalman filter that fuses GPS altitude, barometer and a climb-rate measurement, follow its state, covariance, predict and update steps, tune process and measurement noise, and reject outliers with an innovation gate that cannot lock out the truth.","question":"In a 1-D altitude Kalman filter, what determines the gain, the fraction of each barometer innovation applied to the estimate?","references":["https://en.wikipedia.org/wiki/Kalman_filter","https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf.html","https://ardupilot.org/copter/docs/common-apm-navigation-extended-kalman-filter-overview.html"],"reviewAnswer":"Predicted variance versus measurement variance","reviewPrompt":"What sets the Kalman gain?","sections":[{"body":"The state is x = [altitude, climb rate] and P is its 2x2 covariance. Predict assumes constant velocity: altitude += climb rate * dt, and P = F P F^T + Q, where Q models an unknown acceleration with variance q as q * [[dt^4/4, dt^3/2], [dt^3/2, dt^2]]. Update with an altitude sensor (H = [1 0]) forms the innovation y = z - altitude and its predicted variance S = P00 + R, computes the gain K = [P00 / S, P10 / S], adds K * y to the state and shrinks P to (I - K H) P. R is the sensor's noise variance: 1.2^2 m^2 for the simulator's GPS altitude and 0.3^2 for its barometer. A sensor that measures the climb rate uses H = [0 1]: the same equations then pick row and column 1 instead of 0. Sensors arriving together are fused one after the other. With 2x2 matrices, float64 and plain arrays are enough; larger filters use the Joseph form of the covariance update to keep P symmetric and positive.","title":"State, covariance, predict, update"},{"body":"The program predicts at 50 Hz and updates at 5 Hz with the GPS altitude and then the barometer, over a flight with climbs to 35 m and descents to 20 m. Three barometer samples are corrupted on purpose (+8 m twice, -6 m once), as a pressure spike or a sensor glitch would. Five filters start from P = diag(100, 25): Q 0.5, Q 10 and Q 300 with a 4-sigma innovation gate, Q 10 without a gate, and a gated Q 10 filter that also fuses the telemetry's climb rate (0.15 m/s of noise) with H = [0 1]. A gated filter that rejects five samples in a row from one sensor resets that state to the sensor. The program prints the convergence of the Q 10 filter's barometer gains and an error table against the true state.","code":"package main\n\n// A 1-D constant-velocity Kalman filter for altitude and climb rate, fed at\n// 5 Hz by the simulator's GPS altitude (about 1.2 m of slowly wandering\n// error) and barometer (0.3 m, three glitches injected); one filter also\n// fuses the telemetry's climb rate (0.15 m/s of noise).\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Sensors, and the state each one measures: H = [1 0] for altitude,\n// H = [0 1] for climb rate.\nconst (\n\tGPS = iota\n\tBaro\n\tVel\n)\n\nvar measures = [3]int{GPS: 0, Baro: 0, Vel: 1}\n\n// Kalman estimates X = [altitude m, climb rate m/s] with covariance P.\ntype Kalman struct {\n\tX         [2]float64\n\tP         [2][2]float64\n\tQ         float64    // variance of unmodelled acceleration, (m/s^2)^2\n\tR         [3]float64 // measurement variance per sensor\n\tGate      float64    // reject innovations beyond Gate standard deviations; 0 = off\n\tMaxMisses int        // consecutive rejections before a reset\n\n\tmisses           [3]int\n\tRejected, Resets int\n}\n\nfunc NewKalman(q, gate float64) *Kalman {\n\treturn &Kalman{\n\t\tP:         [2][2]float64{{100, 0}, {0, 25}}, // we know nothing yet\n\t\tQ:         q,\n\t\tR:         [3]float64{GPS: 1.2 * 1.2, Baro: 0.3 * 0.3, Vel: 0.15 * 0.15},\n\t\tGate:      gate,\n\t\tMaxMisses: 5,\n\t}\n}\n\n// Predict moves the state forward by dt assuming constant velocity, and\n// grows the covariance by the acceleration the model ignores.\nfunc (k *Kalman) Predict(dt float64) {\n\tk.X[0] += k.X[1] * dt\n\tp := k.P\n\tp00 := p[0][0] + dt*(p[0][1]+p[1][0]) + dt*dt*p[1][1]\n\tp01 := p[0][1] + dt*p[1][1]\n\tp10 := p[1][0] + dt*p[1][1]\n\tdt2 := dt * dt\n\tk.P = [2][2]float64{\n\t\t{p00 + k.Q*dt2*dt2/4, p01 + k.Q*dt2*dt/2},\n\t\t{p10 + k.Q*dt2*dt/2, p[1][1] + k.Q*dt2},\n\t}\n}\n\n// Update fuses one measurement of state i = measures[sensor]. It returns\n// the gains applied to altitude and climb rate (zero when rejected).\nfunc (k *Kalman) Update(sensor int, z float64) (k0, k1 float64) {\n\ti, r := measures[sensor], k.R[sensor]\n\ty := z - k.X[i]    // innovation\n\ts := k.P[i][i] + r // its predicted variance\n\tif k.Gate > 0 && y*y > k.Gate*k.Gate*s {\n\t\tk.misses[sensor]++\n\t\tif k.misses[sensor] < k.MaxMisses {\n\t\t\tk.Rejected++\n\t\t\treturn 0, 0\n\t\t}\n\t\t// The sensor has disagreed for a second: we are probably the ones\n\t\t// who are wrong. Take its value and forget our confidence.\n\t\tk.Resets++\n\t\tk.misses[sensor] = 0\n\t\tk.X[i] = z\n\t\tk.P[0][1], k.P[1][0] = 0, 0\n\t\tk.P[i][i] = r\n\t\tk.P[1-i][1-i] += 4\n\t\treturn 0, 0\n\t}\n\tk.misses[sensor] = 0\n\tk0, k1 = k.P[0][i]/s, k.P[1][i]/s\n\tk.X[0] += k0 * y\n\tk.X[1] += k1 * y\n\tp := k.P // P = (I - K H) P, where H picks row i\n\tk.P = [2][2]float64{\n\t\t{p[0][0] - k0*p[i][0], p[0][1] - k0*p[i][1]},\n\t\t{p[1][0] - k1*p[i][0], p[1][1] - k1*p[i][1]},\n\t}\n\treturn k0, k1\n}\n\ntype rms struct{ sum float64 }\n\nfunc (r *rms) add(e float64)   { r.sum += e * e }\nfunc (r rms) of(n int) float64 { return math.Sqrt(r.sum / float64(n)) }\n\n// glitch adds pressure spikes to a few barometer samples.\nfunc glitch(sample int) float64 {\n\tswitch sample {\n\tcase 120, 121:\n\t\treturn 8\n\tcase 200:\n\t\treturn -6\n\t}\n\treturn 0\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Seed: 4})\n\td := sim.Drone()\n\n\tnames := []string{\"Q 0.5, gate 4\", \"Q 10, gate 4\", \"Q 300, gate 4\", \"Q 10, no gate\", \"Q 10, gate 4, +vel\"}\n\tfilters := []*Kalman{NewKalman(0.5, 4), NewKalman(10, 4), NewKalman(300, 4), NewKalman(10, 0), NewKalman(10, 4)}\n\tfuseVel := []bool{false, false, false, false, true}\n\taltErr := make([]rms, len(filters))\n\tvelErr := make([]rms, len(filters))\n\tvar gpsErr, baroErr, diffErr, velErr0 rms\n\tvar lastTel, prevBaro float64\n\tvar samples int\n\tvar gains [][3]float64\n\n\testimate := func(float64) {\n\t\tfor _, k := range filters {\n\t\t\tk.Predict(sim.Dt())\n\t\t}\n\t\ttel := d.Telemetry()\n\t\tif tel.Time <= lastTel {\n\t\t\treturn\n\t\t}\n\t\tlastTel = tel.Time\n\t\tsamples++\n\t\tbaro := tel.BaroAlt + glitch(samples)\n\t\tst := d.State()\n\t\tfor i, k := range filters {\n\t\t\tk.Update(GPS, tel.GPS.Z)\n\t\t\tkz, kv := k.Update(Baro, baro)\n\t\t\tif fuseVel[i] {\n\t\t\t\tk.Update(Vel, tel.Velocity.Z)\n\t\t\t}\n\t\t\tif i == 1 && (samples <= 3 || samples == 10 || samples == 50) {\n\t\t\t\tgains = append(gains, [3]float64{float64(samples), kz, kv})\n\t\t\t}\n\t\t\taltErr[i].add(k.X[0] - st.Pos.Z)\n\t\t\tvelErr[i].add(k.X[1] - st.Vel.Z)\n\t\t}\n\t\tgpsErr.add(tel.GPS.Z - st.Pos.Z)\n\t\tbaroErr.add(baro - st.Pos.Z)\n\t\tvelErr0.add(tel.Velocity.Z - st.Vel.Z)\n\t\tif samples > 1 {\n\t\t\tdiffErr.add((baro-prevBaro)/0.2 - st.Vel.Z)\n\t\t}\n\t\tprevBaro = baro\n\t}\n\n\td.Arm()\n\td.TakeOff(15)\n\tsim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })\n\tfor _, wp := range []drone.Vec3{{X: 30, Z: 35}, {X: 30, Y: 30, Z: 20}, {Y: 30, Z: 28}} {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })\n\t\tsim.Run(5, estimate)\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })\n\n\tfmt.Println(\"barometer gains of the Q 10 filter:\")\n\tfor _, g := range gains {\n\t\tfmt.Printf(\"  update %2.0f: altitude %.3f, climb rate %.3f /s\\n\", g[0], g[1], g[2])\n\t}\n\tfmt.Printf(\"%d samples at 5 Hz over %.0f s, 3 baro glitches injected\\n\", samples, sim.Time())\n\tfmt.Printf(\"%-25s %8s %10s %8s %6s\\n\", \"estimate\", \"alt RMSE\", \"rate RMSE\", \"rejected\", \"resets\")\n\tfmt.Printf(\"%-25s %6.2f m %10s\\n\", \"raw GPS Z\", gpsErr.of(samples), \"-\")\n\tfmt.Printf(\"%-25s %6.2f m %6.2f m/s\\n\", \"raw baro\", baroErr.of(samples), diffErr.of(samples-1))\n\tfmt.Printf(\"%-25s %8s %6.2f m/s\\n\", \"raw telemetry vel Z\", \"-\", velErr0.of(samples))\n\tfor i, k := range filters {\n\t\tfmt.Printf(\"%-25s %6.2f m %6.2f m/s %8d %6d\\n\", \"Kalman \"+names[i], altErr[i].of(samples), velErr[i].of(samples), k.Rejected, k.Resets)\n\t}\n\tsim.Save()\n}","language":"go","title":"Five filters on one flight","walkthrough":"The first barometer update has an altitude gain of 0.940, because the GPS update just before it already cut the variance from 100 m^2; the second has a climb-rate gain of 4.017 /s as the filter learns velocity from the first difference. By update 10 the gains are 0.395 and 0.504, by update 50 0.384 and 0.498: converged. Raw GPS altitude has an RMSE of 1.14 m, raw barometer 0.77 m including the glitches, and its differences give a 4.49 m/s climb rate; the telemetry's climb rate is off by 0.16 m/s. Q 10 with the gate reaches 0.22 m and 0.49 m/s, rejecting exactly the 3 glitches. Q 0.5 lags every manoeuvre: 20 rejections, 3 resets, 0.54 m. Q 300 follows the noise (0.67 m/s), and without a gate the glitches pull Q 10 to 0.51 m. Fusing the climb rate brings altitude to 0.13 m with a rate error of 0.17 m/s, about the measurement's own; its 5 rejections are the 3 glitches and two climb-rate samples at the start of the descent from 35 m, where the drone accelerates harder than Q allows."},{"body":"R comes from the sensor: log it at rest and measure the variance, or start from the datasheet. Q is the modelling error, everything the constant-velocity model ignores. Here the autopilot accelerates at up to 8 m/s^2 when it starts a climb, so q of about 10 (m/s^2)^2 fits, and the table shows both failure directions. Too small a Q makes the filter overconfident: it lags manoeuvres, its innovations grow, and with a gate it starts rejecting good data. Too large a Q makes it follow every measurement, and the climb rate becomes noisy. A consistency check helps: innovations should average zero, and y^2 / S should average about 1. Better than inflating Q is a better model: feed the accelerometer into the prediction as EKF2 does with the IMU, so Q only covers accelerometer noise and bias. R also assumes white noise, and the simulator's GPS error, like real GNSS, wanders slowly (a Gauss-Markov process with a 20 s time constant), so a filter that treats it as white trusts the GPS too much. The barometer dominates here; when GPS must carry the altitude, add its slowly varying error as a state, as full navigation filters do.","title":"Tuning Q and R"},{"body":"Before an update, y^2 / S tells how surprising the sample is in units of its expected variance. With Gaussian noise a 3-sigma gate still rejects 0.27% of good samples; models are never perfect, so practical gates are often 3 to 5 sigma, and PX4's EKF2 exposes them as parameters such as EKF2_BARO_GATE. The trap is a filter that has drifted: then the truth looks like an outlier, every sample is rejected and the estimate never recovers. Count consecutive rejections per sensor and reset to the sensor after a timeout, as production estimators do, and log every rejection and reset.","code":"i, r := measures[sensor], k.R[sensor]\ny := z - k.X[i]    // innovation\ns := k.P[i][i] + r // its predicted variance\nif k.Gate > 0 && y*y > k.Gate*k.Gate*s {\n\tk.misses[sensor]++\n\tif k.misses[sensor] < k.MaxMisses {\n\t\tk.Rejected++\n\t\treturn 0, 0\n\t}\n\tk.Resets++ // the sensor kept disagreeing: trust it\n\tk.misses[sensor] = 0\n\tk.X[i] = z\n\tk.P[0][1], k.P[1][0] = 0, 0\n\tk.P[i][i] = r\n\tk.P[1-i][1-i] += 4\n\treturn 0, 0\n}","language":"go","title":"Innovation gates and their trap","walkthrough":"The test compares y^2 with Gate^2 * S, so Gate is in standard deviations and no square root is needed. After MaxMisses rejections in a row the filter assumes it is the one that is wrong: it takes the measurement as the value of the state that sensor measures, with the sensor's variance, drops the correlation and widens the other state's variance so the next samples can correct it."},{"body":"Create New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay) and Run. The console shows the gains and the error table; Output replays the flight, whose climbs and descents are what the constant-velocity model has to follow. Edit the glitch function, change Q or the gate in the NewKalman calls, set the gate to 3, or fuse the climb rate in every filter, and watch the errors, rejections and resets change.","title":"Fly it in GopherForge"}],"takeaway":"A Kalman filter computes its blend from the covariance: high gain while uncertain, a steady gain once converged, weights set by each sensor's variance. Tune R from sensor noise and Q from what the model ignores, gate innovations in standard deviations, and reset after repeated rejections so a gate cannot lock out the truth.","title":"A Kalman filter for altitude and climb rate","unitID":"drones-control","wrongAnswers":["A fixed alpha chosen once from the sample rate","The innovation itself: large surprises get a larger fraction"]},{"conceptTag":"drones.loop-timing","designGuide":{"cautions":["Go on Linux cannot promise hard deadlines; fast loops stay in firmware.","The first tick after a stall is late; dt must come from the clock."],"cost":"A ticker, a measured dt, preallocated buffers and a test that pins the allocation count at zero.","family":"drones","flow":["NewTicker, defer Stop","dt from monotonic clock","Zero-alloc loop body","Count and log overruns"],"ratings":[],"strengths":["A ticker keeps a fixed grid and never bursts after a stall.","AllocsPerRun turns \"no allocations\" into a test you can keep."]},"hint":"The time package says a ticker adjusts the interval or drops ticks to make up for slow receivers. How many ticks can be waiting at once?","id":"drones.loop-timing","introduction":"A control loop assumes its dt. When an iteration starts late, the integral and derivative terms are computed with the wrong time step, and a burst of catch-up iterations is worse than a skipped one. Go is a good language for the 10 to 50 Hz supervisory loops of a companion computer or ground station and the wrong one for the kilohertz rate loop inside a flight controller. This lesson runs three loop styles on a virtual clock, so the results are the same on every run, then counts the heap allocations of two versions of a loop body.","nuance":"Since Go 1.23 timer channels are unbuffered and Stop or Reset discard stale ticks, but a late receiver still gets one tick at once. Measure dt with the monotonic clock instead of assuming the period.","objective":"Run a supervisory control loop at a fixed rate with time.Ticker, understand dropped ticks, jitter and the monotonic clock, keep allocations out of the loop body and prove it with testing.AllocsPerRun, and decide what belongs in firmware instead.","question":"A 50 Hz loop reads from a time.Ticker and one iteration blocks for 90 ms. What happens to the ticks that fell due during the stall?","references":["https://pkg.go.dev/time","https://go.dev/doc/gc-guide","https://pkg.go.dev/testing","https://go.dev/doc/go1.23"],"reviewAnswer":"One late tick waits; the rest are dropped","reviewPrompt":"Ticker vs slow receiver?","sections":[{"body":"A Ticker delivers ticks on a fixed grid, so the work inside the loop does not stretch the period, and the time package documents that it adjusts the interval or drops ticks to make up for slow receivers: at most one tick waits, the others are lost, and the grid keeps its phase. Since Go 1.23 timer channels are unbuffered and Stop or Reset guarantee that no stale tick is received afterwards, but a receiver that comes back late still gets one tick at once. Two common alternatives behave worse: time.Sleep(period) after the work makes the period work plus period, and a deadline loop that adds the period and sleeps until the deadline without ever skipping runs late iterations back to back after a stall. Whatever the loop, measure dt instead of assuming it.","code":"func run(ctx context.Context, period time.Duration, step func(dt time.Duration)) (overruns int, err error) {\n\tt := time.NewTicker(period)\n\tdefer t.Stop()\n\tlast := time.Now()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn overruns, ctx.Err()\n\t\tcase <-t.C:\n\t\t\tnow := time.Now()\n\t\t\tdt := now.Sub(last) // monotonic: immune to clock changes\n\t\t\tlast = now\n\t\t\tif dt > 2*period {\n\t\t\t\toverruns++\n\t\t\t\tdt = 2 * period // do not integrate a huge step\n\t\t\t}\n\t\t\tstep(dt)\n\t\t}\n\t}\n}","language":"go","title":"What time.Ticker promises","walkthrough":"time.Now carries a monotonic clock reading and Sub uses it, so an NTP correction of the wall clock cannot produce a negative or huge dt. Overruns are counted for the logs, and dt is limited so that one stall does not turn into one giant integration step in the controller."},{"body":"Sleeping in a lesson program would make its output depend on the machine, so the program models time with integer durations. Each loop body takes 8 to 12 ms from a seeded generator, and two stalls are injected: a 90 ms blocking log write at 0.6 s and 30 ms of CPU contention at 1.3 s. The sleep loop, the ticker and the catch-up deadline loop each run for 2 s at a 20 ms period. The table counts runs, 20 ms slots in which no iteration started, dropped ticks, the smallest and largest gap between starts, the worst lag behind the tick an iteration serves and the number of stale runs, those more than one period late. Then testing.AllocsPerRun measures two versions of a loop body.","code":"package main\n\n// Loop timing on a virtual clock: three ways to run a 50 Hz control loop\n// meet the same jittery workload and two stalls. Then testing.AllocsPerRun\n// counts heap allocations of two versions of the loop body.\n\nimport (\n\t\"fmt\"\n\t\"math/rand/v2\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tperiod  = 20 * time.Millisecond // 50 Hz\n\thorizon = 2 * time.Second\n)\n\ntype stall struct {\n\tat, dur time.Duration\n\twhy     string\n}\n\nvar stalls = []stall{\n\t{600 * time.Millisecond, 90 * time.Millisecond, \"blocking log write\"},\n\t{1300 * time.Millisecond, 30 * time.Millisecond, \"CPU contention\"},\n}\n\n// worker decides how long each loop body takes: 8-12 ms of work plus any\n// stall due at the moment it starts. Every loop style gets the same seed.\ntype worker struct {\n\trng  *rand.Rand\n\tnext int\n}\n\nfunc newWorker() *worker { return &worker{rng: rand.New(rand.NewPCG(5, 50))} }\n\nfunc (w *worker) run(start time.Duration) time.Duration {\n\td := 8*time.Millisecond + time.Duration(w.rng.IntN(4000))*time.Microsecond\n\tif w.next < len(stalls) && start >= stalls[w.next].at {\n\t\td += stalls[w.next].dur\n\t\tw.next++\n\t}\n\treturn d\n}\n\n// iteration records when a loop body started and the tick it served.\ntype iteration struct{ start, sched time.Duration }\n\n// sleepLoop: work, then time.Sleep(period). The period becomes work+period.\nfunc sleepLoop() []iteration {\n\tw := newWorker()\n\tvar runs []iteration\n\tfor now := time.Duration(0); now < horizon; {\n\t\truns = append(runs, iteration{now, -1})\n\t\tnow += w.run(now)\n\t\tnow += period\n\t}\n\treturn runs\n}\n\n// tickerLoop models time.Ticker: ticks on a fixed grid, at most one tick\n// waits for a slow receiver, later ones are dropped.\nfunc tickerLoop() (runs []iteration, dropped int) {\n\tw := newWorker()\n\tvar now time.Duration\n\tfire := period\n\twaiting, value := false, time.Duration(0)\n\tfor {\n\t\tfor ; fire <= now; fire += period { // ticks that fired while we worked\n\t\t\tif waiting {\n\t\t\t\tdropped++\n\t\t\t} else {\n\t\t\t\twaiting, value = true, fire\n\t\t\t}\n\t\t}\n\t\tif !waiting { // block in <-ticker.C until the next tick\n\t\t\tnow, waiting, value = fire, true, fire\n\t\t\tfire += period\n\t\t}\n\t\tif now >= horizon {\n\t\t\treturn runs, dropped\n\t\t}\n\t\twaiting = false\n\t\truns = append(runs, iteration{now, value})\n\t\tnow += w.run(now)\n\t}\n}\n\n// catchUpLoop sleeps until next deadline, then deadline += period. It never\n// skips, so after a stall it runs late iterations back to back.\nfunc catchUpLoop() []iteration {\n\tw := newWorker()\n\tvar runs []iteration\n\tvar now time.Duration\n\tfor next := period; ; next += period {\n\t\tif now < next {\n\t\t\tnow = next\n\t\t}\n\t\tif now >= horizon {\n\t\t\treturn runs\n\t\t}\n\t\truns = append(runs, iteration{now, next})\n\t\tnow += w.run(now)\n\t}\n}\n\nfunc report(name string, runs []iteration, dropped string) {\n\thit := make([]bool, horizon/period)\n\tminGap, maxGap := time.Hour, time.Duration(0)\n\tstale, lag := 0, time.Duration(-1)\n\tfor i, r := range runs {\n\t\thit[r.start/period] = true\n\t\tif i > 0 {\n\t\t\tgap := r.start - runs[i-1].start\n\t\t\tminGap, maxGap = min(minGap, gap), max(maxGap, gap)\n\t\t}\n\t\tif r.sched >= 0 {\n\t\t\tlag = max(lag, r.start-r.sched)\n\t\t\tif r.start-r.sched > period {\n\t\t\t\tstale++\n\t\t\t}\n\t\t}\n\t}\n\tempty := 0\n\tfor _, h := range hit[1:] {\n\t\tif !h {\n\t\t\tempty++\n\t\t}\n\t}\n\tworst, staleRuns := \"-\", \"-\"\n\tif lag >= 0 {\n\t\tworst, staleRuns = ms(lag), strconv.Itoa(stale)\n\t}\n\tfmt.Printf(\"%-9s %4d %6d %8s %8s %8s %8s %6s\\n\", name, len(runs), empty, dropped, ms(minGap), ms(maxGap), worst, staleRuns)\n}\n\nfunc ms(d time.Duration) string { return strconv.FormatFloat(float64(d)/1e6, 'f', 1, 64) + \" ms\" }\n\n// ---- allocations in the loop body\n\ntype Command struct{ Vx, Vy, Vz, Yaw float64 }\n\ntype loopState struct {\n\twindow []float64 // last N altitude samples\n\thead   int\n\tcmd    *Command\n\tlast   Command\n\tnote   string\n\tbuf    []byte\n}\n\n// bodyAllocating copies the window, allocates a new command and formats a note\n// on every tick.\nfunc bodyAllocating(s *loopState, alt float64) {\n\tw := make([]float64, len(s.window))\n\tcopy(w, s.window[1:])\n\tw[len(w)-1] = alt\n\ts.window = w\n\ts.cmd = &Command{Vz: 0.8 * (10 - mean(w))}\n\ts.note = strconv.FormatFloat(s.cmd.Vz, 'f', 2, 64)\n}\n\n// bodyReusing writes into a ring buffer, stores the command by value and\n// appends the note into a buffer that keeps its capacity.\nfunc bodyReusing(s *loopState, alt float64) {\n\ts.window[s.head] = alt\n\ts.head = (s.head + 1) % len(s.window)\n\ts.last = Command{Vz: 0.8 * (10 - mean(s.window))}\n\ts.buf = strconv.AppendFloat(s.buf[:0], s.last.Vz, 'f', 2, 64)\n}\n\nfunc mean(xs []float64) float64 {\n\tsum := 0.0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn sum / float64(len(xs))\n}\n\nfunc main() {\n\tfmt.Printf(\"virtual clock: %v period (50 Hz) for %v, loop body 8-12 ms\\n\", period, horizon)\n\tfor _, s := range stalls {\n\t\tfmt.Printf(\"stall: %v %s at %v\\n\", s.dur, s.why, s.at)\n\t}\n\tfmt.Printf(\"%-9s %4s %6s %8s %8s %8s %8s %6s\\n\", \"loop\", \"runs\", \"empty\", \"dropped\", \"min gap\", \"max gap\", \"max lag\", \"stale\")\n\treport(\"sleep\", sleepLoop(), \"-\")\n\truns, dropped := tickerLoop()\n\treport(\"ticker\", runs, strconv.Itoa(dropped))\n\treport(\"catch-up\", catchUpLoop(), \"0\")\n\n\ts := &loopState{window: make([]float64, 25), buf: make([]byte, 0, 32)}\n\talt := 9.5\n\ta := testing.AllocsPerRun(1000, func() { bodyAllocating(s, alt) })\n\tb := testing.AllocsPerRun(1000, func() { bodyReusing(s, alt) })\n\tfmt.Printf(\"allocations per tick: allocating body %.0f, reusing body %.0f\\n\", a, b)\n\tfmt.Printf(\"at 50 Hz that is %.0f vs %.0f heap objects a minute\\n\", a*50*60, b*50*60)\n}","language":"go","title":"Three loops on a virtual clock","walkthrough":"The sleep loop manages only 63 runs instead of 99, leaving 37 empty slots: its period became the body plus 20 ms (the smallest gap is 28.1 ms). The ticker makes 94 runs and drops 5 ticks; its smallest gap is 18.3 ms, so it never bursts, and only 2 runs are stale, the late tick after each stall, the worse one 80.4 ms late. The catch-up loop makes 99 runs and drops nothing, but its smallest gap is 8.1 ms: after the stall it runs 6 stale iterations back to back on old data. The allocating loop body makes 3 heap allocations per tick, the reusing one 0, which at 50 Hz is 9000 objects a minute against none."},{"body":"Go's collector runs concurrently with the program. Its stop-the-world phases are short, usually well under a millisecond, but while a cycle runs the background marker uses about a quarter of GOMAXPROCS, and a goroutine that allocates may be drafted into mark assist. A loop body that does not allocate triggers fewer cycles and is not drafted. The allocating body above makes three objects: a slice made with a non-constant length, a *Command stored in a heap object, and the string from strconv.FormatFloat. The reusing body writes into a ring buffer, stores the command by value and appends into a byte slice that keeps its capacity. Find escapes with go build -gcflags=-m, pin the count with testing.AllocsPerRun in a test, and on small boards set GOMEMLIMIT (or debug.SetMemoryLimit) so the runtime collects before the operating system kills the process; GOGC trades memory for collection frequency.","title":"Garbage collection and the loop body"},{"body":"Rate and attitude loops run at hundreds of hertz to kilohertz with deadlines in microseconds, on real-time operating systems (NuttX under PX4, ChibiOS under ArduPilot on most boards) with fixed priorities and the IMU's interrupts driving them. A Go process on Linux shares the CPU with the kernel, other processes and the USB and Wi-Fi drivers; a few milliseconds of jitter are normal and occasional spikes of tens of milliseconds happen. That is acceptable for 10 to 50 Hz setpoints when the autopilot has its own timeout and failsafe, which PX4's offboard mode does. Log dt for every tick, keep a histogram, alert on overruns, and design the outer loop so that a missed tick costs accuracy, not safety.","title":"What stays in firmware"},{"body":"This program does not use the simulator: run it in any Go project, or create New project > Robotics and simulation > Drone flight and replace main.go with it (mission.go can stay), then Run and read the console. To connect it to a flight, call bodyReusing from the control function of sim.Run with d.State().Pos.Z: the simulator calls that function at exactly 50 Hz of simulated time, the ideal loop this lesson approximates, and Output replays the flight.","title":"Fly it in GopherForge"}],"takeaway":"Use time.Ticker for fixed-rate loops: its grid does not drift, and after a stall it delivers one late tick and drops the rest instead of bursting. Compute dt from the monotonic clock, keep the loop body free of allocations and prove it with AllocsPerRun, set GOMEMLIMIT on small boards, and leave kilohertz loops to firmware.","title":"Fixed-rate loops in Go: tickers, jitter, GC and allocations","unitID":"drones-control","wrongAnswers":["All of them are queued and delivered back to back","The ticker restarts its grid from the end of the stall"]},{"conceptTag":"drones.motor-mixing","designGuide":{"cautions":["Clipping per motor couples axes and can flip the vehicle.","Raising thrust at zero throttle (Airmode) can make it climb."],"cost":"A small matrix per airframe, a desaturation routine and ground tests with the propellers removed.","family":"drones","flow":["Roll/pitch spread fits?","Shrink yaw to fit","Shift thrust into 0..1","Check achieved torques"],"ratings":[],"strengths":["Explicit priorities keep the vehicle upright under saturation.","Inverting the mix shows what the motors actually produce."]},"hint":"Ask what happens to the vehicle if each one is lost: a slow heading drift, a small change of height, or a tilt it cannot correct.","id":"drones.motor-mixing","introduction":"Below the rate controller sits the mixer, which PX4 calls control allocation. It knows where each rotor is and which way it spins, and turns four numbers, thrust and three torques, into four motor commands. That is a matrix multiplication until a motor reaches 0 or 1. Then something has to give, and what gives decides whether the vehicle keeps its attitude or rolls over. This lesson writes the mixer, the naive clip and a desaturation with explicit priorities.","nuance":"Clipping each motor separately is the worst option: in the program's last case it cut roll to +0.20 and added a pitch of +0.10 nobody asked for, coupling the axes.","objective":"Map collective thrust and roll, pitch and yaw torque commands to four motor outputs with PX4's Quadrotor X numbering and spin directions, and handle saturation by giving up thrust and yaw before roll and pitch.","question":"A quad X mixer cannot fit a command into 0..1 on every motor. In what order should a desaturating mixer give things up?","references":["https://docs.px4.io/main/en/concept/control_allocation.html","https://docs.px4.io/main/en/config_mc/pid_tuning_guide_multicopter.html","https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d/airframes/4001_quad_x","https://ardupilot.org/copter/docs/connect-escs-and-motors.html"],"reviewAnswer":"Yaw, then collective thrust; keep roll and pitch","reviewPrompt":"Mixer saturates: what goes first?","sections":[{"body":"In PX4's Quadrotor X, motor 1 is front right and spins counter-clockwise, motor 2 rear left counter-clockwise, motor 3 front left clockwise and motor 4 rear right clockwise; ArduPilot's Quad X uses the same order. Using the FRD body frame, a positive roll lowers the right side, so it needs more thrust on the left motors 2 and 3; a positive pitch raises the nose, so it needs more thrust on the front motors 1 and 3. Yaw comes from rotor drag torque: a counter-clockwise propeller twists the body clockwise, so yawing right (clockwise seen from above) speeds up motors 1 and 2 and slows 3 and 4. Each output is thrust plus signed shares of the three torques. PX4 builds that matrix from rotor positions and moment coefficients (CA_ROTORn_PX, CA_ROTORn_PY, and CA_ROTORn_KM, positive for counter-clockwise) and uses its pseudo-inverse. The default KM of 0.05 shows why yaw authority is weak: drag torque is small compared with thrust.","title":"Geometry and spin directions"},{"body":"The program prints the motor table, then mixes seven commands. Thrust is 0..1 and the torques are normalised so that a roll command of 0.1 moves the motors by 0.1. Commands that fit go straight through. For saturated ones the program prints two results: every motor clipped to 0..1 separately, and the desaturated mix. Each line ends with the command the four outputs actually produce, computed by inverting the mix, which is how you see what saturation cost.","code":"package main\n\n// Quad X motor mixing: collective thrust and roll, pitch and yaw torque\n// commands become four motor outputs in 0..1. Saturated cases are shown\n// clipped naively and desaturated with attitude before yaw before thrust.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// Command is what the attitude and rate controllers ask for. Thrust is\n// 0..1; roll, pitch and yaw are normalised torques (FRD body frame:\n// positive roll = right side down, pitch = nose up, yaw = nose right).\ntype Command struct{ Thrust, Roll, Pitch, Yaw float64 }\n\n// Motor is one rotor's share of each torque.\ntype Motor struct {\n\tName             string\n\tRoll, Pitch, Yaw float64\n}\n\n// QuadX uses PX4's numbering for the Quadrotor X airframe.\nvar QuadX = [4]Motor{\n\t{\"1 front right, CCW\", -1, +1, +1},\n\t{\"2 rear left, CCW\", +1, -1, +1},\n\t{\"3 front left, CW\", +1, +1, -1},\n\t{\"4 rear right, CW\", -1, -1, -1},\n}\n\ntype Outputs [4]float64\n\nfunc torques(c Command, yawScale float64) Outputs {\n\tvar a Outputs\n\tfor i, m := range QuadX {\n\t\ta[i] = c.Roll*m.Roll + c.Pitch*m.Pitch + c.Yaw*yawScale*m.Yaw\n\t}\n\treturn a\n}\n\nfunc spread(a Outputs) (lo, hi float64) {\n\tlo, hi = a[0], a[0]\n\tfor _, v := range a[1:] {\n\t\tlo, hi = math.Min(lo, v), math.Max(hi, v)\n\t}\n\treturn lo, hi\n}\n\n// Clipped adds thrust and clamps each motor: the simple, wrong way.\nfunc Clipped(c Command) Outputs {\n\ta := torques(c, 1)\n\tfor i := range a {\n\t\ta[i] = clamp(c.Thrust+a[i], 0, 1)\n\t}\n\treturn a\n}\n\n// Desaturated keeps roll and pitch if at all possible, gives up yaw next\n// and moves collective thrust last.\nfunc Desaturated(c Command) Outputs {\n\tif lo, hi := spread(torques(Command{Roll: c.Roll, Pitch: c.Pitch}, 0)); hi-lo > 1 {\n\t\tk := 1 / (hi - lo) // even roll and pitch alone do not fit: scale them\n\t\tc = Command{Thrust: c.Thrust, Roll: c.Roll * k, Pitch: c.Pitch * k}\n\t}\n\tyawScale := 1.0\n\tif lo, hi := spread(torques(c, 1)); hi-lo > 1 {\n\t\tlow, high := 0.0, 1.0 // largest yaw share that still fits\n\t\tfor range 40 {\n\t\t\tmid := (low + high) / 2\n\t\t\tif lo, hi := spread(torques(c, mid)); hi-lo <= 1 {\n\t\t\t\tlow = mid\n\t\t\t} else {\n\t\t\t\thigh = mid\n\t\t\t}\n\t\t}\n\t\tyawScale = low\n\t}\n\ta := torques(c, yawScale)\n\tlo, hi := spread(a)\n\tthrust := clamp(c.Thrust, -lo, 1-hi) // shift everything into 0..1\n\tfor i := range a {\n\t\ta[i] = clamp(thrust+a[i], 0, 1)\n\t}\n\treturn a\n}\n\n// Achieved inverts the mixer: what the four outputs really produce.\nfunc Achieved(o Outputs) Command {\n\tvar c Command\n\tfor i, m := range QuadX {\n\t\tc.Thrust += o[i] / 4\n\t\tc.Roll += o[i] * m.Roll / 4\n\t\tc.Pitch += o[i] * m.Pitch / 4\n\t\tc.Yaw += o[i] * m.Yaw / 4\n\t}\n\treturn c\n}\n\nfunc (c Command) String() string {\n\treturn fmt.Sprintf(\"T %.2f R %+.2f P %+.2f Y %+.2f\", r2(c.Thrust), r2(c.Roll), r2(c.Pitch), r2(c.Yaw))\n}\n\n// r2 rounds to 0.01 and turns -0 into 0 so the bisection's last bits\n// do not print as -0.00.\nfunc r2(v float64) float64 { return math.Round(v*100)/100 + 0 }\n\nfunc (o Outputs) String() string {\n\treturn fmt.Sprintf(\"%.2f %.2f %.2f %.2f\", o[0], o[1], o[2], o[3])\n}\n\nfunc saturated(c Command) bool {\n\tlo, hi := spread(torques(c, 1))\n\treturn c.Thrust+lo < 0 || c.Thrust+hi > 1\n}\n\nfunc main() {\n\tfmt.Println(\"motors (PX4 Quadrotor X):\")\n\tfor _, m := range QuadX {\n\t\tfmt.Printf(\"  %-19s roll %+.0f pitch %+.0f yaw %+.0f\\n\", m.Name, m.Roll, m.Pitch, m.Yaw)\n\t}\n\tcases := []struct {\n\t\tname string\n\t\tcmd  Command\n\t}{\n\t\t{\"hover\", Command{Thrust: 0.5}},\n\t\t{\"roll right\", Command{Thrust: 0.5, Roll: 0.1}},\n\t\t{\"pitch down, yaw right\", Command{Thrust: 0.55, Pitch: -0.1, Yaw: 0.05}},\n\t\t{\"full throttle + roll\", Command{Thrust: 0.95, Roll: 0.2}},\n\t\t{\"idle + roll\", Command{Thrust: 0.05, Roll: 0.2}},\n\t\t{\"hard yaw at hover\", Command{Thrust: 0.5, Yaw: 0.6}},\n\t\t{\"climb, roll and yaw\", Command{Thrust: 0.8, Roll: 0.3, Yaw: 0.3}},\n\t}\n\tfor _, tc := range cases {\n\t\tfmt.Printf(\"%-22s asks %v\\n\", tc.name, tc.cmd)\n\t\tif !saturated(tc.cmd) {\n\t\t\to := Desaturated(tc.cmd)\n\t\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"mixed\", o, Achieved(o))\n\t\t\tcontinue\n\t\t}\n\t\to := Clipped(tc.cmd)\n\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"clipped\", o, Achieved(o))\n\t\to = Desaturated(tc.cmd)\n\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"desaturated\", o, Achieved(o))\n\t}\n}\n\nfunc clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }","language":"go","title":"Seven commands through the mixer","walkthrough":"Roll right gives 0.40 0.60 0.60 0.40, and pitch down with a little yaw gives 0.50 0.70 0.40 0.60; both achieve exactly what was asked. At full throttle with roll, clipping yields 0.75 1.00 1.00 0.75, which achieves only R +0.13 at T 0.88; desaturation lowers thrust to 0.80 and keeps R +0.20. At idle with roll, clipping again cuts the roll to +0.13, while desaturation raises thrust to 0.20 and keeps it. Hard yaw is limited to Y +0.50 either way. In the last case clipping produces P +0.10 that nobody asked for and only R +0.20; desaturation keeps R +0.30 and P +0.00 and gives up yaw (+0.20) and thrust (0.50)."},{"body":"The desaturating mixer applies the priorities in order. Roll and pitch come first: losing them means a tilt the vehicle cannot correct. If even they do not fit into the 0..1 range, they are scaled down together, which keeps the direction of the correction. Yaw comes next: the program finds the largest share of the yaw command that still fits, since losing yaw only lets the heading drift. Thrust comes last: the collective is moved to the nearest value at which every motor lies in 0..1. PX4 offers both behaviours through CA_METHOD (pseudo-inverse with output clipping, or with sequential desaturation). At the top it reduces thrust. At the bottom, with Airmode off it reduces the torque instead, so at zero throttle no attitude correction is possible; with MC_AIRMODE it raises thrust, as the idle case above does, which keeps control at zero throttle but can make a badly tuned vehicle climb after the throttle is cut.","code":"a := torques(c, yawScale)            // roll, pitch and yaw share per motor\nlo, hi := spread(a)                  // their range now fits in 1\nthrust := clamp(c.Thrust, -lo, 1-hi) // nearest thrust that fits\nfor i := range a {\n\ta[i] = clamp(thrust+a[i], 0, 1)\n}","language":"go","title":"Desaturation and its priorities","walkthrough":"After roll, pitch and yaw have been made to fit, the lowest motor needs thrust of at least -lo and the highest at most 1 - hi. Clamping the requested thrust into that interval moves all four outputs by the same amount, so the torques are untouched and only the collective changes."},{"body":"Outputs in 0..1 reach the ESCs as PWM pulses, OneShot or DShot. Thrust grows roughly with the square of rotor speed, so equal steps in output are not equal steps in thrust; PX4 compensates with a thrust model parameter (THR_MDL_FAC). A minimum output keeps motors spinning in flight, and battery sag lowers the maximum thrust, so a vehicle saturates more often late in a flight. Go meets mixing outside the firmware: in simulators, in log analysis that recomputes achieved torques from recorded motor outputs to find saturation, and in tools for new frame geometries. Test motor order and direction on the ground with the propellers removed.","title":"From normalised outputs to motors"},{"body":"The simulator models the airframe as a point mass whose thrust tilts, without attitude dynamics or individual motors, so there is nothing to mix and this program does not use it. Run it in any project, or create New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay) and Run to read the table in the console. To connect it to a flight, call Desaturated(Command{Thrust: u}) with the thrust a SetThrust loop computes and add a roll command, then count how often a hard climb saturates the motors.","title":"Fly it in GopherForge"}],"takeaway":"A quad X mixer adds thrust and signed roll, pitch and yaw shares per motor, with signs set by rotor position and spin direction. When outputs saturate, never clip motors one by one: keep roll and pitch, cut yaw, then shift the collective, and check what the outputs achieve by inverting the mix.","title":"Motor mixing for a quad X: thrust and torques to four motors","unitID":"drones-control","wrongAnswers":["Roll and pitch first, since thrust keeps it in the air","Clip each motor to 0..1 and accept the result"]},{"conceptTag":"drones.flight-modes","designGuide":{"cautions":["The autopilot can change mode itself; reconcile, do not fight.","Guards that read clocks or I/O make the machine hard to test."],"cost":"A table, a few pure guard functions and a monitor that turns telemetry into events.","family":"drones","flow":["Snapshot vehicle state","Match row, run guard","Command, then commit","Log transition or reason"],"ratings":[],"strengths":["Every allowed path is in one table you can review and test.","Refusals carry reasons the operator can act on."]},"hint":"A table lists every allowed path. What does that imply for an event with no matching row, and what should the operator see?","id":"drones.flight-modes","introduction":"Ground stations and companion computers tend to grow their flight-mode logic one if statement at a time, until nobody can say whether a go-to is allowed while the vehicle returns home. Writing it as a table of transitions with guards makes every allowed path visible, every refusal explainable and the whole logic testable without a vehicle. The autopilot keeps its own modes and checks; this machine decides what your program will ask of it.","nuance":"Rejections matter as much as transitions in the log: they explain why the drone did not move. Guards add reasons to rows that exist; a missing row means the request is never valid in that state.","objective":"Model flight modes as states, events and guarded transitions in a table, reject invalid requests with reasons, run pre-arm checks for battery, GPS fix and geofence, map the states onto the simulator's modes and log every transition.","question":"A ground station's state machine receives goto while in DISARMED, and no row of its transition table matches. What should happen?","references":["https://docs.px4.io/main/en/flight_modes_mc/","https://docs.px4.io/main/en/flying/pre_flight_checks.html","https://ardupilot.org/copter/docs/flight-modes.html","https://mavlink.io/en/messages/common.html"],"reviewAnswer":"Rejected with a reason; the state stays the same","reviewPrompt":"Request not in the table?","sections":[{"body":"The machine has seven states: DISARMED, ARMED, TAKEOFF, HOLD, MISSION, RTL and LAND. Events come from three places: requests from an operator or mission (arm, takeoff, goto, hold, rtl, land, disarm), reports from the vehicle (reached, touchdown) and the program's own monitor (battery low). Each row of the table names a state, an event, the next state and an optional guard. Guards are pure functions of a snapshot of the vehicle and the request: preArm needs at least 40% battery, at least 6 GPS satellites and a position inside the geofence; take-off and go-to altitudes must lie between 2 m and the 60 m ceiling; a go-to target must be inside the fence and the battery well above the 30% reserve. An event without a matching row is rejected. preArm reports every failing check at once with errors.Join, so the operator can fix all of them before the next attempt instead of discovering them one by one.","title":"States, events and guards"},{"body":"The program first runs nine table-driven cases against fresh machines, without any vehicle. Then it flies: the GPS model gains satellites over the first seconds, the program requests arm, take-off, go-tos inside and outside the fence and a disarm in flight, and a monitor turns the simulator's reports into reached events (d.Arrived()) and touchdown events and raises battery low at the 30% reserve. The simulator starts with 45% battery, so after the second leg the program only waits in HOLD until the monitor's reserve check sends the drone home. Each transition is printed with the simulated time and marked on the replay.","code":"package main\n\n// Flight modes as an explicit state machine: a transition table with\n// guards, rejected requests with reasons, and a logged run that drives the\n// simulator only through the machine's decisions.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\ntype State int\n\nconst (\n\tDisarmed State = iota\n\tArmed\n\tTakingOff\n\tHolding\n\tMission\n\tReturning\n\tLanding\n)\n\nvar stateNames = [...]string{\"DISARMED\", \"ARMED\", \"TAKEOFF\", \"HOLD\", \"MISSION\", \"RTL\", \"LAND\"}\n\nfunc (s State) String() string { return stateNames[s] }\n\ntype Event int\n\nconst (\n\tArm Event = iota\n\tDisarm\n\tTakeOff\n\tGoTo\n\tHold\n\tReturnHome\n\tLand\n\tReached    // from the vehicle: take-off altitude or waypoint reached\n\tTouchdown  // from the vehicle: on the ground and disarmed\n\tBatteryLow // from our own monitor\n)\n\nvar eventNames = [...]string{\"arm\", \"disarm\", \"takeoff\", \"goto\", \"hold\", \"rtl\", \"land\", \"reached\", \"touchdown\", \"battery low\"}\n\nfunc (e Event) String() string { return eventNames[e] }\n\n// Snapshot is what guards may look at.\ntype Snapshot struct {\n\tBattery float64 // percent\n\tSats    int     // GPS satellites used in the fix\n\tPos     drone.Vec3\n}\n\n// Request is an event with its argument.\ntype Request struct {\n\tEvent  Event\n\tTarget drone.Vec3 // take-off altitude in Z, or the go-to point\n}\n\nfunc (r Request) String() string {\n\tswitch r.Event {\n\tcase TakeOff:\n\t\treturn fmt.Sprintf(\"takeoff %.0f m\", r.Target.Z)\n\tcase GoTo:\n\t\treturn \"goto \" + r.Target.String()\n\t}\n\treturn r.Event.String()\n}\n\n// Rules are the limits the guards enforce.\ntype Rules struct {\n\tMinArmBattery float64\n\tReserve       float64 // below this, return home\n\tMinSats       int\n\tFence         []drone.Vec3\n\tCeiling       float64\n}\n\ntype Guard func(Rules, Snapshot, Request) error\n\ntype Transition struct {\n\tFrom  State\n\tEvent Event\n\tTo    State\n\tGuard Guard\n}\n\n// preArm reports every failing check at once, as a ground station should.\nfunc preArm(r Rules, s Snapshot, _ Request) error {\n\tvar errs []error\n\tif s.Battery < r.MinArmBattery {\n\t\terrs = append(errs, fmt.Errorf(\"battery %.0f%% < %.0f%%\", s.Battery, r.MinArmBattery))\n\t}\n\tif s.Sats < r.MinSats {\n\t\terrs = append(errs, fmt.Errorf(\"GPS %d satellites < %d\", s.Sats, r.MinSats))\n\t}\n\tif !drone.Inside(r.Fence, s.Pos) {\n\t\terrs = append(errs, errors.New(\"outside geofence\"))\n\t}\n\treturn errors.Join(errs...)\n}\n\nfunc altitudeOK(r Rules, _ Snapshot, q Request) error {\n\tif q.Target.Z <= 2 || q.Target.Z > r.Ceiling {\n\t\treturn fmt.Errorf(\"altitude %.0f m outside 2..%.0f m\", q.Target.Z, r.Ceiling)\n\t}\n\treturn nil\n}\n\nfunc targetOK(r Rules, s Snapshot, q Request) error {\n\tif !drone.Inside(r.Fence, q.Target) {\n\t\treturn fmt.Errorf(\"target %v outside geofence\", q.Target)\n\t}\n\tif s.Battery < r.Reserve+5 {\n\t\treturn fmt.Errorf(\"battery %.0f%% too close to reserve\", s.Battery)\n\t}\n\treturn altitudeOK(r, s, q)\n}\n\nvar table = []Transition{\n\t{Disarmed, Arm, Armed, preArm},\n\t{Armed, Disarm, Disarmed, nil},\n\t{Armed, TakeOff, TakingOff, altitudeOK},\n\t{TakingOff, Reached, Holding, nil},\n\t{Holding, GoTo, Mission, targetOK},\n\t{Mission, GoTo, Mission, targetOK},\n\t{Mission, Reached, Holding, nil},\n\t{Mission, Hold, Holding, nil},\n\t{Returning, Hold, Holding, nil},\n\t{TakingOff, ReturnHome, Returning, nil},\n\t{Holding, ReturnHome, Returning, nil},\n\t{Mission, ReturnHome, Returning, nil},\n\t{TakingOff, BatteryLow, Returning, nil},\n\t{Holding, BatteryLow, Returning, nil},\n\t{Mission, BatteryLow, Returning, nil},\n\t{Holding, Land, Landing, nil},\n\t{Mission, Land, Landing, nil},\n\t{Returning, Land, Landing, nil},\n\t{Returning, Touchdown, Disarmed, nil},\n\t{Landing, Touchdown, Disarmed, nil},\n}\n\n// Machine holds the current state. Fire finds the transition, checks its\n// guard, lets act command the vehicle and commits only if act succeeds.\ntype Machine struct {\n\tState State\n\tRules Rules\n\tLog   func(from, to State, r Request)\n}\n\nfunc (m *Machine) Fire(s Snapshot, r Request, act func(Request) error) error {\n\tfor _, tr := range table {\n\t\tif tr.From != m.State || tr.Event != r.Event {\n\t\t\tcontinue\n\t\t}\n\t\tif tr.Guard != nil {\n\t\t\tif err := tr.Guard(m.Rules, s, r); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v in %v rejected: %s\", r, m.State, strings.ReplaceAll(err.Error(), \"\\n\", \"; \"))\n\t\t\t}\n\t\t}\n\t\tif act != nil {\n\t\t\tif err := act(r); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v in %v: vehicle refused: %w\", r, m.State, err)\n\t\t\t}\n\t\t}\n\t\tfrom := m.State\n\t\tm.State = tr.To\n\t\tif m.Log != nil {\n\t\t\tm.Log(from, m.State, r)\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%v not allowed in %v\", r, m.State)\n}\n\nfunc main() {\n\tfence := []drone.Vec3{{X: -100, Y: -100}, {X: 100, Y: -100}, {X: 100, Y: 100}, {X: -100, Y: 100}}\n\trules := Rules{MinArmBattery: 40, Reserve: 30, MinSats: 6, Fence: fence, Ceiling: 60}\n\n\tfmt.Println(\"table-driven checks:\")\n\tgood := Snapshot{Battery: 90, Sats: 12}\n\tcases := []struct {\n\t\tfrom State\n\t\tsnap Snapshot\n\t\treq  Request\n\t}{\n\t\t{Disarmed, good, Request{Event: Arm}},\n\t\t{Disarmed, Snapshot{Battery: 35, Sats: 4, Pos: drone.Vec3{X: 140}}, Request{Event: Arm}},\n\t\t{Armed, good, Request{TakeOff, drone.Vec3{Z: 80}}},\n\t\t{Holding, good, Request{GoTo, drone.Vec3{X: 150, Z: 20}}},\n\t\t{Holding, Snapshot{Battery: 33, Sats: 12}, Request{GoTo, drone.Vec3{X: 50, Z: 20}}},\n\t\t{Mission, good, Request{Event: Disarm}},\n\t\t{Disarmed, good, Request{GoTo, drone.Vec3{X: 10, Z: 10}}},\n\t\t{Mission, good, Request{Event: BatteryLow}},\n\t\t{Returning, good, Request{Event: Hold}},\n\t}\n\tfor _, c := range cases {\n\t\tm := &Machine{State: c.from, Rules: rules}\n\t\tif err := m.Fire(c.snap, c.req, nil); err != nil {\n\t\t\tfmt.Println(\"  no: \", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"  ok:  %v + %v -> %v\\n\", c.from, c.req, m.State)\n\t\t}\n\t}\n\n\tsim := drone.New(drone.Config{Geofence: fence, Ceiling: rules.Ceiling, Battery: 45, Seed: 7})\n\td := sim.Drone()\n\tsnapshot := func() Snapshot {\n\t\tst := d.State()\n\t\tsats := min(int(sim.Time()*1.5), 14) // the receiver needs a few seconds for a fix\n\t\treturn Snapshot{Battery: st.Battery, Sats: sats, Pos: st.Pos}\n\t}\n\tm := &Machine{State: Disarmed, Rules: rules}\n\tm.Log = func(from, to State, r Request) {\n\t\tline := fmt.Sprintf(\"%v -> %v (%v)\", from, to, r)\n\t\tfmt.Printf(\"  %5.1f s  %s\\n\", sim.Time(), line)\n\t\tsim.Mark(line)\n\t}\n\tact := func(r Request) error {\n\t\tswitch r.Event {\n\t\tcase Arm:\n\t\t\treturn d.Arm()\n\t\tcase TakeOff:\n\t\t\treturn d.TakeOff(r.Target.Z)\n\t\tcase GoTo:\n\t\t\treturn d.GoTo(r.Target)\n\t\tcase Hold:\n\t\t\treturn d.Hold()\n\t\tcase ReturnHome, BatteryLow:\n\t\t\treturn d.ReturnHome()\n\t\tcase Land:\n\t\t\treturn d.Land()\n\t\t}\n\t\treturn nil // disarm on the ground, reached, touchdown: nothing to command\n\t}\n\trequest := func(r Request) {\n\t\tif err := m.Fire(snapshot(), r, act); err != nil {\n\t\t\tfmt.Printf(\"  %5.1f s  no: %v\\n\", sim.Time(), err)\n\t\t}\n\t}\n\t// monitor turns what the vehicle reports into events, once per step.\n\tmonitor := func(float64) {\n\t\tst, s := d.State(), m.State\n\t\tswitch {\n\t\tcase (s == TakingOff || s == Mission) && d.Arrived():\n\t\t\tm.Fire(snapshot(), Request{Event: Reached}, nil)\n\t\tcase (s == Returning || s == Landing) && st.Landed:\n\t\t\tm.Fire(snapshot(), Request{Event: Touchdown}, nil)\n\t\tcase (s == TakingOff || s == Holding || s == Mission) && st.Battery <= rules.Reserve:\n\t\t\trequest(Request{Event: BatteryLow})\n\t\t}\n\t}\n\tsettle := func(want State, limit float64) {\n\t\tsim.RunUntil(limit, func(t float64) bool { monitor(t); return m.State == want || m.State == Returning })\n\t}\n\n\tfmt.Println(\"flight:\")\n\trequest(Request{Event: Arm})\n\tsim.Run(5, nil)\n\trequest(Request{Event: Arm})\n\trequest(Request{TakeOff, drone.Vec3{Z: 80}})\n\trequest(Request{TakeOff, drone.Vec3{Z: 20}})\n\tsettle(Holding, 30)\n\trequest(Request{GoTo, drone.Vec3{X: 150, Z: 20}})\n\trequest(Request{Event: Disarm})\n\trequest(Request{GoTo, drone.Vec3{X: 80, Y: 60, Z: 30}})\n\tsettle(Holding, 60)\n\trequest(Request{GoTo, drone.Vec3{X: -70, Y: 80, Z: 30}})\n\tsettle(Holding, 90)\n\tsim.RunUntil(120, func(t float64) bool { monitor(t); return m.State == Disarmed })\n\tfmt.Printf(\"machine %v, simulator %v\\n\", m.State, d.State().Mode)\n\tsim.Save()\n}","language":"go","title":"The table, tested and flown","walkthrough":"The checks show one valid arm, an arm rejected for three reasons at once (battery 35% < 40%; GPS 4 satellites < 6; outside geofence), a take-off to 80 m outside 2..60 m, a target outside the fence, a go-to refused at 33% battery, disarm not allowed in MISSION and goto not allowed in DISARMED. In flight, arming at 0.0 s fails with GPS 0 satellites < 6 and succeeds at 5.0 s; the take-off reaches HOLD at 13.3 s; the go-to outside the fence and the disarm are refused; the legs end at 23.9 s and 38.8 s; battery low switches HOLD to RTL at 58.0 s; touchdown at 86.5 s ends in DISARMED while the simulator reports LANDED, with 23% battery left."},{"body":"Fire finds the row, checks the guard, lets the act function command the vehicle and changes state only if the command was accepted; if the autopilot refuses, the machine stays where it was and the error explains why. The vehicle can also change mode by itself: geofence breach, low battery and lost link failsafes all act inside the autopilot. A machine that ignores them believes it is flying a mission while the vehicle returns home. So translate the vehicle's reported mode (a MAVLink HEARTBEAT's custom mode, or State().Mode here) into the machine's terms and, when the two disagree, let the vehicle win and log the reconciliation. The reason arrives separately, as STATUSTEXT messages over MAVLink; in the simulator, sim.Events() returns the autopilot's notes, such as battery 20%: return to home.","code":"// fromVehicle maps the simulator's mode onto the machine's states, for\n// reconciling after the autopilot changed mode on its own.\nfunc fromVehicle(m drone.Mode) (State, bool) {\n\tswitch m {\n\tcase drone.Idle, drone.Landed:\n\t\treturn Disarmed, true\n\tcase drone.Armed:\n\t\treturn Armed, true\n\tcase drone.TakingOff:\n\t\treturn TakingOff, true\n\tcase drone.Hold:\n\t\treturn Holding, true\n\tcase drone.GoingTo:\n\t\treturn Mission, true\n\tcase drone.Returning:\n\t\treturn Returning, true\n\tcase drone.Landing:\n\t\treturn Landing, true\n\t}\n\treturn 0, false // Velocity, Manual, Crashed: outside this machine\n}","language":"go","title":"Command the vehicle, then commit","walkthrough":"Every simulator mode that the machine knows maps to exactly one state. The modes it does not model, offboard velocity, manual thrust and a crash, return false, which the program should treat as leaving the machine's authority and report rather than guess."},{"body":"Log every transition with the time, the old and new state and the cause, and log every rejection too: rejections explain why a drone did not move. In the simulator, sim.Mark puts each line on the replay's timeline. The table-driven cases are unit tests as they stand; the table also supports structural tests, such as a graph search proving that every airborne state can reach RTL and LAND and that nothing leaves DISARMED except arm. Keep clocks and I/O out of guards so that a test can build any snapshot. Over MAVLink, arming is MAV_CMD_COMPONENT_ARM_DISARM and mode changes are MAV_CMD_DO_SET_MODE; the COMMAND_ACK the autopilot returns is where act gets its error, and the autopilot's own pre-arm checks still apply.","title":"Logging and testing transitions"},{"body":"Use New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay) and Run. The console prints the checks and the transition log; Output replays the flight with the square geofence, the waypoints and a timeline mark for every transition: the take-off, the first leg, the battery-low return and the landing. Change the battery in drone.Config, the rules or the requests and watch which transitions are refused.","title":"Fly it in GopherForge"}],"takeaway":"Write flight modes as a transition table with pure guards: the allowed paths are visible, every refusal carries a reason and the logic is testable without a vehicle. Command the vehicle before committing a transition, and treat modes the autopilot reports, especially failsafes, as events that win.","title":"Flight modes as an explicit state machine","unitID":"drones-control","wrongAnswers":["Arm automatically, then fly to the target","Ignore it silently and keep no record"]},{"conceptTag":"drones.waypoint-missions","designGuide":{"cautions":["Uploads may not be atomic; verify the stored plan before arming.","Acceptance radius trades corner cutting against slow arrivals."],"cost":"A mission builder, an uploader with timeouts and retries, and a download-and-compare check before every flight.","family":"drones","flow":["Generate mission items","Upload on request","Verify plan on board","Fly and track progress"],"ratings":[],"strengths":["Lost messages are repaired by re-requesting one sequence number.","A generated survey covers the area with a known overlap."]},"hint":"Think about how a lost item gets repaired: whoever asks for items by number can simply ask again.","id":"drones.waypoint-missions","introduction":"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.","nuance":"The ground station sends only MISSION_COUNT unprompted; the vehicle then pulls items by sequence number, so a loss is fixed by asking again. MISSION_ACK comes once, at the end, with the result.","objective":"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.","question":"In a MAVLink mission upload, which side asks for each item, and how?","references":["https://mavlink.io/en/services/mission.html","https://mavlink.io/en/messages/common.html#MAV_CMD_NAV_WAYPOINT","https://ardupilot.org/copter/docs/mission-command-list.html","https://docs.px4.io/main/en/flying/missions.html"],"reviewAnswer":"The vehicle, with MISSION_REQUEST_INT per seq","reviewPrompt":"Who asks for each mission item?","sections":[{"body":"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.","title":"Mission items and when they count as done"},{"body":"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.","code":"func Upload(ctx context.Context, link Link, items []Item) error {\n\tlast := Message(MissionCount{Count: uint16(len(items))})\n\tfor retries := 0; retries <= 5; {\n\t\tif err := link.Send(last); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Receive returns only mission messages from this vehicle.\n\t\tmsg, err := link.Receive(ctx, 1500*time.Millisecond)\n\t\tswitch m := msg.(type) {\n\t\tcase MissionRequestInt:\n\t\t\tif int(m.Seq) >= len(items) {\n\t\t\t\treturn fmt.Errorf(\"vehicle asked for item %d of %d\", m.Seq, len(items))\n\t\t\t}\n\t\t\tlast, retries = items[m.Seq].Encode(m.Seq), 0\n\t\tcase MissionAck:\n\t\t\tif m.Type != MavMissionAccepted {\n\t\t\t\treturn fmt.Errorf(\"upload rejected: %v\", m.Type)\n\t\t\t}\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif !errors.Is(err, ErrTimeout) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tretries++ // silence: send the same message again\n\t\t}\n\t}\n\treturn errors.New(\"mission upload: no answer after 5 retries\")\n}","language":"go","title":"Moving a mission over a lossy link","walkthrough":"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."},{"body":"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.","title":"Idempotent uploads and stale plans"},{"body":"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.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Command is the MAV_CMD_NAV_* number a MAVLink mission item carries.\ntype Command int\n\nconst (\n\tCmdWaypoint   Command = 16 // MAV_CMD_NAV_WAYPOINT\n\tCmdLoiterTime Command = 19 // MAV_CMD_NAV_LOITER_TIME\n\tCmdRTL        Command = 20 // MAV_CMD_NAV_RETURN_TO_LAUNCH\n\tCmdLand       Command = 21 // MAV_CMD_NAV_LAND\n\tCmdTakeoff    Command = 22 // MAV_CMD_NAV_TAKEOFF\n)\n\nfunc (c Command) String() string {\n\tswitch c {\n\tcase CmdWaypoint:\n\t\treturn \"WAYPOINT\"\n\tcase CmdLoiterTime:\n\t\treturn \"LOITER_TIME\"\n\tcase CmdRTL:\n\t\treturn \"RTL\"\n\tcase CmdLand:\n\t\treturn \"LAND\"\n\tcase CmdTakeoff:\n\t\treturn \"TAKEOFF\"\n\t}\n\treturn fmt.Sprintf(\"CMD_%d\", int(c))\n}\n\n// Item is one mission item: what to do, where, and when it counts as done.\ntype Item struct {\n\tSeq    int\n\tCmd    Command\n\tPos    drone.Vec3\n\tAccept float64 // acceptance radius, m\n\tHold   float64 // seconds to stay at the point\n}\n\n// Footprint is the width of ground a camera sees across track.\nfunc Footprint(alt, hfovDeg float64) float64 { return 2 * alt * math.Tan(hfovDeg/2*math.Pi/180) }\n\n// Lawnmower covers the rectangle x0..x1, y0..y1 with legs parallel to X,\n// alternating direction. The spacing is at most maxSpacing, reduced so the\n// legs divide the area evenly and the last one lies on the far edge.\nfunc Lawnmower(x0, y0, x1, y1, alt, maxSpacing float64) (pts []drone.Vec3, spacing float64) {\n\tlegs := int(math.Ceil((y1-y0)/maxSpacing)) + 1\n\tspacing = (y1 - y0) / float64(legs-1)\n\tfor i := 0; i < legs; i++ {\n\t\ty := y0 + float64(i)*spacing\n\t\ta, b := x0, x1\n\t\tif i%2 == 1 {\n\t\t\ta, b = x1, x0\n\t\t}\n\t\tpts = append(pts, drone.Vec3{X: a, Y: y, Z: alt}, drone.Vec3{X: b, Y: y, Z: alt})\n\t}\n\treturn pts, spacing\n}\n\n// BuildMission turns survey points into a numbered mission.\nfunc BuildMission(alt float64, survey []drone.Vec3) []Item {\n\titems := []Item{{Cmd: CmdTakeoff, Pos: drone.Vec3{Z: alt}}}\n\tfor _, p := range survey {\n\t\titems = append(items, Item{Cmd: CmdWaypoint, Pos: p, Accept: 2})\n\t}\n\tcentre := drone.Vec3{X: 0, Y: 30, Z: alt}\n\titems = append(items, Item{Cmd: CmdLoiterTime, Pos: centre, Accept: 1, Hold: 5})\n\titems = append(items, Item{Cmd: CmdRTL})\n\tfor i := range items {\n\t\titems[i].Seq = i\n\t}\n\treturn items\n}\n\n// Execute flies one item and reports whether it completed in time.\nfunc Execute(sim *drone.Sim, d *drone.Drone, it Item) error {\n\tvar err error\n\tswitch it.Cmd {\n\tcase CmdTakeoff:\n\t\tif err = d.Arm(); err == nil {\n\t\t\terr = d.TakeOff(it.Pos.Z)\n\t\t}\n\t\tif err == nil && !sim.RunUntil(60, func(float64) bool { return d.State().Mode == drone.Hold }) {\n\t\t\terr = fmt.Errorf(\"take-off timed out\")\n\t\t}\n\tcase CmdWaypoint, CmdLoiterTime:\n\t\tif err = d.GoTo(it.Pos); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treached := func(float64) bool { return d.State().Pos.Sub(it.Pos).Len() < it.Accept }\n\t\tif !sim.RunUntil(90, reached) {\n\t\t\treturn fmt.Errorf(\"item %d: not within %.0f m after 90 s\", it.Seq, it.Accept)\n\t\t}\n\t\tif it.Hold > 0 {\n\t\t\tsim.Run(it.Hold, nil)\n\t\t}\n\tcase CmdLand:\n\t\terr = d.Land()\n\t\tif err == nil && !sim.RunUntil(120, func(float64) bool { return d.State().Landed }) {\n\t\t\terr = fmt.Errorf(\"landing timed out\")\n\t\t}\n\tcase CmdRTL:\n\t\terr = d.ReturnHome()\n\t\tif err == nil && !sim.RunUntil(180, func(float64) bool { return d.State().Landed }) {\n\t\t\terr = fmt.Errorf(\"return timed out\")\n\t\t}\n\t}\n\treturn err\n}\n\nfunc main() {\n\tfootprint := Footprint(20, 70) // 20 m up, 70 degree lens\n\tmaxSpacing := footprint * (1 - 0.7)\n\tsurvey, spacing := Lawnmower(-30, 10, 30, 50, 20, maxSpacing)\n\tmission := BuildMission(20, survey)\n\tfmt.Printf(\"footprint %.1f m, 70%% sidelap: legs at most %.1f m apart\\n\", footprint, maxSpacing)\n\tfmt.Printf(\"survey 60 x 40 m at 20 m: %d legs %.1f m apart, %d mission items\\n\", len(survey)/2, spacing, len(mission))\n\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 11})\n\td := sim.Drone()\n\tfmt.Println(\"seq  command      target               done at  speed     battery\")\n\tstart := 0.0\n\tfor _, it := range mission {\n\t\tif err := Execute(sim, d, it); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tst := d.State()\n\t\ttarget := it.Pos.String()\n\t\tif it.Cmd == CmdRTL {\n\t\t\ttarget = \"home \" + d.Home().String()\n\t\t}\n\t\tfmt.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)\n\t\tif it.Cmd == CmdTakeoff {\n\t\t\tstart = sim.Time()\n\t\t}\n\t}\n\tst := d.State()\n\tfmt.Printf(\"survey and return took %.0f s; landed %.1f m from home\\n\", sim.Time()-start, st.Pos.Horizontal().Len())\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A lawnmower survey, flown item by item","walkthrough":"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."},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern","unitID":"drones-missions","wrongAnswers":["The ground station, by streaming items after MISSION_COUNT","The vehicle, by sending MISSION_ACK after every item"]},{"conceptTag":"drones.geofencing","designGuide":{"cautions":["Points on edges and rays through vertices need explicit rules.","Position error and tailwind eat into any margin you draw."],"cost":"A point-in-polygon test per position update, an intersection per edge for prediction, and a margin chosen from measured braking.","family":"drones","flow":["Draw inclusion, exclusion","Check point and ceiling","Predict time to boundary","Hold, return or land"],"ratings":[],"strengths":["Ray casting handles concave polygons in a few lines.","Prediction stops the vehicle inside the fence, not beyond it."]},"hint":"Compare where the fence check triggers with how far a vehicle at 8 m/s travels while braking at about 4 m/s squared.","id":"drones.geofencing","introduction":"A geofence stands between a software bug, a gust or a confused operator and an airspace infringement. Most flight stacks act only once the vehicle is already outside, and a multicopter at 8 m/s needs several metres to stop, so where the fence acts matters as much as where it is drawn. The geometry is short; the edge cases and the physics are where fences fail.","nuance":"Most fence actions trigger once the position is outside. At 8 m/s braking at 4 m/s2 the vehicle still covers about 8 m, so use a contingency boundary inside the fence or predict the breach from velocity.","objective":"Implement point-in-polygon with an explicit boundary rule, combine inclusion zones, exclusion zones and a ceiling, predict the time to the boundary from velocity, and compare a reactive fence with a predictive guard in the simulator.","question":"A multicopter flies at 8 m/s straight at a geofence whose action is RTL. Why does it end up several metres outside?","references":["https://en.wikipedia.org/wiki/Point_in_polygon","https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/common-polygon_fence.html","https://docs.px4.io/main/en/flying/geofence.html"],"reviewAnswer":"After the breach; stopping still takes metres","reviewPrompt":"When does a fence action fire?","sections":[{"body":"A fence plan combines inclusion areas the vehicle must stay inside, exclusion areas it must stay out of (an airfield approach, a crowd, a mast) and altitude limits. PX4 and ArduPilot accept polygons and circles of both kinds, uploaded with the MAVLink mission protocol as the fence mission type, next to a simple cylinder around home with a maximum radius and altitude; with several inclusion polygons, ArduPilot lets the vehicle fly only where they all overlap. A position is allowed only if it is inside the inclusion area, outside every exclusion area and below the ceiling. The check runs on the position estimate, so it is only as good as the estimate: a GPS glitch can trigger a false breach, and a fence drawn to the metre needs a margin for position error.","title":"Inclusion, exclusion and ceiling"},{"body":"Cast a ray from the point towards +X and count the edges it crosses: an odd count means inside. The condition (a.Y > p.Y) != (b.Y > p.Y) treats each edge as half-open, so a ray through a vertex is counted once, not twice, and horizontal edges are skipped. Points exactly on an edge are the ambiguous case: plain ray casting puts left and bottom edges inside and right and top edges outside, which is fine for drawing and wrong for a safety check, so test for the boundary first and decide explicitly. Concave polygons need nothing special, but self-intersecting ones break the parity rule and a fence editor should reject them. For fences of a few kilometres, local metres around a reference point are accurate enough; over tens of kilometres, project carefully.","title":"Ray casting and its edge cases"},{"body":"The program defines an L-shaped field, a no-fly box around a mast and a 40 m ceiling. Locate is ray casting with an on-segment test first; Allowed combines the three rules and treats the boundary as a breach. Then the drone dashes east at 8 m/s with the simulator's Geofence set: every 2 s the program prints the time to the boundary along the velocity and the stopping distance, the simulator's failsafe switches to RTL on the breach, and the drone overshoots before it stops. Back inside, a careless mission overrides the RTL and sends it out again; the fence has re-armed and catches the second breach. A second flight holds as soon as the stopping distance plus a 3 m margin reaches the boundary, then tries to climb through the ceiling under velocity control.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// An L-shaped field (concave), a no-fly box around a mast, and a ceiling.\nvar (\n\tfence = []drone.Vec3{{X: -40, Y: -40}, {X: 60, Y: -40}, {X: 60, Y: 20}, {X: 10, Y: 20}, {X: 10, Y: 60}, {X: -40, Y: 60}}\n\tmast  = []drone.Vec3{{X: -25, Y: 30}, {X: -10, Y: 30}, {X: -10, Y: 45}, {X: -25, Y: 45}}\n)\n\nconst ceiling = 40.0\n\nfunc cross(a, b drone.Vec3) float64 { return a.X*b.Y - a.Y*b.X }\n\n// onSegment reports whether p lies on the segment a-b (within 1 cm).\nfunc onSegment(a, b, p drone.Vec3) bool {\n\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\tif math.Abs(cross(ab, ap)) > 0.01*ab.Len() {\n\t\treturn false\n\t}\n\tdot := ab.X*ap.X + ab.Y*ap.Y\n\treturn dot >= 0 && dot <= ab.X*ab.X+ab.Y*ab.Y\n}\n\n// Locate is ray casting with an explicit boundary case. A horizontal ray goes\n// east from p; an edge counts when one end is strictly above p and the other\n// is not, so a ray through a vertex is counted exactly once.\nfunc Locate(poly []drone.Vec3, p drone.Vec3) string {\n\tin := false\n\tfor i, j := 0, len(poly)-1; i < len(poly); j, i = i, i+1 {\n\t\ta, b := poly[i], poly[j]\n\t\tif onSegment(a, b, p) {\n\t\t\treturn \"boundary\"\n\t\t}\n\t\tif (a.Y > p.Y) != (b.Y > p.Y) {\n\t\t\tx := a.X + (p.Y-a.Y)*(b.X-a.X)/(b.Y-a.Y)\n\t\t\tif p.X < x {\n\t\t\t\tin = !in\n\t\t\t}\n\t\t}\n\t}\n\tif in {\n\t\treturn \"inside\"\n\t}\n\treturn \"outside\"\n}\n\n// Allowed applies the whole fence: inclusion polygon, exclusion zone and\n// ceiling. A point on the boundary is treated as a breach.\nfunc Allowed(p drone.Vec3) (bool, string) {\n\tswitch {\n\tcase Locate(fence, p) != \"inside\":\n\t\treturn false, \"outside the field\"\n\tcase Locate(mast, p) != \"outside\":\n\t\treturn false, \"in the mast zone\"\n\tcase p.Z > ceiling:\n\t\treturn false, \"above the ceiling\"\n\t}\n\treturn true, \"ok\"\n}\n\n// TimeToBoundary returns how long until p moving at v crosses an edge.\nfunc TimeToBoundary(poly []drone.Vec3, p, v drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tv = v.Horizontal()\n\tfor i := range poly {\n\t\ta, b := poly[i], poly[(i+1)%len(poly)]\n\t\te, w := b.Sub(a).Horizontal(), a.Sub(p).Horizontal()\n\t\tden := cross(v, e)\n\t\tif den == 0 {\n\t\t\tcontinue // moving parallel to this edge\n\t\t}\n\t\tt, u := cross(w, e)/den, cross(w, v)/den\n\t\tif t >= 0 && u >= 0 && u <= 1 && t < best {\n\t\t\tbest = t\n\t\t}\n\t}\n\treturn best\n}\n\n// stopping distance at speed v: reaction time plus braking at decel m/s^2.\nfunc stopping(v float64) float64 { return v*0.2 + v*v/(2*4.0) }\n\nfunc takeOff(sim *drone.Sim, d *drone.Drone) {\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := d.TakeOff(15); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n}\n\nfunc newSim() *drone.Sim {\n\treturn drone.New(drone.Config{Wind: drone.Vec3{X: 2}, Gust: 0.5, Geofence: fence, Ceiling: ceiling, Seed: 5})\n}\n\nfunc main() {\n\tfmt.Println(\"point            mine      drone.Inside  allowed\")\n\tpoints := []struct {\n\t\tname string\n\t\tp    drone.Vec3\n\t}{\n\t\t{\"home\", drone.Vec3{}},\n\t\t{\"notch\", drone.Vec3{X: 30, Y: 40}},\n\t\t{\"east edge\", drone.Vec3{X: 60, Y: 0}},\n\t\t{\"west edge\", drone.Vec3{X: -40, Y: 0}},\n\t\t{\"inner corner\", drone.Vec3{X: 10, Y: 20}},\n\t\t{\"ray via vertex\", drone.Vec3{X: 0, Y: 20}},\n\t\t{\"mast\", drone.Vec3{X: -15, Y: 35, Z: 20}},\n\t\t{\"too high\", drone.Vec3{X: 0, Y: 10, Z: 45}},\n\t}\n\tfor _, c := range points {\n\t\tok, why := Allowed(c.p)\n\t\tfmt.Printf(\"%-15s  %-8s  %-12v  %v (%s)\\n\", c.name, Locate(fence, c.p), drone.Inside(fence, c.p), ok, why)\n\t}\n\n\t// Reactive: dash east at 8 m/s and let the simulator's fence act. Once\n\t// the drone is back inside, a careless mission sends it out again.\n\tsim := newSim()\n\td := sim.Drone()\n\ttakeOff(sim, d)\n\tstart := sim.Time()\n\tif err := d.SetVelocity(drone.Vec3{X: 8}, 0); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"\\nreactive fence: dash east at 8 m/s from home\")\n\tbreaches, peak, resumed, prev := 0, 0.0, false, d.State().Mode\n\tsim.RunUntil(180, func(t float64) bool {\n\t\tst := d.State()\n\t\tpeak = math.Max(peak, st.Pos.X)\n\t\tk := t - start\n\t\tif breaches == 0 && k > 1 && math.Abs(k-math.Round(k)) < sim.Dt()/2 && int(math.Round(k))%2 == 0 {\n\t\t\tspeed := st.Vel.Horizontal().Len()\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  %4.1f m/s  boundary in %5.1f s, stop needs %4.1f m\\n\",\n\t\t\t\tk, st.Pos.X, speed, TimeToBoundary(fence, st.Pos, st.Vel), stopping(speed))\n\t\t}\n\t\tif st.Mode == drone.Returning && prev != drone.Returning {\n\t\t\tbreaches++\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  %4.1f m/s  simulator: geofence breach %d, RTL\\n\",\n\t\t\t\tk, st.Pos.X, st.Vel.Horizontal().Len(), breaches)\n\t\t}\n\t\tif breaches == 1 && !resumed && st.Mode == drone.Returning && st.Pos.X < 45 {\n\t\t\tresumed = true\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  overshoot was %.1f m; mission resumes: go to x=75 m\\n\", k, st.Pos.X, peak-60)\n\t\t\tpeak = 0\n\t\t\td.GoTo(drone.Vec3{X: 75, Z: 15}) // overrides the RTL: a bug\n\t\t}\n\t\tprev = st.Mode\n\t\treturn st.Landed\n\t})\n\tst := d.State()\n\tfmt.Printf(\"  second overshoot %.1f m; %s %.1f m from home at t=%.1f s\\n\", peak-60, st.Mode, st.Pos.Horizontal().Len(), sim.Time()-start)\n\n\t// Predictive: same dash, but hold when the stopping distance plus a\n\t// margin reaches the boundary along the velocity.\n\tg := newSim()\n\tgd := g.Drone()\n\ttakeOff(g, gd)\n\tgd.SetVelocity(drone.Vec3{X: 8}, 0)\n\theld, gmax := false, 0.0\n\tg.Run(20, func(float64) {\n\t\tst := gd.State()\n\t\tgmax = math.Max(gmax, st.Pos.X)\n\t\tspeed := st.Vel.Horizontal().Len()\n\t\tif !held && TimeToBoundary(fence, st.Pos, st.Vel)*speed <= stopping(speed)+3 {\n\t\t\theld = true\n\t\t\tgd.Hold()\n\t\t\tfmt.Printf(\"\\npredictive guard: hold at x=%.1f m, %.1f m/s\\n\", st.Pos.X, speed)\n\t\t}\n\t})\n\tfmt.Printf(\"  closest approach %.1f m inside the fence, mode %s\\n\", 60-gmax, gd.State().Mode)\n\t// The ceiling holds in every mode, even under velocity control.\n\tgd.SetVelocity(drone.Vec3{Z: 3}, 0)\n\tg.Run(15, nil)\n\tfmt.Printf(\"  climb at 3 m/s for 15 s: altitude %.1f m under the %.0f m ceiling\\n\", gd.State().Pos.Z, ceiling)\n\n\tif err := g.SaveAs(\"guarded\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Check points, then fly at the fence","walkthrough":"drone.Inside says false for the east edge and true for the west edge; Locate calls both boundary and Allowed rejects them, like the inner corner of the L. The ray from (0, 20) through the vertex (10, 20) still counts as inside. The mast point is inside the field but in the exclusion zone, and 45 m is above the ceiling. In the dash the boundary is 0.1 s away at t=8.0 s and the first breach comes at 8.1 s at x=60.3 m; the drone overshoots by 4.6 m, half the 9.6 m that the deliberately cautious 4 m/s2 braking figure predicts. Back inside at x=44.9 m the resumed mission overrides the RTL, but the fence has re-armed: the second breach at 16.2 s comes at 11.3 m/s, overshoots by 8.5 m, and the second RTL lands the drone 0.3 m from home. The guard holds at x=47.5 m and stops 8.2 m inside, and a 15 s climb at 3 m/s levels off at 39.0 m, 1 m under the ceiling."},{"body":"The time to the boundary is the smallest t at which p + v t crosses an edge, a ray-segment intersection per edge computed with 2D cross products. Compare the distance along the velocity with the stopping distance v t_react + v squared / (2a): the reaction time covers the telemetry period and command latency, and a is the braking you have measured, not the best case. When the distance falls below that plus a margin for position error and tailwind, hold or turn. PX4's GF_ACTION and ArduPilot's FENCE_ACTION fire only after the breach; newer PX4 adds a contingency geofence (GF_CONT_H_MARGIN, GF_CONT_ACTION) inside the fence and asks for a margin of at least v squared / 2a, and ArduPilot can stop a Copter before the fence in Loiter when object avoidance is set up.","title":"Predict the breach instead of detecting it"},{"body":"What should happen after a breach depends on what lies beyond the line. Hold stops at once near the boundary and leaves the pilot to decide. Return flies home, usually after climbing to a return altitude, which is wrong if home lies behind an exclusion zone or the climb crosses a ceiling. Land puts the vehicle down outside the fence: acceptable over an empty field, dangerous over a road. Flight termination cuts the motors and is reserved for vehicles with a parachute or for cases where anything else is worse. The simulator's action is RTL on every new breach, re-armed once the drone is back inside, so mission code that overrides the return is caught again; better mission code never overrides a failsafe at all. A real setup chooses the action per fence and checks that the return path stays inside. Log every breach with position, velocity and estimate quality: most breaches turn out to be planning or estimation errors.","title":"Breach actions"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output shows two recordings: flight.gfflight is the reactive run, with the L-shaped fence on the map, both breaches, both overshoots and the return home; guarded.gfflight stops short of the east edge and levels off under the ceiling in the altitude strip. Set the margin to 0 or the dash speed to 12 m/s and watch where the guard stops.","title":"Fly it in GopherForge"}],"takeaway":"Use ray casting with an explicit rule for points on the boundary, combine inclusion, exclusion and ceiling checks, and remember that most breach actions fire after the breach. Predict the boundary from velocity and stopping distance, and keep a margin inside the fence for braking, wind and position error.","title":"Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach","unitID":"drones-missions","wrongAnswers":["RTL climbs first, and the climb drifts it outside","Ray casting misses points that lie on the boundary"]},{"conceptTag":"drones.failsafes","designGuide":{"cautions":["Voltage sag and cold packs distort charge estimates.","A reserve below the land failsafe ends in a forced landing."],"cost":"A consumption model fitted from flight logs, a budget check in the control loop and a test for every failsafe path.","family":"drones","flow":["Fit drain from logs","Budget home plus reserve","Turn back at the need","Keep thresholds as backup"],"ratings":[],"strengths":["The turn-back point adapts to distance and wind.","Fixed thresholds remain an independent last resort."]},"hint":"Ask what a single percentage threshold knows about where the vehicle is and which way the wind blows on the way back.","id":"drones.failsafes","introduction":"Failsafes are the code paths that run when something has already gone wrong: the battery is low, the link is gone, the position estimate is bad, the vehicle left its fence. Normal flights rarely exercise them, which is exactly why they hide bugs. A fixed rule such as 'at 20 percent, return home' is a good last resort and a poor plan, because whether 20 percent is enough depends on how far away home is and which way the wind blows.","nuance":"The charge needed to get home grows with distance and headwind. A budget checked every second turns back earlier when the vehicle is far away or downwind, and later when it is close to home.","objective":"Explain state of charge and voltage sag, estimate the charge needed to fly home against the wind with a reserve, compare that budget with fixed battery thresholds in the simulator, and design link-loss timeouts and failsafe priorities.","question":"A drone with an 'at 20 percent, return home' failsafe is forced to land far from home with 10 percent left. What did the rule miss?","references":["https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/failsafe-battery.html","https://ardupilot.org/copter/docs/gcs-failsafe.html","https://pkg.go.dev/time#Timer"],"reviewAnswer":"It ignores the distance home and the wind on the way","reviewPrompt":"Why is a 20% RTL rule not enough?","sections":[{"body":"A lithium polymer cell rests near 4.2 V when full and falls through about 3.7 V as it empties, and under load its terminal voltage drops by the current times its internal resistance. A burst of throttle sags the pack for a moment, and cold or ageing packs sag more, so a voltage threshold fires early in a climb and late in a gentle hover. That is why ArduPilot's battery failsafe waits until the voltage has stayed low for BATT_LOW_TIMER seconds (10 by default) and BATT_FS_VOLTSRC can select a sag-compensated voltage. Counting consumed charge (the BATT_LOW_MAH style of threshold) or a smart battery's own state of charge is steadier, but needs an accurate capacity and current sensor. The simulator reports percent directly; its drain follows thrust, about 0.18 percent per second in a hover, plus a term that grows with the square of the airspeed, so holding against the wind costs energy.","title":"State of charge, voltage and sag"},{"body":"The question to ask at every moment is: if I turned back now, would I land with my reserve? Answer it with the distance home, the wind and a consumption model fitted from logs. Autopilots usually fly home at a set ground speed, so a headwind first raises the airspeed, and drain grows with airspeed; once the airframe is at its top airspeed, more headwind lowers the ground speed instead, and a crosswind must be cancelled from the same airspeed. Time home is the distance over that ground speed, padded for the turn and the approach; multiply by the drain at that airspeed, add the descent and the reserve. The reserve sits above the critical level: if the land failsafe fires at 10 percent, a reserve of 8 ends in a forced landing short of home. If the wind beats the airframe there is no way home, and the budget must say so. PX4 builds this in as its distance-aware return failsafe: it compares the estimated time for the return path, padded by RTL_TIME_FACTOR and RTL_TIME_MARGIN, with the battery's remaining flight time, and once it has triggered it does not cancel when the estimate improves.","title":"An energy budget for the way home"},{"body":"The program first prints the charge needed from 100, 300 and 500 m in calm air, against 5, 12 and 20 m/s headwinds and in a 10 m/s crosswind. Then it flies the same mission twice on a 45 percent battery: out to x=600 m with a 5 m/s wind behind it, then a hover there for an inspection; the way home is into the wind. Both flights print the autopilot's events live from sim.Events(), as a ground station receives STATUSTEXT messages. The first relies only on the simulator's fixed failsafes; the second checks the budget once per second and turns back when the charge it has reaches the charge it needs.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Budget estimates the charge needed to fly home and land from where the\n// drone is now. The autopilot flies home at a set ground speed unless the\n// airframe's top airspeed cannot make it; drain is hover plus a term that\n// grows with airspeed squared, fitted from flight logs.\ntype Budget struct {\n\tSpeed   float64 // ground speed the autopilot flies home, m/s\n\tMaxAir  float64 // top airspeed of the airframe, m/s\n\tHover   float64 // drain in a hover, %/s\n\tDrag    float64 // extra drain per (m/s of airspeed)^2, %/s\n\tFactor  float64 // time margin for the turn, braking and the approach\n\tDescent float64 // average descent rate, m/s\n\tReserve float64 // charge to keep on the ground, %: above the land failsafe\n}\n\n// Need returns the charge to get home, the ground speed and airspeed it\n// assumes, and the time it takes. A headwind raises the airspeed for the\n// same ground speed; once the airspeed limit is reached it lowers the\n// ground speed instead. If the wind beats the airframe, the need is infinite.\nfunc (b Budget) Need(p, home, wind drone.Vec3) (need, groundSpeed, airspeed, seconds float64) {\n\ttoHome := home.Sub(p).Horizontal()\n\tdist := toHome.Len()\n\tu := drone.Vec3{X: 1}\n\tif dist > 0 {\n\t\tu = toHome.Scale(1 / dist)\n\t}\n\talong := wind.X*u.X + wind.Y*u.Y  // tailwind on the way home\n\tacross := wind.X*u.Y - wind.Y*u.X // crosswind the airframe must cancel\n\tinf := math.Inf(1)\n\tif across*across >= b.MaxAir*b.MaxAir {\n\t\treturn inf, 0, b.MaxAir, inf\n\t}\n\tgroundSpeed = math.Min(b.Speed, along+math.Sqrt(b.MaxAir*b.MaxAir-across*across))\n\tif groundSpeed <= 0.5 {\n\t\treturn inf, groundSpeed, b.MaxAir, inf\n\t}\n\tairspeed = u.Scale(groundSpeed).Sub(wind.Horizontal()).Len()\n\tcruise, descend := b.Factor*dist/groundSpeed, p.Z/b.Descent\n\tneed = cruise*(b.Hover+b.Drag*airspeed*airspeed) + descend*b.Hover + b.Reserve\n\treturn need, groundSpeed, airspeed, cruise + descend\n}\n\nvar (\n\twind   = drone.Vec3{X: 5} // blowing east: a tailwind out, a headwind home\n\ttarget = drone.Vec3{X: 600, Z: 20}\n\tbudget = Budget{Speed: 10, MaxAir: 18, Hover: 0.18, Drag: 0.0016, Factor: 1.1, Descent: 1.5, Reserve: 15}\n)\n\n// fly sends the drone out to the target, where it holds for an inspection,\n// and prints the autopilot's events as a ground station receives them.\nfunc fly(useBudget bool) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: wind, Gust: 0.5, Battery: 45, MaxSpeed: 10, Seed: 9})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(20)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tseen := len(sim.Events())\n\td.GoTo(target)\n\tturned, atTurn := false, 0.0\n\tsim.RunUntil(400, func(t float64) bool {\n\t\tst := d.State()\n\t\tevents := sim.Events()\n\t\tfor _, e := range events[seen:] {\n\t\t\tfmt.Printf(\"  %5.1f s  %-35s battery %4.1f%%  %5.1f m out\\n\", e.T, e.Text, st.Battery, st.Pos.Horizontal().Len())\n\t\t}\n\t\tseen = len(events)\n\t\tonSecond := math.Abs(t-math.Round(t)) < sim.Dt()/2\n\t\tif useBudget && !turned && onSecond && (st.Mode == drone.GoingTo || st.Mode == drone.Hold) {\n\t\t\tneed, gs, air, secs := budget.Need(st.Pos, d.Home(), wind)\n\t\t\tif st.Battery <= need {\n\t\t\t\tturned, atTurn = true, st.Battery\n\t\t\t\tfmt.Printf(\"  %5.1f s  budget: need %.1f%% (%.0f s home at %.1f m/s, airspeed %.1f), have %.1f%%\\n\",\n\t\t\t\t\tt, need, secs, gs, air, st.Battery)\n\t\t\t\td.ReturnHome()\n\t\t\t}\n\t\t}\n\t\treturn st.Landed\n\t})\n\tst := d.State()\n\tif turned {\n\t\tfmt.Printf(\"  used %.1f%% to get home, budgeted %.1f%% plus the %.0f%% reserve\\n\",\n\t\t\tatTurn-st.Battery, atTurn-budget.Reserve, budget.Reserve)\n\t}\n\tfmt.Printf(\"  %s %.1f m from home with %.1f%%\\n\", st.Mode, st.Pos.Horizontal().Len(), st.Battery)\n\treturn sim\n}\n\nfunc main() {\n\tfmt.Println(\"charge to get home from x m east at 20 m (10 m/s home, 18 m/s top airspeed, 15% reserve)\")\n\tfmt.Printf(\"  %-5s%13s%13s%13s%13s%13s\\n\", \"x\", \"calm\", \"5 m/s head\", \"12 m/s head\", \"20 m/s head\", \"10 m/s cross\")\n\tfor _, dist := range []float64{100, 300, 500} {\n\t\tfmt.Printf(\"  %3.0f m \", dist)\n\t\tfor _, w := range []drone.Vec3{{}, {X: 5}, {X: 12}, {X: 20}, {Y: 10}} {\n\t\t\tneed, _, _, _ := budget.Need(drone.Vec3{X: dist, Z: 20}, drone.Vec3{}, w)\n\t\t\tcell := fmt.Sprintf(\"%.1f%%\", need)\n\t\t\tif math.IsInf(need, 1) {\n\t\t\t\tcell = \"no way home\"\n\t\t\t}\n\t\t\tfmt.Printf(\"%13s\", cell)\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println(\"\\nfixed thresholds only: out to x=600 m on 45%, hold there\")\n\tfixed := fly(false)\n\tif err := fixed.SaveAs(\"thresholds\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"\\nenergy budget checked every second, same mission\")\n\tsim := fly(true)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Thresholds against a budget","walkthrough":"Wind, not distance alone, decides: from 300 m the need is 28.6 percent in calm air, 35.2 against 5 m/s, where the ground speed stays 10 m/s but the airspeed rises to 15, and 55.8 against 12 m/s, where the 18 m/s airspeed limit leaves 6 m/s over the ground; against 20 m/s there is no way home. With thresholds only, the drone arrives at x=600 m with 29.2 percent and hovers until the event 'battery 20%: return to home' at 112.4 s, 600.0 m out; 'battery 10%: forced landing' follows at 131.3 s, 422.4 m out, and it lands 422.7 m from home with 7.0. With the budget, at 40.0 s and 310.0 m out the need of 35.8 percent meets the charge; the return used 20.9 points against 20.8 budgeted and lands at home with 14.9, the 15 percent reserve."},{"body":"A vehicle cannot tell a dead ground station from a radio fade, so link loss is a timeout on heartbeats. ArduPilot's GCS failsafe fires when no ground-station HEARTBEAT has arrived for FS_GCS_TIMEOUT seconds (5 by default); PX4 uses COM_DL_LOSS_T with the action in NAV_DLL_ACT. Loss of manual control has its own short timeout (COM_RC_LOSS_T in PX4), because the vehicle keeps flying on the last stick input until it fires. Too short and every fade triggers a return; too long and a runaway keeps going. The ground station needs the mirror image: notice a silent vehicle, warn the operator, and never queue commands during an outage to replay them later. In Go, a watchdog is a timer that every heartbeat resets.","code":"func Watch(ctx context.Context, beats <-chan struct{}, timeout time.Duration, lost func(bool)) {\n\tt := time.NewTimer(timeout)\n\tdefer t.Stop()\n\tdown := false\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-beats:\n\t\t\tif down {\n\t\t\t\tdown = false\n\t\t\t\tlost(false)\n\t\t\t}\n\t\t\tt.Reset(timeout)\n\t\tcase <-t.C:\n\t\t\tdown = true\n\t\t\tlost(true)\n\t\t}\n\t}\n}","language":"go","title":"Link loss is a timeout","walkthrough":"Every heartbeat pushes the deadline back with Reset; since Go 1.23, Reset and Stop never leave a stale tick in the channel, so no draining is needed. The timer fires once per outage and is re-armed only by the next heartbeat, which also reports recovery. Wrapped in testing/synctest, a test drives this with a fake clock, so a 5 s timeout is checked instantly and deterministically."},{"body":"Several failsafes can fire together: a low battery during link loss outside the fence. PX4 orders actions by severity (warning, hold, return, land, disarm, flight termination) and takes the most severe one, by default after holding for COM_FAIL_ACT_T seconds so an operator can intervene. Land beats return when the battery cannot reach home, when the position estimate is bad (ArduPilot's battery RTL falls back to Land without a good position) or when the return path is unsafe; return beats land over water, roads or people. Write the table down and test each row: in a simulator, in SITL with the flight stack's own failsafe code, and on a field with a pilot ready to take over. A failsafe that has never fired in a test has unknown behaviour, and one that fires in every flight teaches operators to ignore it.","title":"Priorities, and testing every failsafe"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists two recordings: thresholds.gfflight hovers at x=600 m and ends in a field 423 m east of home, and flight.gfflight turns back 310 m out and lands at home; the HUD's battery shows where each decision was taken. Raise the wind to 8 m/s, or lower the reserve to 8 percent, below the 10 percent land failsafe, and watch where the drone lands.","title":"Fly it in GopherForge"}],"takeaway":"A fixed battery threshold ignores distance and wind; a budget compares the charge you have with the charge needed to fly home against the wind, descend and keep a reserve above the land failsafe, and turns back in time. Treat link loss as a heartbeat timeout, decide which action wins when several failsafes fire, and test every one of them.","title":"Failsafes: battery energy budgets, link-loss timeouts and which action wins","unitID":"drones-missions","wrongAnswers":["Percent readings are too coarse to trigger in time","RTL always diverts to the nearest rally point"]},{"conceptTag":"drones.path-planning","designGuide":{"cautions":["Grid resolution can close narrow gaps or waste space.","A straight-line RTL ignores the zones you planned around."],"cost":"A rasterized map with an inflation step, a priority-queue search and a replan hook wherever the map can change.","family":"drones","flow":["Inflate zones into a grid","A* with octile heuristic","Prune by line of sight","Replan when map changes"],"ratings":[],"strengths":["Optimal grid paths with far fewer expansions than Dijkstra.","Pruned paths are short lists of flyable waypoints."]},"hint":"Compare the Manhattan distance of one diagonal step with what that step actually costs on the grid.","id":"drones.path-planning","introduction":"A straight line from take-off to destination is the shortest path until something is in the way: a stay-out zone, a building, a temporary restriction published in the middle of a mission. Planning turns a map of allowed space into waypoints the autopilot can fly. The classic pipeline is a grid, an A* search, smoothing, and a replan whenever the map changes; each stage has a property to protect: the safety margin, optimality and flyability.","nuance":"With diagonals allowed, Manhattan counts a diagonal step as 2 instead of 1.41. That overestimate makes A* trust a wrong ordering, so the first path to reach the goal is no longer guaranteed shortest.","objective":"Rasterize no-fly zones into an inflated grid, find the shortest path with A* and the admissible octile heuristic, prune it to a few waypoints by line of sight, fly it in the simulator and replan when a new restriction appears.","question":"On an 8-connected grid you switch the A* heuristic from octile to Manhattan distance, and some paths get longer. What went wrong?","references":["https://en.wikipedia.org/wiki/A*_search_algorithm","https://en.wikipedia.org/wiki/Any-angle_path_planning","https://ardupilot.org/copter/docs/common-oa-dijkstras.html","https://pkg.go.dev/container/heap"],"reviewAnswer":"Overestimating the remaining cost to the goal","reviewPrompt":"What must an A* heuristic avoid?","sections":[{"body":"Rasterize the area into cells, 5 m here, mark every cell covered by a no-fly zone, then inflate the zones by the safety buffer: the vehicle's size, the position error and the tracking error in wind. Planning on the inflated map lets the planner treat the drone as a point. Cell size is a trade: coarse cells close narrow gaps and waste space, fine cells multiply the work. Altitude can be a third dimension, but small-drone planning is usually 2D at a fixed height, with terrain and ceilings checked separately. ArduPilot does this kind of planning on board: its Dijkstra's object avoidance (OA_TYPE = 2) plans around fences and stay-out zones in Auto, Guided and RTL, and OA_MARGIN_MAX sets how far it stays from them.","title":"From map to grid"},{"body":"A* expands the cell with the lowest f = g + h, where g is the cost so far and h estimates the cost to the goal. If h never overestimates (admissible), the first time the goal is expanded its path is optimal; if h is also consistent, no cell is ever expanded twice. On an 8-connected grid where straight moves cost 1 and diagonals sqrt(2), the octile distance max(dx, dy) + (sqrt(2) - 1) min(dx, dy) is the exact cost on an empty map, so it is both. Euclidean distance is admissible but weaker; Manhattan distance overestimates once diagonals are allowed and silently gives up optimality. Forbid diagonals that cut a blocked corner, and break ties deterministically (here by h, then insertion order) so the same map always yields the same path. container/heap provides the priority queue.","title":"A* and an admissible heuristic"},{"body":"The program blocks a 4 by 10 cell zone (a smaller zone grown by one cell), runs A* and Dijkstra's algorithm (A* with h = 0) from home to a goal 95 m east, prunes the cell path by line of sight and flies the waypoints with a 2 m acceptance radius. After the first waypoint a new restriction is published: the program blocks it, replans from the cell the drone is in, prints the new plan and flies it, then lands at the goal. Clearance records the distance from the drone to the nearest blocked cell on every step.","code":"package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tW, H = 24, 14 // grid size in cells\n\tcell = 5.0    // metres per cell\n\talt  = 15.0   // flight altitude, m\n\tsx   = 2      // start cell X\n\tsy   = 7      // start cell Y (home)\n)\n\ntype P struct{ X, Y int }\n\n// Grid marks blocked cells: a no-fly zone already grown by a safety buffer.\ntype Grid [H][W]bool\n\nfunc (g *Grid) Block(x0, y0, x1, y1 int) {\n\tfor y := y0; y <= y1; y++ {\n\t\tfor x := x0; x <= x1; x++ {\n\t\t\tg[y][x] = true\n\t\t}\n\t}\n}\n\nfunc (g *Grid) Free(p P) bool { return p.X >= 0 && p.Y >= 0 && p.X < W && p.Y < H && !g[p.Y][p.X] }\n\n// octile distance: the exact cost on an empty 8-connected grid, so it never\n// overestimates and A* stays optimal.\nfunc octile(a, b P) float64 {\n\tdx, dy := math.Abs(float64(a.X-b.X)), math.Abs(float64(a.Y-b.Y))\n\treturn math.Max(dx, dy) + (math.Sqrt2-1)*math.Min(dx, dy)\n}\n\ntype node struct {\n\tp    P\n\tf, h float64\n\tseq  int\n}\ntype queue []node\n\nfunc (q queue) Len() int { return len(q) }\nfunc (q queue) Less(i, j int) bool {\n\tif q[i].f != q[j].f {\n\t\treturn q[i].f < q[j].f\n\t}\n\tif q[i].h != q[j].h {\n\t\treturn q[i].h < q[j].h\n\t}\n\treturn q[i].seq < q[j].seq\n}\nfunc (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\nfunc (q *queue) Push(x any)   { *q = append(*q, x.(node)) }\nfunc (q *queue) Pop() any {\n\told := *q\n\tn := old[len(old)-1]\n\t*q = old[:len(old)-1]\n\treturn n\n}\n\n// AStar returns the cheapest 8-connected path and how many cells it\n// expanded. With useH false it is Dijkstra's algorithm.\nfunc AStar(g *Grid, start, goal P, useH bool) ([]P, int) {\n\th := func(p P) float64 {\n\t\tif useH {\n\t\t\treturn octile(p, goal)\n\t\t}\n\t\treturn 0\n\t}\n\tcost := map[P]float64{start: 0}\n\tfrom := map[P]P{}\n\tclosed := map[P]bool{}\n\tq := &queue{{p: start, f: h(start), h: h(start)}}\n\tseq, expanded := 0, 0\n\tfor q.Len() > 0 {\n\t\tcur := heap.Pop(q).(node)\n\t\tif closed[cur.p] {\n\t\t\tcontinue\n\t\t}\n\t\tclosed[cur.p] = true\n\t\texpanded++\n\t\tif cur.p == goal {\n\t\t\tpath := []P{goal}\n\t\t\tfor p := goal; p != start; {\n\t\t\t\tp = from[p]\n\t\t\t\tpath = append([]P{p}, path...)\n\t\t\t}\n\t\t\treturn path, expanded\n\t\t}\n\t\tfor dy := -1; dy <= 1; dy++ {\n\t\t\tfor dx := -1; dx <= 1; dx++ {\n\t\t\t\tn := P{cur.p.X + dx, cur.p.Y + dy}\n\t\t\t\tif (dx == 0 && dy == 0) || !g.Free(n) || closed[n] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// no corner cutting: a diagonal needs both side cells free\n\t\t\t\tif dx != 0 && dy != 0 && (!g.Free(P{cur.p.X + dx, cur.p.Y}) || !g.Free(P{cur.p.X, cur.p.Y + dy})) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc := cost[cur.p] + math.Hypot(float64(dx), float64(dy))\n\t\t\t\tif old, ok := cost[n]; ok && old <= c {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcost[n], from[n] = c, cur.p\n\t\t\t\tseq++\n\t\t\t\theap.Push(q, node{p: n, f: c + h(n), h: h(n), seq: seq})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, expanded\n}\n\n// Visible samples the straight segment between two cell centres.\nfunc Visible(g *Grid, a, b P) bool {\n\tn := int(math.Ceil(math.Hypot(float64(b.X-a.X), float64(b.Y-a.Y)) * 4))\n\tfor i := 0; i <= n; i++ {\n\t\tt := float64(i) / float64(max(n, 1))\n\t\tx := float64(a.X) + t*float64(b.X-a.X)\n\t\ty := float64(a.Y) + t*float64(b.Y-a.Y)\n\t\tif !g.Free(P{int(math.Round(x)), int(math.Round(y))}) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Prune keeps a cell only when the next one is not in line of sight from\n// the last kept cell.\nfunc Prune(g *Grid, path []P) []P {\n\tout := []P{path[0]}\n\tfor i := 1; i < len(path)-1; i++ {\n\t\tif !Visible(g, out[len(out)-1], path[i+1]) {\n\t\t\tout = append(out, path[i])\n\t\t}\n\t}\n\treturn append(out, path[len(path)-1])\n}\n\nfunc length(path []P) float64 {\n\tsum := 0.0\n\tfor i := 1; i < len(path); i++ {\n\t\tsum += math.Hypot(float64(path[i].X-path[i-1].X), float64(path[i].Y-path[i-1].Y)) * cell\n\t}\n\treturn sum\n}\n\nfunc toWorld(p P) drone.Vec3 {\n\treturn drone.Vec3{X: float64(p.X-sx) * cell, Y: float64(p.Y-sy) * cell, Z: alt}\n}\nfunc toCell(v drone.Vec3) P {\n\treturn P{int(math.Round(v.X/cell)) + sx, int(math.Round(v.Y/cell)) + sy}\n}\n\n// Clearance is the distance from a position to the nearest blocked cell.\nfunc Clearance(g *Grid, v drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tfor y := 0; y < H; y++ {\n\t\tfor x := 0; x < W; x++ {\n\t\t\tif !g[y][x] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := toWorld(P{x, y})\n\t\t\tdx := math.Max(0, math.Abs(v.X-c.X)-cell/2)\n\t\t\tdy := math.Max(0, math.Abs(v.Y-c.Y)-cell/2)\n\t\t\tbest = math.Min(best, math.Hypot(dx, dy))\n\t\t}\n\t}\n\treturn best\n}\n\nfunc draw(g *Grid, path, wps []P) {\n\trows := make([][]byte, H)\n\tfor y := range rows {\n\t\trows[y] = []byte(strings.Repeat(\".\", W))\n\t\tfor x := 0; x < W; x++ {\n\t\t\tif g[y][x] {\n\t\t\t\trows[y][x] = '#'\n\t\t\t}\n\t\t}\n\t}\n\tfor _, p := range path {\n\t\trows[p.Y][p.X] = '*'\n\t}\n\tfor i, p := range wps {\n\t\trows[p.Y][p.X] = byte('0' + i)\n\t}\n\tfor y := H - 1; y >= 0; y-- { // north up\n\t\tfmt.Println(\"  \" + string(rows[y]))\n\t}\n}\n\nfunc main() {\n\tvar g Grid\n\tg.Block(9, 2, 12, 11) // zone x 10..11, y 3..10 grown by one 5 m cell\n\tstart, goal := P{sx, sy}, P{21, sy}\n\n\tpath, n := AStar(&g, start, goal, true)\n\tdpath, nd := AStar(&g, start, goal, false)\n\twps := Prune(&g, path)\n\tfmt.Printf(\"A*: %d cells, %.1f m, expanded %d cells\\n\", len(path), length(path), n)\n\tfmt.Printf(\"Dijkstra: %d cells, %.1f m, expanded %d cells\\n\", len(dpath), length(dpath), nd)\n\tfmt.Printf(\"pruned to %d waypoints, %.1f m\\n\", len(wps), length(wps))\n\tdraw(&g, path, wps)\n\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: -2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 3})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n\n\tplan, clearance := 1, math.Inf(1)\n\tfor i := 1; i < len(wps); i++ {\n\t\tp := toWorld(wps[i])\n\t\td.GoTo(p)\n\t\tlast := i == len(wps)-1\n\t\tif !sim.RunUntil(90, func(float64) bool {\n\t\t\tclearance = math.Min(clearance, Clearance(&g, d.State().Pos))\n\t\t\tif last {\n\t\t\t\treturn d.Arrived()\n\t\t\t}\n\t\t\treturn d.State().Pos.Sub(p).Len() < 2\n\t\t}) {\n\t\t\tlog.Fatalf(\"waypoint %d not reached\", i)\n\t\t}\n\t\tfmt.Printf(\"plan %d, waypoint %d %v at %.1f s\\n\", plan, i, p, sim.Time())\n\t\tif plan == 1 && i == 1 {\n\t\t\t// A new restriction is published: plan again from here.\n\t\t\tplan = 2\n\t\t\tg.Block(16, 4, 18, 13)\n\t\t\there := toCell(d.State().Pos)\n\t\t\tpath, n = AStar(&g, here, goal, true)\n\t\t\twps = Prune(&g, path)\n\t\t\ti = 0\n\t\t\tfmt.Printf(\"new zone x 16..18, y 4..13: replan from cell %d,%d: %d waypoints, %.1f m, expanded %d\\n\",\n\t\t\t\there.X, here.Y, len(wps), length(wps), n)\n\t\t\tdraw(&g, path, wps)\n\t\t}\n\t}\n\t// Land at the goal: a straight-line RTL from here would cross the zones.\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool {\n\t\tclearance = math.Min(clearance, Clearance(&g, d.State().Pos))\n\t\treturn d.State().Landed\n\t})\n\tfmt.Printf(\"closest approach to a blocked cell: %.1f m\\n\", clearance)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Plan, prune, fly, replan","walkthrough":"A* finds a 20-cell, 115.7 m path over the zone after expanding 85 cells; Dijkstra finds a path of the same 115.7 m but expands 274. Pruning keeps 4 waypoints, the start, two corners above the zone and the goal, and cuts the flight to 110.2 m because straight segments replace the 45 degree staircase. The new zone at x 16..18 closes the northern route, so the replan from cell 9,12 runs down the corridor between the zones and under the new one: 5 waypoints, 108.5 m, 79 cells expanded. The drone lands at (95.3, 0.8, 0.0) and came no closer than 0.6 m to a blocked cell, so the buffer absorbed its tracking error."},{"body":"Grid paths zigzag in 45 degree steps, and a waypoint per cell would make the autopilot slow down at each one. Line-of-sight pruning (string pulling) keeps a cell only when the next cell cannot be seen in a straight line from the last kept one, checking the segment against the inflated grid; any-angle planners such as Theta* fold the same test into the search. The result is never longer than the grid path and never crosses a blocked cell, though it is not guaranteed shortest in continuous space. Convert cell centres to the vehicle's frame, add the altitude, and keep the acceptance radius smaller than the buffer, or corner cutting near a zone eats the margin; ArduPilot's documentation gives the same advice for its waypoint radius and fence margin.","title":"Smoothing and waypoints"},{"body":"Replan from the vehicle's current cell whenever the map changes: a new restriction, an obstacle seen by a sensor, a wind that makes a leg infeasible. Keep flying the old plan only while it is still clear, and make the switch an explicit event in the log. On grids this small a full A* is cheap enough to rerun; on large or frequently changing maps, incremental planners such as D* Lite reuse the previous search. Plan the way back too: a plain RTL flies a straight line home and in this example would cross both zones, which is why the program lands at the goal. ArduPilot can run its Dijkstra planner in RTL, and its SmartRTL mode retraces the path already flown.","title":"Replanning and the way back"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. The console shows both grids; Output replays the flight with every waypoint flown from both plans on the map, the turn at the first waypoint where the replan happened, and the landing at the goal. Move the second zone or switch the heuristic to Manhattan distance and compare the paths and the expanded counts.","title":"Fly it in GopherForge"}],"takeaway":"Inflate no-fly zones by the safety buffer, search the grid with A* and an admissible, consistent heuristic such as the octile distance, prune the path by line of sight into a few waypoints, keep the acceptance radius below the buffer, and replan from the current position whenever the map changes.","title":"Path planning around no-fly zones: A*, line-of-sight pruning and replanning","unitID":"drones-missions","wrongAnswers":["Manhattan distance makes A* expand every cell","Manhattan distance ignores blocked cells"]},{"conceptTag":"drones.fleets","designGuide":{"cautions":["A slow consumer can stall a fan-in unless channels are bounded.","Lockstep tests hide the timing problems of real links."],"cost":"A goroutine and inbox per vehicle, a supervisor loop with a context, and a pairwise separation check sized to position error.","family":"drones","flow":["Goroutine per vehicle","Fan-in tagged telemetry","Supervisor with context","Check pairs every cycle"],"ratings":[],"strengths":["Each vehicle state has exactly one owner, so no locks.","One context cancel stops every vehicle goroutine."]},"hint":"Layered routes cross directly above each other. Which of the two distances still protects them at the crossing point?","id":"drones.fleets","introduction":"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.","nuance":"Either distance is enough. At a crossing the horizontal distance falls to zero and the layer spacing carries the separation, so it must exceed the vertical minimum plus altitude error.","objective":"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.","question":"Under a rule of 10 m horizontal or 4 m vertical separation, when are two drones in a fleet separated?","references":["https://go.dev/blog/pipelines","https://pkg.go.dev/context","https://github.com/bluenviron/gomavlib","https://pkg.go.dev/sync#WaitGroup.Go"],"reviewAnswer":"When horizontal or vertical distance meets its minimum","reviewPrompt":"When are two drones separated?","sections":[{"body":"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.","title":"One goroutine per vehicle"},{"body":"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.","title":"Supervisor, context and shutdown"},{"body":"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.","title":"Separation assurance"},{"body":"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.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"sync\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Command is what a pilot goroutine asks the link to send to its vehicle.\ntype Command struct {\n\tKind   string // \"takeoff\", \"goto\" or \"land\"\n\tTarget drone.Vec3\n}\n\n// Report is one telemetry cycle from a pilot: what it saw, what it wants.\ntype Report struct {\n\tDrone int\n\tTel   drone.Telemetry\n\tCmd   *Command\n}\n\n// Route is one vehicle's job: climb to its layer, fly to a point, land.\ntype Route struct {\n\tLayer float64\n\tTo    drone.Vec3\n}\n\n// pilot runs in its own goroutine. It only sees telemetry and only\n// answers with commands, exactly as it would over a radio link.\nfunc pilot(ctx context.Context, id int, r Route, in <-chan drone.Telemetry, out chan<- Report) {\n\tphase := \"ground\"\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase tel := <-in:\n\t\t\tvar cmd *Command\n\t\t\tdest := drone.Vec3{X: r.To.X, Y: r.To.Y, Z: r.Layer}\n\t\t\tswitch {\n\t\t\tcase phase == \"ground\":\n\t\t\t\tphase, cmd = \"climb\", &Command{Kind: \"takeoff\", Target: drone.Vec3{Z: r.Layer}}\n\t\t\tcase phase == \"climb\" && tel.Mode == drone.Hold:\n\t\t\t\tphase, cmd = \"cruise\", &Command{Kind: \"goto\", Target: dest}\n\t\t\tcase phase == \"cruise\" && tel.GPS.Sub(dest).Horizontal().Len() < 3 && tel.Velocity.Len() < 1:\n\t\t\t\tphase, cmd = \"land\", &Command{Kind: \"land\"}\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase out <- Report{Drone: id, Tel: tel, Cmd: cmd}:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc apply(d *drone.Drone, c Command) error {\n\tswitch c.Kind {\n\tcase \"takeoff\":\n\t\tif err := d.Arm(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn d.TakeOff(c.Target.Z)\n\tcase \"goto\":\n\t\treturn d.GoTo(c.Target)\n\tcase \"land\":\n\t\treturn d.Land()\n\t}\n\treturn fmt.Errorf(\"unknown command %q\", c.Kind)\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 1.5, Y: -1}, Gust: 1, MaxSpeed: 6, Seed: 21})\n\tsim.AddDrone(\"bravo\", drone.Vec3{X: -20, Y: 30})\n\tsim.AddDrone(\"charlie\", drone.Vec3{X: 15, Y: 45})\n\tdrones := sim.Drones()\n\t// Three routes that all cross (0, 30), one altitude layer each.\n\troutes := []Route{\n\t\t{Layer: 20, To: drone.Vec3{X: 0, Y: 60}},\n\t\t{Layer: 25, To: drone.Vec3{X: 30, Y: 30}},\n\t\t{Layer: 30, To: drone.Vec3{X: -30, Y: 0}},\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\treports := make(chan Report, len(drones))\n\tinboxes := make([]chan drone.Telemetry, len(drones))\n\tvar wg sync.WaitGroup\n\tfor i := range drones {\n\t\tinboxes[i] = make(chan drone.Telemetry)\n\t\twg.Go(func() { pilot(ctx, i, routes[i], inboxes[i], reports) })\n\t}\n\n\ttype pair struct{ min, minH, vAtMinH, t float64 }\n\tpairs := map[[2]int]*pair{}\n\tkeys := [][2]int{{0, 1}, {0, 2}, {1, 2}}\n\tfor _, k := range keys {\n\t\tpairs[k] = &pair{min: math.Inf(1), minH: math.Inf(1)}\n\t}\n\tviolations := 0\n\n\t// The supervisor: one telemetry cycle every 0.2 s of simulated time.\n\tfor sim.Time() < 120 {\n\t\tfor i, d := range drones {\n\t\t\tinboxes[i] <- d.Telemetry()\n\t\t}\n\t\tbatch := make([]Report, len(drones))\n\t\tfor range drones {\n\t\t\tr := <-reports\n\t\t\tbatch[r.Drone] = r // fan-in arrives in any order; index it\n\t\t}\n\t\tfor i, r := range batch { // act in a fixed order\n\t\t\tif r.Cmd == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := apply(drones[i], *r.Cmd); err != nil {\n\t\t\t\tcancel()\n\t\t\t\tlog.Fatalf(\"%s: %v\", drones[i].Name, err)\n\t\t\t}\n\t\t\twhat := r.Cmd.Kind\n\t\t\tswitch r.Cmd.Kind {\n\t\t\tcase \"takeoff\":\n\t\t\t\twhat = fmt.Sprintf(\"take off to the %.0f m layer\", r.Cmd.Target.Z)\n\t\t\tcase \"goto\":\n\t\t\t\twhat = fmt.Sprintf(\"go to %v\", r.Cmd.Target)\n\t\t\t}\n\t\t\tfmt.Printf(\"%5.1f s  %-7s %s\\n\", sim.Time(), drones[i].Name, what)\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\ta, b := batch[k[0]].Tel, batch[k[1]].Tel\n\t\t\tif a.Time == 0 || drones[k[0]].State().Landed && drones[k[1]].State().Landed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th := a.GPS.Sub(b.GPS).Horizontal().Len()\n\t\t\tv := math.Abs(a.BaroAlt - b.BaroAlt)\n\t\t\tp := pairs[k]\n\t\t\tif dist := math.Hypot(h, v); dist < p.min {\n\t\t\t\tp.min, p.t = dist, a.Time\n\t\t\t}\n\t\t\tif h < p.minH {\n\t\t\t\tp.minH, p.vAtMinH = h, v\n\t\t\t}\n\t\t\tif h < 10 && v < 4 {\n\t\t\t\tviolations++\n\t\t\t}\n\t\t}\n\t\tlanded := 0\n\t\tfor _, d := range drones {\n\t\t\tif d.State().Landed {\n\t\t\t\tlanded++\n\t\t\t}\n\t\t}\n\t\tif sim.Time() > 1 && landed == len(drones) {\n\t\t\tbreak\n\t\t}\n\t\tsim.Run(0.2, nil)\n\t}\n\tcancel()\n\twg.Wait()\n\n\tfmt.Println(\"separation (rule: 10 m horizontal or 4 m vertical)\")\n\tfor _, k := range keys {\n\t\tp := pairs[k]\n\t\tfmt.Printf(\"  %-7s %-7s closest %4.1f m at %4.1f s; min horizontal %4.1f m with %3.1f m vertical\\n\",\n\t\t\tdrones[k[0]].Name, drones[k[1]].Name, p.min, p.t, p.minH, p.vAtMinH)\n\t}\n\tfmt.Printf(\"  samples breaking the rule: %d\\n\", violations)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Three drones, three layers","walkthrough":"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."},{"body":"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.","title":"Deterministic simulation, concurrent reality"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation","unitID":"drones-missions","wrongAnswers":["Only when both distances exceed their minimums","Only when their straight-line distance exceeds 10 m"]},{"conceptTag":"drones.simulation-testing","designGuide":{"cautions":["A simple model can pass what a real airframe fails.","A harness that overrides failsafes tests the wrong program."],"cost":"A deterministic simulator, a scenario table with expectations, an invariant checker and CI time for SITL runs.","family":"drones","flow":["Seed and fixed timestep","Scenarios as table rows","Check invariants per run","SITL, HIL, then field"],"ratings":[],"strengths":["Hundreds of flights per second, reproducible to the last digit.","A new world costs one table row; the invariants stay."]},"hint":"Ask which properties must hold in every world whatever the tuning: the fence, the landing, the speed, the reserve.","id":"drones.simulation-testing","introduction":"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.","nuance":"Golden logs change with every harmless tweak. Invariants such as never leaving the fence and landing near home must always hold, and each row adds its expected outcome, such as a safe abort on low battery.","objective":"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.","question":"Your mission test compares the whole printed flight log with a golden file and breaks after every tuning change. What should it assert instead?","references":["https://go.dev/wiki/TableDrivenTests","https://pkg.go.dev/testing/synctest","https://ardupilot.org/dev/docs/sitl-simulator-software-in-the-loop.html","https://docs.px4.io/main/en/simulation/"],"reviewAnswer":"Safety invariants, plus each row's expected outcome","reviewPrompt":"What do scenario tests assert?","sections":[{"body":"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 ==.","title":"Determinism first"},{"body":"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.","title":"Scenarios as a table"},{"body":"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.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// The survey corners are at 30 m; the fence leaves a 2 m margin.\nvar fence = []drone.Vec3{{X: -32, Y: -32}, {X: 32, Y: -32}, {X: 32, Y: 32}, {X: -32, Y: 32}}\n\n// Scenario is one row of the test matrix: the world the mission flies in\n// and whether the mission is expected to finish or to be aborted safely.\ntype Scenario struct {\n\tName     string\n\tWind     drone.Vec3\n\tGust     float64\n\tBattery  float64\n\tSeed     int64\n\tComplete bool\n}\n\n// Result is what the run measured; invariants are checked against it.\ntype Result struct {\n\tWaypoints int     // survey corners reached\n\tMaxSpeed  float64 // horizontal, m/s\n\tOutside   float64 // furthest distance outside the fence, m\n\tTouchdown float64 // vertical speed at touchdown, m/s\n\tHomeDist  float64 // landing distance from home, m\n\tBattery   float64 // at the end, %\n\tCrashed   bool\n\tFinal     drone.State\n}\n\n// distance from p to the nearest fence edge\nfunc edgeDistance(poly []drone.Vec3, p drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tfor i := range poly {\n\t\ta, b := poly[i], poly[(i+1)%len(poly)]\n\t\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\t\tt := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/(ab.X*ab.X+ab.Y*ab.Y)))\n\t\tbest = math.Min(best, ap.Sub(ab.Scale(t)).Len())\n\t}\n\treturn best\n}\n\n// Fly runs the survey mission in one scenario and measures it.\nfunc Fly(sc Scenario) (*drone.Sim, Result) {\n\tsim := drone.New(drone.Config{Wind: sc.Wind, Gust: sc.Gust, Battery: sc.Battery, MaxSpeed: 10, Geofence: fence, Seed: sc.Seed})\n\td := sim.Drone()\n\tvar r Result\n\tprevVz := 0.0\n\twatch := func() {\n\t\tst := d.State()\n\t\tr.MaxSpeed = math.Max(r.MaxSpeed, st.Vel.Horizontal().Len())\n\t\tif !drone.Inside(fence, st.Pos) {\n\t\t\tr.Outside = math.Max(r.Outside, edgeDistance(fence, st.Pos))\n\t\t}\n\t\tif !st.Landed {\n\t\t\tprevVz = st.Vel.Z\n\t\t}\n\t}\n\tuntil := func(limit float64, done func() bool) bool {\n\t\treturn sim.RunUntil(limit, func(float64) bool { watch(); return done() })\n\t}\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatalf(\"%s: %v\", sc.Name, err)\n\t}\n\td.TakeOff(15)\n\tuntil(30, d.Arrived)\n\tfor _, 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}} {\n\t\t// Arrived means the autopilot holds our last target. Otherwise a\n\t\t// failsafe owns the vehicle or it cannot hold: never override it.\n\t\tif !d.Arrived() {\n\t\t\tbreak\n\t\t}\n\t\td.GoTo(p)\n\t\tuntil(90, func() bool { return d.State().Mode != drone.GoingTo })\n\t\tif d.Arrived() {\n\t\t\tr.Waypoints++\n\t\t}\n\t}\n\tif d.Arrived() {\n\t\td.ReturnHome()\n\t}\n\tuntil(240, func() bool { s := d.State(); return s.Landed || s.Mode == drone.Crashed })\n\tst := d.State()\n\tr.Touchdown, r.HomeDist, r.Battery = -prevVz, st.Pos.Horizontal().Len(), st.Battery\n\tr.Crashed, r.Final = st.Mode == drone.Crashed, st\n\treturn sim, r\n}\n\n// Check returns the invariants and expectations a run broke.\nfunc Check(sc Scenario, r Result) []string {\n\tvar failed []string\n\tif sc.Complete != (r.Waypoints == 4) {\n\t\tfailed = append(failed, \"mission\")\n\t}\n\tif r.Crashed || !r.Final.Landed {\n\t\tfailed = append(failed, \"landed\")\n\t}\n\tif r.Outside > 0 {\n\t\tfailed = append(failed, \"fence\")\n\t}\n\tif r.MaxSpeed > 10.5 {\n\t\tfailed = append(failed, \"speed\")\n\t}\n\tif r.Touchdown > 1.5 {\n\t\tfailed = append(failed, \"touchdown\")\n\t}\n\tif r.HomeDist > 3 {\n\t\tfailed = append(failed, \"home\")\n\t}\n\tif r.Battery < 10 {\n\t\tfailed = append(failed, \"reserve\")\n\t}\n\treturn failed\n}\n\nfunc main() {\n\tscenarios := []Scenario{\n\t\t{Name: \"calm\", Battery: 100, Seed: 1, Complete: true},\n\t\t{Name: \"crosswind 5\", Wind: drone.Vec3{Y: 5}, Battery: 100, Seed: 1, Complete: true},\n\t\t{Name: \"gusty 6+3\", Wind: drone.Vec3{X: -6}, Gust: 3, Battery: 100, Seed: 2, Complete: true},\n\t\t{Name: \"storm 10+4\", Wind: drone.Vec3{X: 10}, Gust: 4, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"gale 14+4\", Wind: drone.Vec3{X: 14}, Gust: 4, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"wind 20\", Wind: drone.Vec3{X: 20}, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"battery 40\", Battery: 40, Seed: 4, Complete: true},\n\t\t{Name: \"battery 30 wind\", Wind: drone.Vec3{X: 6}, Battery: 30, Seed: 5, Complete: false},\n\t}\n\tfmt.Printf(\"%-16s  %-3s  %4s  %8s  %5s  %7s  %6s  %s\\n\", \"scenario\", \"wps\", \"vmax\", \"outside\", \"touch\", \"home\", \"batt\", \"result\")\n\tvar last *drone.Sim\n\tfor _, sc := range scenarios {\n\t\tsim, r := Fly(sc)\n\t\tverdict := \"PASS\"\n\t\tif failed := Check(sc, r); len(failed) > 0 {\n\t\t\tverdict = \"FAIL \" + strings.Join(failed, \",\")\n\t\t}\n\t\tfmt.Printf(\"%-16s  %d/4  %4.1f  %6.2f m  %5.1f  %5.1f m  %5.1f%%  %s\\n\",\n\t\t\tsc.Name, r.Waypoints, r.MaxSpeed, r.Outside, r.Touchdown, r.HomeDist, r.Battery, verdict)\n\t\tlast = sim\n\t}\n\n\t// Same seed, same inputs, same flight: bit for bit.\n\t_, a := Fly(scenarios[2])\n\t_, b := Fly(scenarios[2])\n\tfmt.Printf(\"gusty run twice: identical final state %v (%v, %.4f%%)\\n\", a.Final == b.Final, a.Final.Pos, a.Final.Battery)\n\n\tif err := last.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A scenario matrix","walkthrough":"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."},{"body":"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.","code":"func TestSurveyScenarios(t *testing.T) {\n\tfor _, sc := range scenarios {\n\t\tt.Run(sc.Name, func(t *testing.T) {\n\t\t\tt.Parallel() // each scenario builds its own Sim\n\t\t\t_, r := Fly(sc)\n\t\t\tfor _, broken := range Check(sc, r) {\n\t\t\t\tt.Errorf(\"%s: %+v\", broken, r)\n\t\t\t}\n\t\t})\n\t}\n}","language":"go","title":"From a program to go test","walkthrough":"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."},{"body":"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.","title":"SITL, HIL and CI"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Testing drone software: seeded scenarios, invariants, SITL, HIL and CI","unitID":"drones-missions","wrongAnswers":["Only the final position, with no other checks","Only that the program exits without an error"]},{"conceptTag":"drones.rangefinders","designGuide":{"cautions":["One horizontal plane: lower obstacles and wires are invisible.","Gaps between beams can hide a thin mast entirely."],"cost":"A scanner and its driver, a clustering and filtering pass per scan, and a second sensor for what the scan plane misses.","family":"drones","flow":["Scan n beams","Cluster hits by gap","Median per beam","Points via position"],"ratings":[],"strengths":["Ranges are good to centimetres, independent of GPS error.","Clustering and OBSTACLE_DISTANCE packing are cheap every scan."]},"hint":"Think about what the sensor reports when no pulse comes back, and what averaging 40 m into a real 18 m reading would do.","id":"drones.rangefinders","introduction":"GPS tells a drone where it is; a rangefinder tells it how far away things are. Single-beam rangefinders and spinning lidars time a light pulse along a narrow beam, so every reading is a distance along one direction, valid between a minimum and a maximum range. Turning readings into obstacles is where the subtle bugs live: the maximum reading means that nothing was seen, beams leave gaps between them, a horizontal scan sees one thin slice of the world, and a few bad returns in every scan are normal.","nuance":"The maximum is a code for 'no echo', not a distance. OBSTACLE_DISTANCE uses max_distance + 1 for no obstacle and UINT16_MAX for unknown; averaging either with real ranges invents or hides obstacles.","objective":"Model a rangefinder as a ray with a maximum range and noise, turn a lidar scan into clustered obstacle points in local coordinates, reject dropouts and spurious returns with a median, pack the result as MAVLink OBSTACLE_DISTANCE, and name what a horizontal scan cannot see.","question":"A 360-degree lidar with a 40 m maximum range reads exactly 40 m on most beams. How should avoidance code treat those readings?","references":["https://mavlink.io/en/messages/common.html#OBSTACLE_DISTANCE","https://ardupilot.org/copter/docs/common-proximity-landingpage.html","https://en.wikipedia.org/wiki/Lidar","https://en.wikipedia.org/wiki/Median_filter"],"reviewAnswer":"No echo within range: free, not an obstacle at 40 m","reviewPrompt":"What does a 40 m reading mean?","sections":[{"body":"A lidar measures the round-trip time of a laser pulse, so the distance is c t / 2; sonar does the same with sound and radar with radio. A single-point rangefinder looks down for height above ground or forward for obstacles; a 360-degree scanner spins one beam or combines several fixed sensors, and ArduPilot accepts such scanners as proximity sensors. Every reading is valid between a minimum and a maximum range. Closer than the minimum, further than the maximum, off a black, wet or glancing surface, or into bright sunlight, no echo returns. Real beams also diverge, so the footprint grows with distance and a beam that half-hits an edge can report a distance in between. The simulator's Range is an ideal ray at the drone's altitude with about 3 cm of noise that reads drone.RangeMax, 40 m, when nothing is hit; Scan(n) takes n readings counter-clockwise from east, aligned with the world. MAVLink carries one reading in DISTANCE_SENSOR (min_distance, max_distance, current_distance in cm and the orientation) and a whole scan in OBSTACLE_DISTANCE: 72 distances in cm, index 0 at north by default, increments clockwise, 0 for touching, max_distance + 1 for no obstacle and UINT16_MAX for unknown.","title":"Rays, beams and maximum range"},{"body":"A 2D lidar measures one plane at the drone's altitude. Anything lower than the drone, a tree, a roof, a person, is invisible until the drone descends into its height, so descent and landing need a downward rangefinder, a map or a camera. Wires, branches and overhangs above or below the plane escape it too, and glass or black surfaces may return nothing. Between beams there are gaps: with spacing d theta the beams are r d theta apart at range r, 0.35 m at 20 m for 1 degree and 1.75 m for 5 degrees, wide enough to miss a mast. On a real vehicle the scanner is fixed to the body, so a beam's world heading is the yaw plus the beam angle, and when the drone pitches 15 degrees to accelerate, the plane tilts with it: from 10 m up its beams meet the ground about 37 m ahead, and the ground looks like a wall. ArduPilot offers PRX_IGN_GND to drop such returns with the help of a downward rangefinder, and exclusion sectors (PRXx_IGN_ANGx, PRXx_IGN_WIDx) for legs or masts that block the scanner's view.","title":"What a horizontal scan cannot see"},{"body":"The world holds a 30 m tower of radius 3 m, a mast of radius 0.3 m, a 7 m tree and a hangar. From home at 10 m the program scans 360 beams and groups the hits into clusters: a new cluster starts after a miss, or where neighbouring points are further apart than 0.5 m plus 10 percent of the range, because points spread out with distance and jump where a beam grazes an edge. Each cluster's nearest point is converted into local coordinates twice, from the true position and from GPS, as the coordinates lesson's local frame would hold it. Then it counts hits at five resolutions, flies east scanning every 4 s, hovers for five 72-beam scans with dropouts (6 percent) and spurious short returns (3 percent) added from a seeded math/rand/v2 source, because the simulator's rangefinder is cleaner than a real one, compares a single scan, the mean and the median of five against the clean readings, packs the median scan as OBSTACLE_DISTANCE, and finally descends beside the tree.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math/rand/v2\"\n\t\"slices\"\n\n\t\"gopherforge.app/drone\"\n)\n\nvar world = []drone.Obstacle{\n\t{Name: \"tower\", X: 30, Y: 14, Radius: 3, Height: 30},\n\t{Name: \"mast\", X: 16, Y: -12, Radius: 0.3, Height: 25},\n\t{Name: \"tree\", X: 22, Y: -6, Radius: 2.5, Height: 7},\n\t{Name: \"hangar\", X: 62, Y: -15, Radius: 7, Height: 12},\n}\n\n// heading of beam i of an n-beam scan: counter-clockwise from east.\nfunc heading(i, n int) float64 { return 2 * math.Pi * float64(i%n) / float64(n) }\n\n// Point turns one reading into an obstacle point relative to the drone, on\n// the local east-north axes. Scan is world-aligned, so no yaw is added.\nfunc Point(r, h float64) drone.Vec3 { return drone.Vec3{X: r * math.Cos(h), Y: r * math.Sin(h)} }\n\n// A Cluster is a run of neighbouring beams whose points lie close together.\ntype Cluster struct {\n\tFirst, Last int        // beam indices (Last may pass n: it wraps)\n\tNear        float64    // shortest range, m\n\tBearing     float64    // heading of the shortest range, degrees\n\tAt          drone.Vec3 // nearest point, relative to the drone\n}\n\n// Clusters groups hits (readings under RangeMax) into objects. A new one starts\n// after a miss, or where neighbouring points lie over 0.5 m + 10% of r apart.\nfunc Clusters(scan []float64) []Cluster {\n\tn := len(scan)\n\thit := func(i int) bool { return scan[i%n] < drone.RangeMax }\n\tpt := func(i int) drone.Vec3 { return Point(scan[i%n], heading(i, n)) }\n\tstart := 0\n\tfor start < n && hit(start) {\n\t\tstart++\n\t}\n\tvar out []Cluster\n\tfor i := start; i < start+n; i++ {\n\t\tif !hit(i) {\n\t\t\tcontinue\n\t\t}\n\t\tr, deg := scan[i%n], 360*float64(i%n)/float64(n)\n\t\tif k := len(out) - 1; k >= 0 && out[k].Last == i-1 && pt(i-1).Sub(pt(i)).Len() < 0.5+0.1*r {\n\t\t\tc := &out[k]\n\t\t\tif c.Last = i; r < c.Near {\n\t\t\t\tc.Near, c.Bearing, c.At = r, deg, pt(i)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, Cluster{First: i, Last: i, Near: r, Bearing: deg, At: pt(i)})\n\t}\n\treturn out\n}\n\n// name is a truth check only: the obstacle whose surface passes near p.\nfunc name(p drone.Vec3) string {\n\tfor _, o := range world {\n\t\tif math.Abs(math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius) < 0.5 {\n\t\t\treturn o.Name\n\t\t}\n\t}\n\treturn \"?\"\n}\n\n// ObstacleDistance packs a 72-beam scan as MAVLink OBSTACLE_DISTANCE does:\n// cm, sector 0 north, 5 degrees clockwise, max_distance+1 for \"no obstacle\".\nfunc ObstacleDistance(scan []float64) (out [72]uint16) {\n\tfor j := range out {\n\t\tr := scan[(18-j+72)%72] // north is beam 18 counter-clockwise from east\n\t\tif r >= drone.RangeMax {\n\t\t\tr = drone.RangeMax + 0.01\n\t\t}\n\t\tout[j] = uint16(math.Round(r * 100))\n\t}\n\treturn out\n}\n\nfunc median(v []float64) float64 { s := slices.Sorted(slices.Values(v)); return s[len(s)/2] }\nfunc mean(v []float64) float64 {\n\tsum := 0.0\n\tfor _, x := range v {\n\t\tsum += x\n\t}\n\treturn sum / float64(len(v))\n}\nfunc xy(v drone.Vec3) string { return fmt.Sprintf(\"(%.1f, %.1f)\", v.X, v.Y) }\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 1.5, Y: 0.5}, Gust: 0.5, Obstacles: world, Seed: 11})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tfly := func(p drone.Vec3) { d.GoTo(p); sim.RunUntil(30, func(float64) bool { return d.Arrived() }) }\n\n\tfmt.Println(\"from home at 10 m, 360 beams:\")\n\thits := 0\n\tfor _, c := range Clusters(d.Scan(360)) {\n\t\tpos, gps := d.State().Pos, d.Telemetry().GPS\n\t\thits += c.Last - c.First + 1\n\t\tfmt.Printf(\"  %-6s %2d beams  %4.1f m at %3.0f deg  point %v, via GPS %v\\n\",\n\t\t\tname(pos.Add(c.At)), c.Last-c.First+1, c.Near, c.Bearing, xy(pos.Add(c.At)), xy(gps.Add(c.At)))\n\t}\n\tfmt.Printf(\"  the other %d beams read %.0f m: no echo, nothing within range\\n\", 360-hits, drone.RangeMax)\n\n\tfmt.Println(\"beams that hit, by scan resolution:\")\n\tfor _, n := range []int{8, 16, 36, 72, 360} {\n\t\tcount := map[string]int{}\n\t\tfor i, r := range d.Scan(n) {\n\t\t\tif r < drone.RangeMax {\n\t\t\t\tcount[name(d.State().Pos.Add(Point(r, heading(i, n))))]++\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"  %3d beams %4.1f deg apart, %5.2f m apart at 20 m: tower %2d, mast %d\\n\",\n\t\t\tn, 360/float64(n), 20*2*math.Pi/float64(n), count[\"tower\"], count[\"mast\"])\n\t}\n\n\tfmt.Println(\"flying east at 4 m/s along y = 0, a scan every 4 s:\")\n\td.SetVelocity(drone.Vec3{X: 4}, 0)\n\tfor range 5 {\n\t\tp := d.State().Pos\n\t\tline := fmt.Sprintf(\"  x=%4.1f\", p.X)\n\t\tfor _, c := range Clusters(d.Scan(360)) {\n\t\t\tline += fmt.Sprintf(\"  %s %.1f m at %.0f\", name(p.Add(c.At)), c.Near, c.Bearing)\n\t\t}\n\t\tfmt.Println(line)\n\t\tsim.Run(4, nil)\n\t}\n\n\tfly(drone.Vec3{X: 45, Z: 10})\n\tfmt.Println(\"hover at (45, 0): 5 scans of 72 beams, with dropouts and spurious returns added\")\n\trng := rand.New(rand.NewPCG(1, 2))\n\tclean, noisy := make([][]float64, 72), make([][]float64, 72)\n\tfor range 5 {\n\t\tfor i, r := range d.Scan(72) {\n\t\t\tclean[i] = append(clean[i], r)\n\t\t\tswitch u := rng.Float64(); {\n\t\t\tcase u < 0.06:\n\t\t\t\tr = drone.RangeMax // no return: a dark or glancing surface\n\t\t\tcase u < 0.09:\n\t\t\t\tr = 0.5 + 2.5*rng.Float64() // dust, rain, a bird\n\t\t\t}\n\t\t\tnoisy[i] = append(noisy[i], r)\n\t\t}\n\t\tsim.Run(0.1, nil)\n\t}\n\tshown, filtered := map[bool]bool{}, make([]float64, 72)\n\tfor i := range noisy {\n\t\ttruth, onObstacle := median(clean[i]), median(clean[i]) < drone.RangeMax\n\t\tfiltered[i] = median(noisy[i])\n\t\tif !shown[onObstacle] && (onObstacle && slices.Max(noisy[i]) == drone.RangeMax || !onObstacle && slices.Min(noisy[i]) < 5) {\n\t\t\tshown[onObstacle] = true\n\t\t\tfmt.Printf(\"  beam %2d truth %4.1f  raw %4.1f  mean %4.1f  median %4.1f\\n\", i, truth, noisy[i], mean(noisy[i]), median(noisy[i]))\n\t\t}\n\t}\n\tnames := []string{\"single scan\", \"mean of 5\", \"median of 5\"}\n\tfor k, reduce := range []func([]float64) float64{func(v []float64) float64 { return v[0] }, mean, median} {\n\t\tshort, long := 0, 0\n\t\tfor i := range noisy {\n\t\t\tswitch truth, got := median(clean[i]), reduce(noisy[i]); {\n\t\t\tcase got < truth-0.5:\n\t\t\t\tshort++\n\t\t\tcase got > truth+0.5:\n\t\t\t\tlong++\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"  %-11s  phantom obstacles %2d  obstacles too far or gone %d\\n\", names[k], short, long)\n\t}\n\tline := \"  OBSTACLE_DISTANCE, sectors with an obstacle (cm):\"\n\tfor j, v := range ObstacleDistance(filtered) {\n\t\tif v <= drone.RangeMax*100 {\n\t\t\tline += fmt.Sprintf(\" %d:%d\", j, v)\n\t\t}\n\t}\n\tfmt.Println(line)\n\n\tfly(drone.Vec3{X: 22, Y: -1.5, Z: 10})\n\tsouth := -math.Pi / 2\n\tfmt.Printf(\"beside the 7 m tree at 10 m: range south %.1f m; descend at 1 m/s\\n\", d.Range(south))\n\td.SetVelocity(drone.Vec3{Z: -1}, 0)\n\tsim.RunUntil(8, func(float64) bool { return d.Range(south) < drone.RangeMax })\n\tfmt.Printf(\"  first echo at z=%.1f m: the tree is %.1f m away\\n\", d.State().Pos.Z, d.Range(south))\n\td.Land()\n\tsim.RunUntil(30, func(float64) bool { return d.State().Landed })\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Scan, cluster, filter, pack","walkthrough":"From home the tower is 11 beams wide, 30.1 m away at 25 degrees, and its nearest point is (27.2, 12.7) from the true position but (28.1, 12.9) via GPS: the range is good to centimetres, the map point only to the position estimate. The mast shows in a single beam at 19.7 m, and the other 348 beams read 40 m. The table explains it: with 72 beams 1.75 m apart at 20 m the mast gets no hit, and with 8 beams even the tower gets none. On the way east the tree never appears: at 7 m it is below the 10 m scan plane, although the track passes 3.5 m from its edge. The hangar first shows at x=31.3, 27.2 m away. Beam 10 sees nothing; one spurious 1.3 m return drags the mean of 40.0, 40.0, 40.0, 1.3, 40.0 to 32.3 m, a phantom obstacle, while the median stays 40.0. Beam 26 sees the hangar at 17.8 m and one dropout pushes its mean to 22.3 m. Over 72 beams the single scan has 2 phantom obstacles, the mean 10 phantoms and 2 obstacles too far, the median none. OBSTACLE_DISTANCE fills sectors 23 to 29 (the hangar, south-east) and 62 to 64 (the tower, north-west), counted clockwise from north. Beside the tree the reading is 40.0 m at 10 m; the first echo comes at z=7.0 m, 2.2 m away."},{"body":"Real rangefinders produce outliers in both directions: dropouts that read as the maximum or as an invalid code, and spurious short returns from dust, rain, insects or the vehicle's own legs. Treat the maximum as 'no echo within range', never as an obstacle at 40 m, and never average it with real distances: one dropout in five moved the hangar 4.5 m further away, one spurious return in five invented an obstacle at 32 m. A median of the last 3 or 5 readings per beam rejects isolated outliers either way, at the price of a delay: a median of 5 follows a real change only when 3 samples are new, two periods late, 0.2 s at 10 Hz or 1.6 m at 8 m/s. A median across neighbouring beams has no delay but erases anything one beam wide, which is exactly what the mast was. Keep 'unknown' separate from 'free': OBSTACLE_DISTANCE has UINT16_MAX for it, and PX4's collision prevention by default will not move towards directions without data. ArduPilot also low-pass filters proximity readings (PRX_FILT), which smooths noise but bends towards outliers instead of rejecting them.","title":"Median filters and the meaning of 40 m"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go (its Square helper is unused here) and tap Run. Open Output: the replay of flight.gfflight draws the four obstacles as grey discs with their heights, the trail east past the tower and the hangar, the hover at (45, 0) and the descent beside the 7 m tree, which the altitude strip shows passing the tree's height where the first echo came. Change the fly-past scan to 72 beams and watch the mast vanish, or move the spurious band's upper limit from 0.09 to 0.3 and see when a median of five stops coping.","title":"Fly it in GopherForge"}],"takeaway":"A rangefinder reading is a distance along one ray between a minimum and a maximum range. Treat the maximum as no echo, group hits into clusters with a range-dependent gap, place points with the position estimate, reject outliers with a median per beam, and remember what the scan plane and the gaps between beams cannot see.","title":"Rangefinders and lidar scans: rays, maximum range, noise and what a horizontal scan misses","unitID":"drones-autonomy","wrongAnswers":["As obstacles 40 m away, averaged with the other readings","As sensor faults, so the whole scan is discarded"]},{"conceptTag":"drones.reactive-avoidance","designGuide":{"cautions":["Sees only the present: dead ends and long detours are not foreseen.","Reaction time and braking must be measured, not guessed."],"cost":"A 360-degree range sensor at 10 Hz or more, a corridor check and speed limit per scan, and measured braking and latency figures.","family":"drones","flow":["Scan at a fixed rate","Free distance in corridor","Speed from free distance","Sidestep when blocked"],"ratings":[],"strengths":["Needs no map and reacts to obstacles nobody charted.","The speed limit is provably safe for a measured reaction and braking."]},"hint":"Compare the 3 m threshold with v times the reaction time plus v squared over 2a at both speeds.","id":"drones.reactive-avoidance","introduction":"Reactive avoidance answers one question many times a second: given what the sensors see now, how fast may I fly in this direction? It needs no map and no plan, which makes it the last line of defence under every planner and the whole of the avoidance in many simple systems. Its failures are all about time and distance: a threshold that ignores speed, a ray that ignores the vehicle's width, a decision that comes one sensor period too late.","nuance":"At 8 m/s with 0.3 s and 5 m/s2 the drone needs 8.8 m to stop. Limiting speed so that this distance always fits in the free corridor, v = k (free - d_stop), keeps it safe at every speed.","objective":"Check the corridor a drone sweeps instead of a single ray, limit speed in proportion to the free distance with a gain that is provably safe for a measured reaction time and braking, and get past a building with stop-and-sidestep, without a map.","question":"A drone stops whenever its forward ray reads under 3 m. It works at 2 m/s but hits a wall at 8 m/s. What should limit its speed instead?","references":["https://docs.px4.io/main/en/computer_vision/collision_prevention","https://ardupilot.org/copter/docs/common-simple-object-avoidance.html","https://en.wikipedia.org/wiki/Braking_distance"],"reviewAnswer":"Stopping distance must fit in the free corridor","reviewPrompt":"What caps speed near obstacles?","sections":[{"body":"The geofencing lesson predicted a breach with the stopping distance v t_r + v squared / (2a). An obstacle is a fence that the sensor redraws ten times a second, and the same formula decides everything here. The reaction time t_r adds the sensor period, the processing, the velocity loop's response and the command latency; a is the braking you measured, reduced for tailwind and payload. With 0.3 s and 5 m/s2, 8 m/s needs 8.8 m. PX4's collision prevention states the goal in these words: the velocity is restricted so that the vehicle stops in time to keep the distance CP_DIST, and its CP_DELAY parameter is the sensor plus velocity-tracking delay, typically 0.1 to 0.5 s for tracking and up to 0.2 s more for external vision. The sensor's range then caps the speed: if it sees 5 m and you must stop 3 m short, 0.3 v + v squared / 10 must stay under 2 m, so no more than 3.2 m/s whatever the airframe can do.","title":"Stopping distance, now against obstacles"},{"body":"A single ray along the direction of travel misses the tree that will clip the right-hand propeller. Check the corridor the vehicle sweeps instead: every scan point ahead whose sideways offset from the line of travel is smaller than the half-width (contact radius plus a margin for position and tracking error) limits the free distance to its distance along the line. Then let the free distance set the speed: v = min(vmax, k (free - d_stop)). That zone is safe if at every speed the stopping distance fits into what is left, k t_r + k squared x / (2a) <= 1 for x = free - d_stop, and because k x never exceeds vmax this holds whenever k <= 1 / (t_r + vmax / (2a)): 0.91 per second here. The zone then begins exactly the stopping distance at vmax before d_stop. The square-root profile v = a (sqrt(t_r squared + 2x / a) - t_r) is the fastest safe one; the proportional zone is simpler, slower near obstacles, and approaches the stop exponentially with time constant 1/k.","title":"Corridors and a slow-down zone"},{"body":"The program prints the stopping distances for the design values and measures how far the simulator's airframe really brakes from each speed. A naive run then flies at 8 m/s towards a goal 75 m east, behind a warehouse 16 m across, reading one ray straight ahead at 5 Hz and stopping when it reads under 3 m. The second run scans 360 beams at 10 Hz, flies the corridor speed limit towards the goal and, when the limit falls under 0.5 m/s with the goal still beyond the obstacle, compares the free distance to the left and right, sidesteps at up to 2 m/s towards the side with more room, and turns back to the goal only when the corridor to it is clear for the whole sensor range. A pole north of the line makes the choice matter. A truth check records the closest approach to any surface.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nvar (\n\tworld = []drone.Obstacle{\n\t\t{Name: \"warehouse\", X: 40, Radius: 8, Height: 20},\n\t\t{Name: \"pole\", X: 28, Y: 9, Radius: 1.5, Height: 15},\n\t}\n\tgoal = drone.Vec3{X: 75, Z: 10}\n)\n\nconst (\n\treact  = 0.3 // s: sensor period, processing and command latency\n\tbrake  = 5.0 // m/s2: the braking we design for, below what the airframe can do\n\tvmax   = 8.0 // m/s cruise\n\tdStop  = 3.0 // m: where we want to come to rest in front of an obstacle\n\thalfW  = 1.5 // m: half-width of the corridor the drone sweeps (0.3 contact + margin)\n\tsensor = 0.1 // s: one 360-beam scan every 0.1 s (10 Hz)\n)\n\n// Stopping is the distance covered from seeing an obstacle to standing still.\nfunc Stopping(v float64) float64 { return v*react + v*v/(2*brake) }\n\n// Free is how far the drone can fly along direction u (a unit vector) before\n// a scan point enters its corridor: points ahead, within halfW of the line.\nfunc Free(scan []float64, u drone.Vec3) float64 {\n\tfree := drone.RangeMax\n\tfor i, r := range scan {\n\t\ta := 2 * math.Pi * float64(i) / float64(len(scan))\n\t\tp := drone.Vec3{X: r * math.Cos(a), Y: r * math.Sin(a)}\n\t\talong, across := p.X*u.X+p.Y*u.Y, math.Abs(p.X*u.Y-p.Y*u.X)\n\t\tif r < drone.RangeMax && along > 0 && across < halfW {\n\t\t\tfree = math.Min(free, along)\n\t\t}\n\t}\n\treturn free\n}\n\n// k keeps the proportional slow-down zone safe: at vmax the drone must still\n// stop within the zone, so k <= 1/(react + vmax/(2 brake)).\nvar k = 1 / (react + vmax/(2*brake))\n\n// Speed is the slow-down zone: proportional to the free distance left.\nfunc Speed(free float64) float64 { return math.Max(0, math.Min(vmax, k*(free-dStop))) }\n\nfunc unit(v drone.Vec3) drone.Vec3 { return v.Horizontal().Scale(1 / v.Horizontal().Len()) }\nfunc left(u drone.Vec3) drone.Vec3 { return drone.Vec3{X: -u.Y, Y: u.X} }\n\n// clearance is a truth check: distance from the drone to the nearest surface.\nfunc clearance(p drone.Vec3) float64 {\n\tc := math.Inf(1)\n\tfor _, o := range world {\n\t\tc = math.Min(c, math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius)\n\t}\n\treturn c\n}\n\nfunc newSim() (*drone.Sim, *drone.Drone) {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 1, Y: 2}, Gust: 1, Obstacles: world, Seed: 21})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tsim.Waypoint(goal) // drawn on the replay's map\n\treturn sim, d\n}\n\nfunc hit(sim *drone.Sim) string {\n\tfor _, e := range sim.Events() {\n\t\tif strings.HasPrefix(e.Text, \"hit \") {\n\t\t\treturn fmt.Sprintf(\"t=%.1f s %s\", e.T, e.Text)\n\t\t}\n\t}\n\treturn \"no collision\"\n}\n\nfunc main() {\n\tfmt.Printf(\"stopping distance with %.1f s reaction and %.0f m/s2 braking:\\n\", react, brake)\n\tfmt.Println(\"  v m/s  reaction  braking  total   simulator braking\")\n\tfor _, v := range []float64{2, 4, 6, 8, 10} {\n\t\tsim := drone.New(drone.Config{Seed: 1})\n\t\td := sim.Drone()\n\t\td.Arm()\n\t\td.TakeOff(10)\n\t\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\t\td.SetVelocity(drone.Vec3{X: v}, 0)\n\t\tsim.Run(6, nil)\n\t\tx := d.State().Pos.X\n\t\td.SetVelocity(drone.Vec3{}, 0)\n\t\tsim.RunUntil(10, func(float64) bool { return d.State().Vel.Len() < 0.05 })\n\t\tfmt.Printf(\"  %5.0f  %6.1f m  %5.1f m  %4.1f m  %5.1f m\\n\", v, v*react, v*v/(2*brake), Stopping(v), d.State().Pos.X-x)\n\t}\n\n\tfmt.Println(\"naive: 8 m/s at the goal, stop when the ray ahead reads under 3 m (5 Hz)\")\n\tsim, d := newSim()\n\td.SetVelocity(drone.Vec3{X: vmax}, 0)\n\tstopped := false\n\tsim.RunUntil(20, func(t float64) bool {\n\t\tif !stopped && math.Mod(math.Round(t/sim.Dt()), 10) == 0 { // every 0.2 s\n\t\t\tif r := d.Range(0); r < 3 {\n\t\t\t\tstopped = true\n\t\t\t\tfmt.Printf(\"  t=%.1f s x=%.1f m  ahead %.1f m at %.1f m/s: stop\\n\", t, d.State().Pos.X, r, d.State().Vel.Len())\n\t\t\t\td.SetVelocity(drone.Vec3{}, 0)\n\t\t\t}\n\t\t}\n\t\treturn d.State().Mode == drone.Crashed\n\t})\n\tsim.Run(2, nil) // the crashed drone falls\n\tfmt.Printf(\"  %s\\n\", hit(sim))\n\tnaive := sim\n\n\tfmt.Printf(\"avoid: corridor %.1f m each side, speed min(%.0f, %.2f (free - %.0f m)), scans at 10 Hz\\n\", halfW, vmax, k, dStop)\n\tsim, d = newSim()\n\tmode, side, minC, path, last := \"goal\", drone.Vec3{}, math.Inf(1), 0.0, d.State().Pos\n\tsim.RunUntil(90, func(t float64) bool {\n\t\tst := d.State()\n\t\tminC, path, last = math.Min(minC, clearance(st.Pos)), path+st.Pos.Sub(last).Horizontal().Len(), st.Pos\n\t\tif math.Mod(math.Round(t/sim.Dt()), 5) != 0 {\n\t\t\treturn false\n\t\t}\n\t\tscan, toGoal := d.Scan(360), goal.Sub(st.Pos).Horizontal()\n\t\tu := unit(toGoal)\n\t\tfree := Free(scan, u)\n\t\tif math.Mod(math.Round(t/sim.Dt()), 100) == 0 {\n\t\t\tfmt.Printf(\"  t=%4.1f s %v %-8s free %4.1f m  speed %3.1f m/s\\n\", t, st.Pos, mode, free, st.Vel.Horizontal().Len())\n\t\t}\n\t\tswitch mode {\n\t\tcase \"goal\":\n\t\t\tif Speed(free) < 0.5 && free < toGoal.Len() {\n\t\t\t\tn, s := Free(scan, left(u)), Free(scan, left(u).Scale(-1))\n\t\t\t\tmode, side = \"sidestep\", left(u)\n\t\t\t\tname := \"north\"\n\t\t\t\tif s > n {\n\t\t\t\t\tside, name = side.Scale(-1), \"south\"\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"  t=%4.1f s %v blocked: free %.1f m; north %.1f m, south %.1f m: sidestep %s\\n\", t, st.Pos, free, n, s, name)\n\t\t\t}\n\t\tcase \"sidestep\":\n\t\t\tif free >= math.Min(toGoal.Len(), drone.RangeMax) {\n\t\t\t\tmode = \"goal\"\n\t\t\t\tfmt.Printf(\"  t=%4.1f s %v corridor to the goal clear for %.1f m: go\\n\", t, st.Pos, free)\n\t\t\t}\n\t\t}\n\t\tif mode == \"goal\" {\n\t\t\td.SetVelocity(u.Scale(math.Min(Speed(free), toGoal.Len())), 0)\n\t\t} else {\n\t\t\td.SetVelocity(side.Scale(math.Min(2, Speed(Free(scan, side)))), 0)\n\t\t}\n\t\treturn toGoal.Len() < 3 || st.Mode == drone.Crashed\n\t})\n\td.GoTo(goal) // the last metres: let the position loop stop on the goal\n\tsim.RunUntil(10, func(float64) bool {\n\t\tpath, last = path+d.State().Pos.Sub(last).Horizontal().Len(), d.State().Pos\n\t\treturn d.Arrived()\n\t})\n\tfmt.Printf(\"  %s; t=%.1f s at %v, closest surface %.1f m, path %.1f m (straight %.0f m)\\n\",\n\t\thit(sim), sim.Time(), d.State().Pos, minC, path, goal.Horizontal().Len())\n\td.Land()\n\tsim.RunUntil(30, func(float64) bool { return d.State().Landed })\n\tif err := naive.SaveAs(\"naive\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A naive stop, then corridor and sidestep","walkthrough":"The design figures are deliberately pessimistic: at 8 m/s they give 8.8 m (2.4 m reaction, 6.4 m braking) while the simulator brakes in 4.7 m, at 10 m/s 13.0 against 6.9 m. The naive run sees 2.0 m ahead at t=9.0 s while still doing 8.1 m/s; braking needs 4.7 m, and the next line is 't=9.2 s hit warehouse'. At 8 m/s a 5 Hz sensor moves 1.6 m between readings, so the reading that trips a 3 m threshold can be anywhere from 1.4 to 3 m. The avoiding run cruises at 8.1 m/s with 10.6 m free at t=8.0 s, slows inside the zone and is blocked at t=9.9 s at x=28.4 with 3.5 m free: 7.4 m to the north, where the pole stands, 40.0 m to the south, so it sidesteps south at about 2 m/s. At t=16.7 s, 13.5 m south of the line, the corridor is clear for 40.0 m and it flies the diagonal at 8 m/s, stopping on the goal at (74.6, -0.2) at t=24.5 s with 92.1 m of path for 75 m straight, never closer than 2.3 m to a surface."},{"body":"Stop-and-sidestep is the simplest way past an obstacle, and real autopilots offer similar behaviours in pilot-assisted modes. ArduPilot's simple avoidance in Loiter stops or slides along the obstacle (AVOID_BEHAVE), keeps AVOID_MARGIN and backs away at AVOID_BACKUP_SPD if something comes closer. PX4's collision prevention in Position mode limits the velocity and may turn the commanded direction by up to CP_GUIDE_ANG towards a freer sector; by default it refuses to move towards directions without sensor data. What no reactive method can do is see beyond the present scan: a sidestep can lead into a courtyard with no exit, the side with more room now may be the longer way round, and nothing guarantees arrival. That is why autonomous missions put a planner on top, the A* of the path planning lesson or ArduPilot's BendyRuler and Dijkstra in Auto and Guided, and keep the reactive limit underneath as the layer that never trusts the plan.","title":"Stop, slide or plan"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists naive.gfflight, where the drone reaches the warehouse wall at full speed and falls, and flight.gfflight, with the slow-down, the stop, the sidestep south past the pole and the diagonal to the goal marker. Set react to 0.6 or brake to 3 and watch the zone start earlier, or move the pole south of the line and see the sidestep switch sides.","title":"Fly it in GopherForge"}],"takeaway":"A fixed range threshold is right at one speed only, because braking grows with the square of speed. Check the corridor the vehicle sweeps, limit speed in proportion to the free distance with k no larger than 1 / (t_r + vmax / 2a), let the sensor range cap vmax, and when blocked, sidestep towards the side with more room until the way to the goal is clear.","title":"Reactive avoidance: corridors, slow-down zones and stop-and-sidestep","unitID":"drones-autonomy","wrongAnswers":["A fixed 3 m threshold measured with a faster sensor","The distance to the goal, so it slows down on arrival"]},{"conceptTag":"drones.potential-fields","designGuide":{"cautions":["Concave obstacles create minima that stop the vehicle with no error.","Gains depend on speed, braking and beam count; narrow gaps oscillate."],"cost":"A scan at 10 Hz, a sum over beams per cycle, a progress monitor and an escape behaviour, tuned per airframe and speed.","family":"drones","flow":["Pull towards the goal","Push from scan points","Fly the summed gradient","Escape on no progress"],"ratings":[],"strengths":["A few lines per scan, no map, smooth paths around scattered obstacles.","Any number of obstacles combine in one sum."]},"hint":"Add up the pull towards the goal and the pushes from the three walls at the point where the drone stopped.","id":"drones.potential-fields","introduction":"A potential field treats the goal as a valley and obstacles as hills and lets the vehicle roll downhill: the velocity command is the negative gradient of attraction plus repulsion. It takes a few dozen lines, reacts to every scan and draws smooth curves around scattered obstacles. It also has a famous flaw: wherever the pushes and the pull cancel, the vehicle stops, and a U-shaped building between it and the goal can hold it there indefinitely.","nuance":"Inside the U the walls push back as hard as the goal pulls, so the gradient is zero away from the goal. No gain removes that; it takes an escape such as wall following, or a planner.","objective":"Build an artificial potential field from a goal and rangefinder readings, fly its negative gradient as a velocity command, watch it stall inside a U-shaped obstacle, detect the stall, and escape by wall following, with an honest account of what fields cannot guarantee.","question":"A drone flying a potential field stops inside a U-shaped building that lies between it and the goal, and reports no fault. Why?","references":["https://en.wikipedia.org/wiki/Motion_planning","https://en.wikipedia.org/wiki/Bug_algorithm"],"reviewAnswer":"Where attraction and repulsion cancel: a local minimum","reviewPrompt":"Where do potential fields stall?","sections":[{"body":"The attractive potential is quadratic near the goal, so the pull grows with the distance, and conic beyond a radius, so the pull stays at the cruise speed: here 1 m/s per metre up to 5 m/s. Khatib's repulsive potential (1986) for an obstacle at distance rho inside an influence distance rho0 is (eta/2)(1/rho - 1/rho0) squared; its negative gradient pushes straight away from the obstacle with strength eta (1/rho - 1/rho0) / rho squared, zero at rho0 and unbounded at the surface. A scan gives no obstacle list, only points, so every beam that reads under rho0 adds a push away from its point. The sum, clamped to the cruise speed, becomes the velocity setpoint, the way a companion computer streams setpoints to the autopilot in the cascaded control lesson. The reactive avoidance lesson limited speed along one direction; a field chooses the direction as well.","title":"Attraction, repulsion, gradient"},{"body":"Summing over beams makes the push depend on how many beams hit: a wall that 30 beams see pushes 30 times harder than a pole one beam sees, and doubling the resolution doubles every push. Weight each beam by its angular width, 2 pi / n, so the sum approximates an integral over the field of view, or keep only the nearest point of each cluster. Then tune the repulsion against the cruise speed and the braking. The program uses eta = 300 and rho0 = 8 m at 5 m/s. With eta = 40 the push is too weak to keep a margin and the drone passes within 0.9 m of a trunk and 0.7 m of a wall, close to the 0.3 m contact distance; with eta = 1000 it backs off in front of a tree near the line to the goal and makes no progress for seconds. Koren and Borenstein's 1991 analysis lists the classic failures: traps at local minima, no passage between closely spaced obstacles, and oscillation near obstacles and in narrow passages.","title":"Weighting the beams and tuning"},{"body":"Three flights at 10 m use 72-beam scans at 10 Hz. The first crosses four trees with tree 3 exactly on the straight line to the goal and prints a trace every 3 s. The second flies into a U of overlapping 1.5 m cylinders that opens towards the start, with the goal 30 m behind its bottom wall. The program watches progress: if the distance to the goal has not dropped by 0.5 m in 4 s, it prints the attraction, the repulsion and their sum at that moment. Without an escape it keeps flying the field for 20 s more. The third flight escapes by wall following: it keeps the nearest scan point on its right at 3 m while moving at 2.5 m/s, and returns to the field once the goal is closer than where it got stuck and the line to it is clear. A truth check records the closest approach to any surface.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tbeams = 72\n\tka    = 1.0   // 1/s: attraction, m/s per metre to the goal\n\tvmax  = 5.0   // m/s: the attraction saturates here (conic far away)\n\td0    = 8.0   // m: obstacles further than this do not push\n\tkr    = 300.0 // repulsion gain\n\tdw    = 3.0   // m: wall-following standoff\n)\n\nvar goal = drone.Vec3{X: 70, Z: 10}\n\nfunc point(r float64, i int) drone.Vec3 {\n\ta := 2 * math.Pi * float64(i) / beams\n\treturn drone.Vec3{X: r * math.Cos(a), Y: r * math.Sin(a)}\n}\n\nfunc clampLen(v drone.Vec3, max float64) drone.Vec3 {\n\tif l := v.Len(); l > max {\n\t\treturn v.Scale(max / l)\n\t}\n\treturn v\n}\n\n// Attract is minus the gradient of a potential that is quadratic near the\n// goal and conic (constant slope) beyond vmax/ka metres.\nfunc Attract(toGoal drone.Vec3) drone.Vec3 { return clampLen(toGoal.Horizontal().Scale(ka), vmax) }\n\n// Repel sums Khatib's repulsion over the scan points within d0. Each beam is\n// weighted by its angle, so a wall does not push harder because more beams\n// hit it than hit a pole.\nfunc Repel(scan []float64) drone.Vec3 {\n\tvar f drone.Vec3\n\tfor i, r := range scan {\n\t\tif r < d0 {\n\t\t\tp := point(r, i)\n\t\t\tf = f.Sub(p.Scale(kr * (1/r - 1/d0) / (r * r * r) * 2 * math.Pi / beams))\n\t\t}\n\t}\n\treturn f\n}\n\n// Follow keeps the nearest scan point on the right at dw metres.\nfunc Follow(scan []float64) drone.Vec3 {\n\tnear := 0\n\tfor i := range scan {\n\t\tif scan[i] < scan[near] {\n\t\t\tnear = i\n\t\t}\n\t}\n\tn := point(1, near) // unit vector to the wall\n\tt := drone.Vec3{X: -n.Y, Y: n.X}\n\treturn t.Scale(2.5).Add(n.Scale(math.Max(-2, math.Min(2, 1.5*(scan[near]-dw)))))\n}\n\n// Free reports whether the straight line to the goal is clear within range.\nfunc Free(scan []float64, toGoal drone.Vec3) bool {\n\tu := toGoal.Horizontal().Scale(1 / toGoal.Horizontal().Len())\n\tfor i, r := range scan {\n\t\tp := point(r, i)\n\t\talong, across := p.X*u.X+p.Y*u.Y, math.Abs(p.X*u.Y-p.Y*u.X)\n\t\tif r < drone.RangeMax && along > 0 && along < toGoal.Len() && across < 2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc clearance(world []drone.Obstacle, p drone.Vec3) float64 {\n\tc := math.Inf(1)\n\tfor _, o := range world {\n\t\tc = math.Min(c, math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius)\n\t}\n\treturn c\n}\n\n// Fly runs the field at 10 Hz. Without escape it reports a stall and keeps\n// flying the field for 20 s; with escape it follows the wall when progress\n// stops, and returns to the field once the goal is closer and in clear view.\nfunc Fly(label string, world []drone.Obstacle, escape, trace bool) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: -1, Y: 1}, Gust: 0.5, Obstacles: world, Seed: 8})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tsim.Waypoint(goal)\n\tfmt.Println(label)\n\tstart := sim.Time()\n\tmode, best, bestAt, stuckAt, minC, next := \"field\", math.Inf(1), start, 0.0, math.Inf(1), start\n\tsim.RunUntil(150, func(t float64) bool {\n\t\tst := d.State()\n\t\ttoGoal := goal.Sub(st.Pos).Horizontal()\n\t\tminC = math.Min(minC, clearance(world, st.Pos))\n\t\tif toGoal.Len() < 1 || st.Mode == drone.Crashed {\n\t\t\treturn true\n\t\t}\n\t\tif math.Mod(math.Round(t/sim.Dt()), 5) != 0 {\n\t\t\treturn false\n\t\t}\n\t\tscan := d.Scan(beams)\n\t\tif toGoal.Len() < best-0.5 {\n\t\t\tbest, bestAt = toGoal.Len(), t\n\t\t\tif mode == \"stuck\" {\n\t\t\t\tfmt.Printf(\"  t=%4.1f s %v moving towards the goal again\\n\", t-start, st.Pos)\n\t\t\t\tmode = \"field\"\n\t\t\t}\n\t\t}\n\t\tatt, rep := Attract(toGoal), Repel(scan)\n\t\tif trace && t >= next {\n\t\t\tnext += 3\n\t\t\tfmt.Printf(\"  t=%4.1f s %v attraction %.1f, repulsion %.1f, speed %.1f m/s\\n\",\n\t\t\t\tt-start, st.Pos, att.Len(), rep.Len(), st.Vel.Horizontal().Len())\n\t\t}\n\t\tswitch {\n\t\tcase mode == \"stuck\" && t-bestAt > 24:\n\t\t\treturn true\n\t\tcase mode == \"field\" && t-bestAt > 4:\n\t\t\tfmt.Printf(\"  t=%4.1f s %v no progress for 4 s, %.1f m from the goal: attraction %.2f, repulsion %.2f, sum %.2f m/s\\n\",\n\t\t\t\tt-start, st.Pos, toGoal.Len(), att.Len(), rep.Len(), att.Add(rep).Len())\n\t\t\tmode, stuckAt = \"stuck\", toGoal.Len()\n\t\t\tif escape {\n\t\t\t\tmode = \"follow\"\n\t\t\t}\n\t\tcase mode == \"follow\" && toGoal.Len() < stuckAt-1 && Free(scan, toGoal):\n\t\t\tfmt.Printf(\"  t=%4.1f s %v closer than %.1f m and clear: back to the field\\n\", t-start, st.Pos, stuckAt)\n\t\t\tmode, best, bestAt = \"field\", toGoal.Len(), t\n\t\t}\n\t\tif mode == \"follow\" {\n\t\t\td.SetVelocity(Follow(scan), 0)\n\t\t} else {\n\t\t\td.SetVelocity(clampLen(att.Add(rep), vmax), 0)\n\t\t}\n\t\treturn false\n\t})\n\tif goal.Sub(d.State().Pos).Horizontal().Len() < 1 {\n\t\td.Land()\n\t\tsim.RunUntil(30, func(float64) bool { return d.State().Landed })\n\t}\n\tst := d.State()\n\tfmt.Printf(\"  end at t=%.1f s %v, %.1f m from the goal, closest surface %.1f m\\n\",\n\t\tsim.Time()-start, st.Pos, goal.Sub(st.Pos).Horizontal().Len(), minC)\n\treturn sim\n}\n\nfunc main() {\n\tscattered := []drone.Obstacle{\n\t\t{Name: \"tree 1\", X: 18, Y: 5, Radius: 2, Height: 20},\n\t\t{Name: \"tree 2\", X: 30, Y: -4, Radius: 2.5, Height: 20},\n\t\t{Name: \"tree 3\", X: 45, Radius: 2, Height: 20},\n\t\t{Name: \"tree 4\", X: 58, Y: 4, Radius: 1.5, Height: 20},\n\t}\n\tvar cup []drone.Obstacle // a U open to the west: bottom at x=40, arms along y=+-10\n\tfor y := -10.0; y <= 10; y += 2.5 {\n\t\tcup = append(cup, drone.Obstacle{Name: fmt.Sprintf(\"wall %.0f,%.0f\", 40.0, y), X: 40, Y: y, Radius: 1.5, Height: 20})\n\t}\n\tfor x := 25.0; x < 40; x += 2.5 {\n\t\tcup = append(cup, drone.Obstacle{Name: fmt.Sprintf(\"wall %.0f,10\", x), X: x, Y: 10, Radius: 1.5, Height: 20},\n\t\t\tdrone.Obstacle{Name: fmt.Sprintf(\"wall %.0f,-10\", x), X: x, Y: -10, Radius: 1.5, Height: 20})\n\t}\n\ta := Fly(\"four trees, tree 3 on the straight line to the goal:\", scattered, false, true)\n\tb := Fly(\"a U open towards the start, field only:\", cup, false, false)\n\tc := Fly(\"the same U, wall following when stuck:\", cup, true, false)\n\tif err := a.SaveAs(\"field\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := b.SaveAs(\"trapped\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := c.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A field, a trap and an escape","walkthrough":"In the trees the drone cruises at 5.0 m/s; beside tree 2 at (26.1, -1.1) the repulsion reaches 11.9, more than twice the attraction, slows it to 2.3 m/s and pushes it north. That detour means tree 3, on the straight line, is passed on its north side at (46.8, 6.1) at full speed. Tree 4, ahead and slightly to the left, slows it to 1.7 m/s at (53.1, 2.6) before it slips past; it lands 0.9 m from the goal, never closer than 1.6 m to a surface. In the U the forces cancel at (35.4, 0.0): attraction 5.00, repulsion 5.10, sum 0.10 m/s, and 20 s later the drone is still at (35.3, 0.0), 34.7 m from the goal, with no error anywhere. With the escape it follows the wall north around the arm, and at t=30.0 s at (39.7, 14.3) the goal is closer than 34.6 m and in clear view; the field takes it to the goal, where it lands 0.9 m off with 2.3 m of clearance throughout."},{"body":"A local minimum is any point away from the goal where the gradient vanishes; a concave side facing the goal creates one, and an obstacle exactly between vehicle and goal creates a saddle on its axis that only noise or wind breaks. You cannot tune it away. A random walk, a few seconds in a direction drawn from a seeded generator before trying the field again, is simple and often enough in open ground, but it wanders and gives no bound on time in a deep trap. Wall following, as here, borrows the boundary-following and leave rules of the Bug family of algorithms; their versions with strict leave rules are proven to reach a reachable goal with ideal sensing and localisation, and this program's version, with a noisy scan and a lagging velocity loop, has no such proof. Navigation functions and harmonic potentials have no minima except the goal but need the map in advance. In practice a field is a local layer under a planner such as the A* of the path planning lesson, with a progress monitor and an escape.","title":"Local minima, and getting out"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists field.gfflight with the curve through the trees, trapped.gfflight with the drone hovering inside the U until the recording ends, and flight.gfflight with the wall-following detour around the north arm and the landing at the goal marker. Set kr to 40 and the closest approach drops to under a metre; set it to 1000 and tree 4 stops the first flight for several seconds.","title":"Fly it in GopherForge"}],"takeaway":"A potential field adds a pull towards the goal to pushes away from every scan point inside an influence distance and flies the negative gradient as a velocity command. Weight beams by their angle, tune the repulsion against speed and braking, watch progress, and plan an escape for the local minima that concave obstacles always create.","title":"Potential fields: attraction, repulsion from a scan, and the local-minimum trap","unitID":"drones-autonomy","wrongAnswers":["The repulsion is too weak to steer it around the walls","The attraction saturates at the cruise speed far from the goal"]},{"conceptTag":"drones.gap-following","designGuide":{"cautions":["Still local: dead ends and long walls can trap it.","Coarse sectors or wide margins close gaps that are really there."],"cost":"A 360-degree scan, a 72-sector histogram with widening each cycle, a cost function and a rate-limited heading.","family":"drones","flow":["Bin scan into sectors","Block with hysteresis","Widen by vehicle radius","Steer to best free sector"],"ratings":[],"strengths":["Chooses among directions, so obstacles on the line do not stall it.","Widening makes the vehicle size and margin explicit."]},"hint":"A sector is free when no beam in it hit anything. Compare the width of the drone with the gap those free beams passed through.","id":"drones.gap-following","introduction":"Instead of adding forces, a polar histogram asks which directions are open. Borenstein and Koren's Vector Field Histogram (1991) and its successor VFH+ (Ulrich and Borenstein, 1998) reduce the surroundings to a ring of sectors, mark the ones an obstacle blocks and steer into the open sector that best serves the goal. Because it chooses among directions rather than summing pushes, an obstacle on the line to the goal cannot balance it into a standstill. It is still a local method, and the vehicle's width has to be put in explicitly.","nuance":"Each reading must block every sector within asin((radius + margin) / d) of its bearing. Then a 0.6 m gap closes for a drone with a 0.3 m contact radius, and near obstacles block wide arcs.","objective":"Bin a lidar scan into a polar histogram, threshold it with hysteresis into blocked and free sectors, widen every reading by the vehicle radius, choose the free direction with a VFH+ style cost, smooth heading and speed, and fly through a cluttered field.","question":"A VFH-style planner flies a drone into a gap between two trees that is narrower than the drone. Which step was missing?","references":["https://en.wikipedia.org/wiki/Vector_Field_Histogram","https://ardupilot.org/copter/docs/common-oa-bendyruler.html","https://docs.px4.io/main/en/computer_vision/collision_prevention"],"reviewAnswer":"Widening blocked sectors by the drone's size","reviewPrompt":"What closes too-narrow gaps?","sections":[{"body":"Divide the circle into sectors, here 72 of 5 degrees centred on 0, 5, 10 degrees and so on, the resolution of the OBSTACLE_DISTANCE message from the rangefinders lesson, and give each sector the nearest reading that falls into it. The original VFH accumulates certainty values in a grid around the robot and weights each cell by its distance; with a precise lidar the nearest distance per sector carries the same information. A threshold turns the histogram into blocked and free sectors: blocked when something is closer than 8 m. With a single threshold, an obstacle hovering at 8 m makes a sector flicker and the chosen heading jump between scans. VFH+ uses two: here a sector becomes blocked under 8 m and free again only beyond 10 m, and between the two it keeps its previous state, the same hysteresis a thermostat uses.","title":"From a scan to a polar histogram"},{"body":"The histogram describes a point. A free sector whose centre line passes 10 cm from a trunk is free for a point and a collision for a drone with a 0.3 m contact radius, and the gaps between beams only make it worse. VFH+ enlarges every obstacle by the robot's radius plus a safety distance: a reading at distance d blocks every sector within gamma = asin((radius + margin) / d) of its bearing, and half the circle when d is smaller than radius plus margin. Near obstacles block wide arcs (49 degrees at 2 m with 1.5 m), far ones narrow arcs (4.3 degrees at 20 m). Gaps narrower than twice the widened radius disappear, which is exactly the point: a 0.6 m gap between two trees must not look free to a drone that needs 0.6 m to fit through, let alone a margin. The margin also covers tracking error in gusts and the 1 degree spacing of the beams.","title":"Widening by the vehicle radius"},{"body":"Among the free sectors, take the one with the lowest cost: 5 times its angle from the goal, plus 2 times its angle from the current heading, plus 2 times its angle from the previous choice. The goal weight exceeds the other two together, so the goal wins whenever its direction is open; the other terms matter when two valleys cost nearly the same, where they keep the choice from hopping between them on alternate scans. In this field the goal term alone also gets through, so treat the weights as insurance, not as tuning for one map. The heading then turns towards the chosen sector at no more than 1.5 rad/s, and the speed follows the widened free distance along the current heading, 0.6 (d - 2) between 0.5 and 6 m/s, so the drone slows while it is still pointed at something and speeds up once it faces the gap.","title":"Choosing and smoothing the heading"},{"body":"Two gate trees stand on the straight line 22 m out with 0.6 m between their trunks, and ten more trees fill the field up to the goal 80 m east. The program flies twice, scanning 360 beams at 10 Hz: once with no widening, where a sector is blocked only by beams that hit inside it, and once widened by 1.5 m, the 0.3 m contact radius plus a 1.2 m margin. The second flight prints a trace every 2.5 s with the goal bearing, the chosen sector, the smoothed heading and the speed, all in degrees from east, and, whenever the choice differs from the goal, the front half of the histogram as a pilot facing east would see it: north on the left, south on the right, one character per sector.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tsectors = 72 // 5 degrees each, centred on 0, 5, 10 ... degrees\n\twidth   = 2 * math.Pi / sectors\n\tdBlock  = 8.0  // m: a sector with an obstacle closer than this is blocked\n\tdFree   = 10.0 // m: and it is free again only beyond this (hysteresis)\n\tvmax    = 6.0  // m/s\n\tturn    = 1.5  // rad/s: the heading turns at most this fast\n)\n\nvar (\n\tgoal  = drone.Vec3{X: 80, Z: 10}\n\tworld = []drone.Obstacle{\n\t\t{Name: \"gate north\", X: 22, Y: 1.1, Radius: 0.8, Height: 15}, // 0.6 m between them\n\t\t{Name: \"gate south\", X: 22, Y: -1.1, Radius: 0.8, Height: 15},\n\t\t{Name: \"tree 1\", X: 32, Y: 6, Radius: 1.5, Height: 15},\n\t\t{Name: \"tree 2\", X: 35, Y: -5, Radius: 2, Height: 15},\n\t\t{Name: \"tree 3\", X: 40, Y: 1, Radius: 1.2, Height: 15},\n\t\t{Name: \"tree 4\", X: 44, Y: 9, Radius: 1.5, Height: 15},\n\t\t{Name: \"tree 5\", X: 46, Y: -8, Radius: 1.5, Height: 15},\n\t\t{Name: \"tree 6\", X: 50, Y: 3, Radius: 2, Height: 15},\n\t\t{Name: \"tree 7\", X: 53, Y: -3, Radius: 1, Height: 15},\n\t\t{Name: \"tree 8\", X: 57, Y: 8, Radius: 1.5, Height: 15},\n\t\t{Name: \"tree 9\", X: 60, Y: -6, Radius: 2, Height: 15},\n\t\t{Name: \"tree 10\", X: 63, Y: 1, Radius: 1.5, Height: 15},\n\t}\n)\n\nfunc wrap(a float64) float64 { return math.Remainder(a, 2*math.Pi) }\nfunc sector(a float64) int   { return (int(math.Round(a/width))%sectors + sectors) % sectors }\n\n// Histogram returns, for each sector, the nearest reading that blocks it.\n// Every reading at distance r blocks its own sector and, widened by the\n// angle asin(rs/r), every sector a body of radius rs would touch.\nfunc Histogram(scan []float64, rs float64) []float64 {\n\tnear := make([]float64, sectors)\n\tfor k := range near {\n\t\tnear[k] = drone.RangeMax\n\t}\n\tfor i, r := range scan {\n\t\tif r >= drone.RangeMax {\n\t\t\tcontinue\n\t\t}\n\t\ta, g := 2*math.Pi*float64(i)/float64(len(scan)), 0.0\n\t\tif rs > 0 {\n\t\t\tg = math.Asin(math.Min(1, rs/r))\n\t\t}\n\t\tfor k := range near {\n\t\t\tif math.Abs(wrap(a-float64(k)*width)) <= g+width/2 {\n\t\t\t\tnear[k] = math.Min(near[k], r)\n\t\t\t}\n\t\t}\n\t}\n\treturn near\n}\n\n// Choose returns the free sector with the lowest VFH+ style cost: 5 x the\n// angle to the goal, 2 x the turn from the current heading and 2 x the change\n// from the previous choice. -1 means every sector is blocked.\nfunc Choose(blocked []bool, goal, heading float64, prevK int) int {\n\tbest, cost := -1, math.Inf(1)\n\tfor k, b := range blocked {\n\t\ta := float64(k) * width\n\t\tc := 5*math.Abs(wrap(a-goal)) + 2*math.Abs(wrap(a-heading)) + 2*math.Abs(wrap(a-float64(prevK)*width))\n\t\tif !b && c < cost {\n\t\t\tbest, cost = k, c\n\t\t}\n\t}\n\treturn best\n}\n\n// draw shows the front half, as a pilot facing east sees it: north on the\n// left, south on the right, one character per 5 degree sector.\nfunc draw(blocked []bool, goalK, chosen int) string {\n\tvar b strings.Builder\n\tfor deg := 90; deg >= -90; deg -= 5 {\n\t\tswitch k := sector(float64(deg) * math.Pi / 180); {\n\t\tcase k == chosen:\n\t\t\tb.WriteByte('^')\n\t\tcase k == goalK:\n\t\t\tb.WriteByte('G')\n\t\tcase blocked[k]:\n\t\t\tb.WriteByte('#')\n\t\tdefault:\n\t\t\tb.WriteByte('.')\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// Fly navigates to the goal with a vehicle radius rs (0: no widening).\nfunc Fly(rs float64, show bool) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{Y: -1.5}, Gust: 0.8, Obstacles: world, Seed: 4})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tsim.Waypoint(goal)\n\tstart, heading, prev, next := sim.Time(), 0.0, 0, sim.Time()\n\tblocked, minC, path, last := make([]bool, sectors), math.Inf(1), 0.0, d.State().Pos\n\twatch := func(st drone.State) { // truth: path flown and closest approach to a trunk\n\t\tpath, last = path+st.Pos.Sub(last).Horizontal().Len(), st.Pos\n\t\tfor _, o := range world {\n\t\t\tminC = math.Min(minC, math.Hypot(st.Pos.X-o.X, st.Pos.Y-o.Y)-o.Radius)\n\t\t}\n\t}\n\tsim.RunUntil(90, func(t float64) bool {\n\t\tst := d.State()\n\t\twatch(st)\n\t\ttoGoal := goal.Sub(st.Pos).Horizontal()\n\t\tif toGoal.Len() < 2 || st.Mode == drone.Crashed {\n\t\t\treturn true\n\t\t}\n\t\tif math.Mod(math.Round(t/sim.Dt()), 5) != 0 {\n\t\t\treturn false\n\t\t}\n\t\tnear := Histogram(d.Scan(360), rs)\n\t\tfor k, r := range near {\n\t\t\tif r < dBlock {\n\t\t\t\tblocked[k] = true\n\t\t\t} else if r > dFree {\n\t\t\t\tblocked[k] = false\n\t\t\t}\n\t\t}\n\t\tgoalA := math.Atan2(toGoal.Y, toGoal.X)\n\t\tgoalK, k := sector(goalA), Choose(blocked, goalA, heading, prev)\n\t\tif k < 0 {\n\t\t\td.SetVelocity(drone.Vec3{}, 0)\n\t\t\treturn false\n\t\t}\n\t\tprev = k\n\t\theading += math.Max(-turn*0.1, math.Min(turn*0.1, wrap(float64(k)*width-heading)))\n\t\tspeed := math.Max(0.5, math.Min(vmax, 0.6*(near[sector(heading)]-2)))\n\t\td.SetVelocity(drone.Vec3{X: speed * math.Cos(heading), Y: speed * math.Sin(heading)}, 0)\n\t\tif show && t >= next {\n\t\t\tnext += 2.5\n\t\t\tdeg := func(a float64) float64 { return math.Round(wrap(a)*180/math.Pi) + 0 } // + 0: no \"-0\"\n\t\t\tfmt.Printf(\"  t=%4.1f s %v goal %4.0f  chosen %4.0f  heading %4.0f deg  %.1f m/s\\n\", t-start, st.Pos,\n\t\t\t\tdeg(goalA), deg(float64(k)*width), deg(heading), speed)\n\t\t\tif goalK != k {\n\t\t\t\tfmt.Printf(\"    N %s S\\n\", draw(blocked, goalK, k))\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n\tif st := d.State(); st.Mode == drone.Crashed {\n\t\tev := sim.Events()\n\t\tfmt.Printf(\"  %s at %v after %.1f s\\n\", ev[len(ev)-1].Text, st.Pos, sim.Time()-start)\n\t\tsim.Run(2, nil)\n\t\treturn sim\n\t}\n\td.GoTo(goal)\n\tsim.RunUntil(10, func(float64) bool { watch(d.State()); return d.Arrived() })\n\tfmt.Printf(\"  arrived after %.1f s, path %.1f m for %.0f m straight, closest surface %.2f m\\n\",\n\t\tsim.Time()-start, path, goal.Horizontal().Len(), minC)\n\td.Land()\n\tsim.RunUntil(30, func(float64) bool { return d.State().Landed })\n\treturn sim\n}\n\nfunc main() {\n\tfmt.Println(\"no widening: sectors are blocked only where a beam hit\")\n\tnaive := Fly(0, false)\n\trs := 1.5 // contact radius 0.3 m plus a margin\n\tfmt.Printf(\"widened by %.1f m (0.3 m contact radius + %.1f m margin):\\n\", rs, rs-0.3)\n\tfmt.Println(\"  histogram ahead, 90 deg left to 90 deg right: # blocked, G goal, ^ chosen\")\n\tsim := Fly(rs, true)\n\tif err := naive.SaveAs(\"naive\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A gate and a cluttered field","walkthrough":"Without widening the gate's sector stays free, because from 8 m the central beams still pass between the trunks, so the drone flies straight into the gap: 'hit gate south at (21.8, 0.0, 9.9) after 4.4 s'. With widening the gate blocks the line long before; at t=5.1 s the drone is past it at (24.1, -4.3). At t=7.6 s the widened trees block everything from 35 degrees left to 30 degrees right, goal included, and of the two valleys it stays with the left one it is already turning into, 40 degrees. At t=10.1 s that valley has shrunk to 30 to 40 degrees while everything beyond 45 degrees right is open, and it switches to -45; at t=12.6 s only the right side is open, from 30 degrees right, and it takes -30. At t=15.1 s, at (66.5, -7.7), the goal sector is free and chosen. It arrives after 18.2 s with 93.5 m of path for 80 m straight, never closer than 1.79 m to a trunk."},{"body":"VFH looks only at the current surroundings. A dead end, or a goal behind a wall longer than the sensor range, can lead it into a pocket it has to back out of, and two valleys of equal cost can still make it hesitate. VFH* (Ulrich and Borenstein, 2000) checks each candidate direction with an A* look-ahead over the projected positions before committing. The flight stacks use the same ideas: ArduPilot's BendyRuler probes directions around the vehicle up to OA_BR_LOOKAHEAD, typically 5 m, and picks one that is open enough while moving towards the destination, keeping OA_MARGIN_MAX from obstacles; PX4's collision prevention keeps its obstacle map in angular bins and may turn the commanded direction by up to CP_GUIDE_ANG towards a freer bin. Too few sectors or too much widening close real gaps, too little lets the vehicle scrape past trunks, so tune the margin against the vehicle's measured tracking error.","title":"Where histograms still fail"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists naive.gfflight, which ends at the gate, and flight.gfflight, which weaves south of the gate and through the trees to the goal marker. Change rs from 1.5 to 0.8 m and the path straightens while the closest approach shrinks to about 1 m; set turn to 0.5 rad/s and the drone swings wide and slows while its heading lags the choice.","title":"Fly it in GopherForge"}],"takeaway":"Reduce the scan to a ring of sectors, block a sector with hysteresis, widen every reading by asin((radius + margin) / d) so gaps narrower than the vehicle close, choose the free sector with a cost dominated by the goal direction, and limit the turn rate and the speed. It is fast and decisive, and still local.","title":"Gap following with a polar histogram: VFH-style sectors, widening and heading choice","unitID":"drones-autonomy","wrongAnswers":["Hysteresis between the blocked and free thresholds","A cost term for the previous steering direction"]},{"conceptTag":"drones.inspection-orbit","designGuide":{"cautions":["Lattice towers, guy wires and flat walls break the round-mast model.","A lost return must stop the orbit, not continue it blind."],"cost":"A horizontal rangefinder or scan, a radial PI loop with anti-windup at 10 Hz, and a lap counter and standoff log per inspection.","family":"drones","flow":["Find the mast in the scan","Radial PI on range error","Tangential speed command","Count laps, score standoff"],"ratings":[],"strengths":["Holds the standoff to centimetres whatever the map error.","The measured bearing can point the camera without a model."]},"hint":"Ask what the controller measures: the distance from its GPS position to a point on the site plan, or the distance to the mast itself.","id":"drones.inspection-orbit","introduction":"Inspection flights photograph masts, chimneys, wind turbine towers and bridge piers from a fixed distance, so that every image has the same scale and focus and the vehicle never drifts into the structure. Autopilots can orbit a point in coordinates. That works when the coordinates are right, but site plans, imagery and GPS are each good to a few metres, and a 4 m error in the centre turns an 8 m standoff into anything from 4 to 12 m.","nuance":"A GPS orbit flies a good circle around the wrong centre: a 3.9 m map error swung the standoff from 3.8 to 12.2 m while the controller believed it was within 0.6 m. A rangefinder measures the standoff itself.","objective":"Orbit a mast at a constant distance from its surface with a radial PI loop on the rangefinder and a tangential speed, count laps, and compare per-lap standoff statistics with a GPS-only orbit around a mapped position that is a few metres off.","question":"An orbit around a mast's surveyed coordinates shows 8 m on the ground station, yet the images change scale around every lap. Why?","references":["https://docs.px4.io/main/en/flight_modes_mc/orbit","https://ardupilot.org/copter/docs/circle-mode.html","https://mavlink.io/en/messages/common.html#MAV_CMD_DO_ORBIT"],"reviewAnswer":"The mapped centre may be off; range measures the gap","reviewPrompt":"Why orbit on range, not on GPS?","sections":[{"body":"PX4's Orbit mode takes a centre, radius, altitude and speed from a ground station or from MAV_CMD_DO_ORBIT, whose parameters are the radius (positive clockwise, negative counter-clockwise), the tangential velocity, the yaw behaviour, the number of radians to fly and the centre. It faces the centre by default and limits the speed to keep the centripetal acceleration below 2 m/s2. ArduPilot's Circle mode orbits a point CIRCLE_RADIUS_M ahead of the vehicle (in metres, default 10; CIRCLE_RADIUS in centimetres up to firmware 4.6) at CIRCLE_RATE degrees per second, limits the speed so that the centripetal acceleration stays under half of WP_ACC, and with CIRCLE_OPTIONS can set the centre at the current position and point a mount at it. Both fly a circle around coordinates on the position estimate; neither measures the structure. The centripetal acceleration is v squared / R: 0.95 m/s2 at 3 m/s on a 9.5 m radius.","title":"Orbiting a point: what autopilots offer"},{"body":"A horizontal rangefinder measures the quantity that matters, the distance to the surface. For a round mast the shortest reading in a scan points at its centre, so one scan gives both the inward direction n and the range r. Command v = vt t + (kp e + ki integral of e) n, with e = r - standoff, n pointing at the mast and t = n turned 90 degrees clockwise, which keeps the mast on the left and flies counter-clockwise. The integral earns its place here for a different reason than in the PID altitude lesson: the circle needs an inward acceleration, the velocity loop lags the command as it turns, and the drone drifts outwards until a P-only loop has enough error to command the inward speed it needs. The integral supplies that command with zero error and also absorbs the wind; clamp it, as in the PID lesson's anti-windup. Count laps by unwrapping the bearing to the mast and counting whole turns of 2 pi.","title":"Closing the loop on the structure"},{"body":"The mast stands at (30, 20) with a radius of 1.5 m and a height of 40 m; the site plan puts it at (27, 22.5). The target is 8 m from the surface at 3 m/s and 20 m altitude, in a 3 m/s wind with 1.5 m/s gusts, three laps per method. The GPS-only orbit runs the same radial PI on the distance from the telemetry GPS to the mapped centre; the rangefinder orbits use the shortest of 360 beams, once with P only (kp 0.8) and once with PI (ki 0.15). Every lap prints its duration, the true standoff from the simulator's truth (what an inspector measuring the images would find), its RMS error against 8 m, and the RMS error the controller believes it has.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tstandoff = 8.0  // m from the mast's surface: what the camera is focused for\n\tvt       = 3.0  // m/s along the orbit\n\talt      = 20.0 // m\n\tlaps     = 3\n)\n\nvar (\n\tmast   = drone.Obstacle{Name: \"mast\", X: 30, Y: 20, Radius: 1.5, Height: 40}\n\tmapped = drone.Vec3{X: 27, Y: 22.5} // where the site plan puts it: 3.9 m off\n)\n\n// Stats collects, over one lap, the true standoff and the error the\n// controller believes it has.\ntype Stats struct{ n, sum, sq, min, max, believed float64 }\n\nfunc (s *Stats) Add(v, e float64) {\n\tif s.n == 0 {\n\t\ts.min, s.max = v, v\n\t}\n\ts.n, s.sum, s.sq, s.believed = s.n+1, s.sum+v, s.sq+(v-standoff)*(v-standoff), s.believed+e*e\n\ts.min, s.max = math.Min(s.min, v), math.Max(s.max, v)\n}\n\nfunc (s Stats) String() string {\n\treturn fmt.Sprintf(\"standoff %4.1f..%4.1f m  mean %4.2f  rms error %4.2f m (believed %4.2f)\",\n\t\ts.min, s.max, s.sum/s.n, math.Sqrt(s.sq/s.n), math.Sqrt(s.believed/s.n))\n}\n\n// Nearest returns the shortest reading and its heading: towards the centre\n// of a round mast, as the shortest distance to a circle points at its centre.\nfunc Nearest(scan []float64) (r, heading float64) {\n\tk := 0\n\tfor i := range scan {\n\t\tif scan[i] < scan[k] {\n\t\t\tk = i\n\t\t}\n\t}\n\treturn scan[k], 2 * math.Pi * float64(k) / float64(len(scan))\n}\n\n// Orbit flies `laps` counter-clockwise laps. The guidance function returns\n// the unit vector towards the centre and the radial error (positive: too\n// far out), from whatever the vehicle believes.\nfunc Orbit(label string, ki float64, guidance func(d *drone.Drone) (drone.Vec3, float64, bool)) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1.5, Obstacles: []drone.Obstacle{mast}, Seed: 17})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tstart := mapped.Add(drone.Vec3{X: -(standoff + mast.Radius), Z: alt})\n\td.GoTo(start)\n\tsim.RunUntil(60, func(float64) bool { return d.Arrived() })\n\tfmt.Println(label)\n\n\tintegral, e, turned, lap, prev, lapStart := 0.0, 0.0, 0.0, 0, math.NaN(), sim.Time()\n\tvar s Stats\n\tsim.RunUntil(400, func(t float64) bool {\n\t\tst := d.State()\n\t\tif math.Mod(math.Round(t/sim.Dt()), 5) == 0 { // 10 Hz\n\t\t\tin, err, ok := guidance(d)\n\t\t\tif e = err; !ok {\n\t\t\t\td.Hold()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tintegral = math.Max(-2, math.Min(2, integral+e*0.1))\n\t\t\tradial := math.Max(-2, math.Min(2, 0.8*e+ki*integral))\n\t\t\ttangent := drone.Vec3{X: in.Y, Y: -in.X} // centre on the left: counter-clockwise\n\t\t\td.SetVelocity(tangent.Scale(vt).Add(in.Scale(radial)), 0)\n\t\t}\n\t\t// truth, for scoring only: the angle around the real mast and the real standoff\n\t\trel := st.Pos.Sub(drone.Vec3{X: mast.X, Y: mast.Y}).Horizontal()\n\t\ta := math.Atan2(rel.Y, rel.X)\n\t\tif !math.IsNaN(prev) {\n\t\t\tturned += math.Remainder(a-prev, 2*math.Pi)\n\t\t}\n\t\tprev = a\n\t\ts.Add(rel.Len()-mast.Radius, e)\n\t\tif turned >= 2*math.Pi*float64(lap+1) {\n\t\t\tlap++\n\t\t\tfmt.Printf(\"  lap %d %4.1f s  %v\\n\", lap, t-lapStart, s)\n\t\t\ts, lapStart = Stats{}, t\n\t\t}\n\t\treturn lap == laps\n\t})\n\tfmt.Printf(\"  radial integral %.2f m/s\\n\", ki*integral)\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool { return d.State().Landed })\n\treturn sim\n}\n\nfunc main() {\n\tfmt.Printf(\"mast at (%.1f, %.1f), radius %.1f m; the site plan says (%.1f, %.1f), %.1f m off\\n\",\n\t\tmast.X, mast.Y, mast.Radius, mapped.X, mapped.Y, mapped.Sub(drone.Vec3{X: mast.X, Y: mast.Y}).Len())\n\tfmt.Printf(\"orbit %.0f m from the surface at %.0f m/s, %d laps each, wind 3 m/s with gusts\\n\", standoff, vt, laps)\n\n\tgps := Orbit(\"GPS only, around the mapped centre:\", 0.15, func(d *drone.Drone) (drone.Vec3, float64, bool) {\n\t\trel := mapped.Sub(d.Telemetry().GPS).Horizontal()\n\t\treturn rel.Scale(1 / rel.Len()), rel.Len() - mast.Radius - standoff, true\n\t})\n\tranged := func(d *drone.Drone) (drone.Vec3, float64, bool) {\n\t\tr, h := Nearest(d.Scan(360))\n\t\treturn drone.Vec3{X: math.Cos(h), Y: math.Sin(h)}, r - standoff, r < drone.RangeMax\n\t}\n\tp := Orbit(\"rangefinder, radial P only:\", 0, ranged)\n\tpi := Orbit(\"rangefinder, radial PI:\", 0.15, ranged)\n\tif err := gps.SaveAs(\"gps-orbit\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := p.SaveAs(\"p-only\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := pi.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A GPS orbit against a rangefinder orbit","walkthrough":"The GPS orbit is a good circle around the wrong point. Its controller believes it holds 8 m within 0.52 to 0.63 m RMS, the GPS noise, while the true standoff swings from 3.8 to 12.2 m with 2.32 to 2.90 m RMS error, so the image scale changes threefold around each lap. The rangefinder orbits start 11.1 m out and converge during lap 1. P only settles at 8.25 m, 0.25 m outside, the error it needs to command about 0.2 m/s inwards (0.8 x 0.25); PI holds a mean of 8.02 and 8.04 m with 0.07 and 0.08 m RMS on laps 2 and 3, and its integral ends at 0.24 m/s, the same inward command delivered without an error. What the rangefinder controller believes agrees with the truth to 0.02 m, because it measures what it controls. Laps take 18.8 to 20.2 s, close to 2 pi x 9.5 / 3 = 19.9 s."},{"body":"Real structures are rarely smooth cylinders. A lattice tower lets beams through, guy wires are invisible to most scanners and must come from the map with a wide margin, and a flat wall has a nearest point but no centre, so follow it along its normal instead. Near large structures GNSS also suffers from multipath and a blocked sky, one more reason to measure the structure directly. Point the camera along the measured bearing rather than at the mapped centre. Cover the height in laps at several altitudes, stepping by the camera's vertical footprint minus the overlap, as the survey in the waypoint missions lesson stepped sideways. Decide what happens when the return is lost: a reading at maximum range means the structure is gone from view, so hold or back away instead of flying the last command, and keep the mapped position as a sanity check on the measured one, which should agree within the map's known error.","title":"Inspection in practice"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists gps-orbit.gfflight, whose circle sits visibly off-centre around the grey mast disc, p-only.gfflight and flight.gfflight, the PI orbit hugging the mast at a constant distance. Move mapped onto the true position and the GPS orbit's error drops to the GPS noise; pass 0.4 instead of 0.15 as the PI orbit's ki and the first lap dips to 7.6 m before it settles.","title":"Fly it in GopherForge"}],"takeaway":"An orbit around coordinates is only as good as the coordinates. Measure the structure instead: the shortest reading gives the bearing and the range, a radial PI loop on the range error plus a tangential speed holds the standoff, the integral supplies the inward command that turning and wind need, and per-lap statistics show whether the images will be consistent.","title":"Inspecting a structure: a constant-standoff orbit from rangefinder feedback","unitID":"drones-autonomy","wrongAnswers":["The orbit speed is too high for the camera shutter","The radial P gain is too low to hold the radius"]},{"conceptTag":"drones.occupancy-grid","designGuide":{"cautions":["Pose error smears obstacles across cells.","A 2D slice misses anything lower than the drone."],"cost":"A grid sized to the site, a beam tracer and a pose good to a fraction of a cell.","family":"drones","flow":["Scan at each pose","Trace beams, add log-odds","Clamp every cell","Threshold into a map"],"ratings":[],"strengths":["Free, occupied and unknown stay distinct.","Each update is an addition, cheap enough for every scan."]},"hint":"Count how many misses of -0.4 it takes to undo 131 hits of +0.85, and then how many it takes from 3.5.","id":"drones.occupancy-grid","introduction":"A planner needs a map, and on most sites nobody hands you a current one: a crane moved, a container arrived, a tree grew. A drone can build its own with a rangefinder. Every beam says two things: the space it crossed was empty, and something stood where it ended. An occupancy grid collects that evidence cell by cell, as a probability that the cell is occupied, and keeps apart three answers that a naive map mixes up: free, occupied, and never looked at.","nuance":"Unclamped, evidence piles up without limit: a cell hit 131 times needs 273 beams through it to read free. Clamping bounds both certainty and inertia, so the map can follow a site that changes.","objective":"Build a 2D occupancy grid in local metres from rangefinder scans: add log-odds evidence along each beam traced with Bresenham's line, mark nothing for readings without a return, clamp every cell so the map can change, and compare the built map with the true obstacles after a survey flight.","question":"Why do occupancy grids clamp each cell's log-odds, for example to [-2, 3.5]?","references":["https://en.wikipedia.org/wiki/Occupancy_grid_mapping","https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm","https://github.com/OctoMap/octomap","https://ardupilot.org/copter/docs/common-oa-bendyruler.html"],"reviewAnswer":"So a cell can change its state within a few readings","reviewPrompt":"Why clamp log-odds in a grid?","sections":[{"body":"Cover the area with square cells in the local ENU frame of the coordinates lesson, here 2 m cells over 60 by 40 m, and find a point's cell with floor((x - x0) / cell). Each cell holds the probability that something occupies it. It starts at 0.5, which means unknown, not half full. Bayes' rule updates a probability by multiplying odds, and the logarithm turns that product into a sum. So each cell stores its log-odds, l = log(p / (1 - p)), and every reading adds a constant: log(0.7/0.3) = 0.85 for the cell where a beam ended, log(0.4/0.6) = -0.4 for each cell it crossed. Those two numbers are the sensor model: how far one hit or one miss should move your belief. They are OctoMap's defaults, and one hit outweighs one miss on purpose: a thin obstacle in a cell is passed by far more beams than hit it. The grid is a 2D slice at the flight altitude. Range only sees obstacles taller than the drone, so the map says nothing about anything lower.","title":"A grid of probabilities in local metres"},{"body":"For each reading, compute the hit point from the drone's position, the beam's heading and the range, convert both ends to cells, and walk the cells between them. Bresenham's algorithm does that walk with integer additions only. It steps along one axis and keeps an error term that says when to step along the other, so it visits every cell on the line once, in order. Every cell before the end gets the miss update, and the end cell gets the hit update. A reading of drone.RangeMax means no return within 40 m, and it gets nothing at all: no free cells and no hit. No return is weak evidence, because a real lidar also gets none from glass, black paint, rain or a surface at a grazing angle. Mappers that trust their sensor clear free space along such beams up to a shorter distance. The configuration-space lesson makes that choice and explains it.","code":"// Ray adds one reading taken at p: Bresenham's line from the drone's cell to\n// the cell of the hit, free on the way and occupied at the end. A max-range\n// reading has no hit and marks nothing.\nfunc (g *Grid) Ray(p drone.Vec3, heading, r float64) bool {\n\tif r >= drone.RangeMax {\n\t\treturn false\n\t}\n\tax, ay := cellOf(p.X, p.Y)\n\tbx, by := cellOf(p.X+r*math.Cos(heading), p.Y+r*math.Sin(heading))\n\tdx, dy := abs(bx-ax), -abs(by-ay)\n\tsx, sy := sign(bx-ax), sign(by-ay)\n\te := dx + dy\n\tfor ax != bx || ay != by {\n\t\tg.add(ax, ay, lFree)\n\t\te2 := 2 * e\n\t\tif e2 >= dy {\n\t\t\te += dy\n\t\t\tax += sx\n\t\t}\n\t\tif e2 <= dx {\n\t\t\te += dx\n\t\t\tay += sy\n\t\t}\n\t}\n\tg.add(bx, by, lOcc)\n\treturn true\n}","language":"go","title":"Tracing a beam with Bresenham's line","walkthrough":"dx is the run and dy the negative rise, so e = dx + dy is the error before the first step. Each pass marks the current cell free, doubles the error once and uses that one value for both tests: e2 >= dy steps in x, e2 <= dx steps in y, and both together make a diagonal step. If you recompute 2*e after the x step, an easy slip, the walk can pass the end cell and never stop. The loop ends on the hit cell, which gets lOcc, and the result lets the caller count the readings that marked nothing."},{"body":"The program places four obstacles: a 30 m tower of radius 5 m, a 25 m mast, a 14 m tree and a 6 m shed, which is lower than the 10 m survey altitude. The drone flies a 48 by 16 m loop around the tower at 4 m/s, in a 2.2 m/s wind with 1 m/s gusts. On each 5 Hz telemetry report it takes a 90-beam scan. It builds two maps from the same readings. One uses the pose a program actually has, the GPS position in telemetry. The other uses the true pose, which only a simulator knows, to show what the pose error costs. The program prints the GPS-pose map next to the true obstacles. Then, for each map, it counts what the map says about the true obstacle cells and the true free cells.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tcell       = 2.0    // metres per cell\n\tW, H       = 30, 20 // cells: 60 m by 40 m\n\tx0, y0     = -6.0, -20.0\n\talt        = 10.0 // survey altitude, m\n\tlOcc       = 0.85 // log-odds added at a hit: log(0.7/0.3)\n\tlFree      = -0.4 // added to each cell the beam crossed: log(0.4/0.6)\n\tlMin, lMax = -2.0, 3.5\n)\n\nvar obstacles = []drone.Obstacle{\n\t{Name: \"tower\", X: 22, Y: 8, Radius: 5, Height: 30},\n\t{Name: \"mast\", X: 42, Y: -10, Radius: 1.5, Height: 25},\n\t{Name: \"tree\", X: 10, Y: -10, Radius: 2.5, Height: 14},\n\t{Name: \"shed\", X: 30, Y: -12, Radius: 3, Height: 6},\n}\n\n// Grid holds the log-odds of occupancy per cell (0 is unknown, p = 0.5) and\n// counts the hits and pass-throughs behind each value.\ntype Grid struct {\n\tL            [H][W]float64\n\thits, passes [H][W]int\n}\n\nfunc cellOf(x, y float64) (int, int) {\n\treturn int(math.Floor((x - x0) / cell)), int(math.Floor((y - y0) / cell))\n}\n\nfunc (g *Grid) add(cx, cy int, l float64) {\n\tif cx < 0 || cy < 0 || cx >= W || cy >= H {\n\t\treturn\n\t}\n\tg.L[cy][cx] = math.Max(lMin, math.Min(lMax, g.L[cy][cx]+l))\n\tif l > 0 {\n\t\tg.hits[cy][cx]++\n\t} else {\n\t\tg.passes[cy][cx]++\n\t}\n}\n\n// Ray adds one reading taken at p: Bresenham's line from the drone's cell to\n// the cell of the hit, free on the way and occupied at the end. A max-range\n// reading has no hit and marks nothing.\nfunc (g *Grid) Ray(p drone.Vec3, heading, r float64) bool {\n\tif r >= drone.RangeMax {\n\t\treturn false\n\t}\n\tax, ay := cellOf(p.X, p.Y)\n\tbx, by := cellOf(p.X+r*math.Cos(heading), p.Y+r*math.Sin(heading))\n\tdx, dy := abs(bx-ax), -abs(by-ay)\n\tsx, sy := sign(bx-ax), sign(by-ay)\n\te := dx + dy\n\tfor ax != bx || ay != by {\n\t\tg.add(ax, ay, lFree)\n\t\te2 := 2 * e\n\t\tif e2 >= dy {\n\t\t\te += dy\n\t\t\tax += sx\n\t\t}\n\t\tif e2 <= dx {\n\t\t\te += dx\n\t\t\tay += sy\n\t\t}\n\t}\n\tg.add(bx, by, lOcc)\n\treturn true\n}\n\nfunc abs(v int) int  { return max(v, -v) }\nfunc sign(v int) int { return min(max(v, -1), 1) }\n\nfunc symbol(l float64) byte {\n\tswitch {\n\tcase l >= 0.5:\n\t\treturn '#' // p >= 0.62\n\tcase l <= -0.3:\n\t\treturn '.' // p <= 0.43\n\t}\n\treturn ' ' // unknown or undecided\n}\n\n// truth draws a cell from the obstacle list: '#' where an obstacle at least\n// as tall as the survey altitude overlaps it, 'o' for a lower one.\nfunc truth(cx, cy int) byte {\n\tt := byte('.')\n\tlx, ly := x0+float64(cx)*cell, y0+float64(cy)*cell\n\tfor _, o := range obstacles {\n\t\tnx := math.Max(lx, math.Min(o.X, lx+cell))\n\t\tny := math.Max(ly, math.Min(o.Y, ly+cell))\n\t\tif math.Hypot(nx-o.X, ny-o.Y) < o.Radius {\n\t\t\tif o.Height > alt {\n\t\t\t\treturn '#'\n\t\t\t}\n\t\t\tt = 'o'\n\t\t}\n\t}\n\treturn t\n}\n\n// score counts true obstacle cells and true free cells by what the map says.\nfunc score(g *Grid) (occ, free [3]int) {\n\tfor cy := range H {\n\t\tfor cx := range W {\n\t\t\tk := strings.IndexByte(\"#. \", symbol(g.L[cy][cx]))\n\t\t\tif truth(cx, cy) == '#' {\n\t\t\t\tocc[k]++\n\t\t\t} else {\n\t\t\t\tfree[k]++\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 2, Y: 1}, Gust: 1, MaxSpeed: 4, Seed: 7, Obstacles: obstacles})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\n\t// built uses the pose a program has (GPS telemetry); ideal uses the true\n\t// pose, which only a simulator knows, to show what the pose error costs.\n\tvar built, ideal Grid\n\tscans, readings, misses := 0, 0, 0\n\tlast := -1.0\n\troute := []drone.Vec3{{X: 48, Z: alt}, {X: 48, Y: 16, Z: alt}, {X: 0, Y: 16, Z: alt}, {Z: alt}}\n\tfor _, wp := range route {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(60, func(float64) bool {\n\t\t\ttel := d.Telemetry()\n\t\t\tif tel.Time != last { // a new 5 Hz report: scan with it\n\t\t\t\tlast = tel.Time\n\t\t\t\tscans++\n\t\t\t\tfor i, r := range d.Scan(90) {\n\t\t\t\t\theading := 2 * math.Pi * float64(i) / 90\n\t\t\t\t\treadings++\n\t\t\t\t\tif !built.Ray(tel.GPS, heading, r) {\n\t\t\t\t\t\tmisses++\n\t\t\t\t\t}\n\t\t\t\t\tideal.Ray(d.State().Pos, heading, r)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn d.Arrived()\n\t\t})\n\t}\n\td.Land()\n\tsim.RunUntil(30, func(float64) bool { return d.State().Landed })\n\n\tfmt.Printf(\"%d scans of 90 beams: %d readings, %d at max range (marked nothing)\\n\", scans, readings, misses)\n\tfmt.Printf(\"  %-34s%s\\n\", \"built map (GPS pose)\", \"true obstacles at 10 m (o: lower)\")\n\tfor cy := H - 1; cy >= 0; cy-- { // north up\n\t\tvar a, b strings.Builder\n\t\tfor cx := range W {\n\t\t\ta.WriteByte(symbol(built.L[cy][cx]))\n\t\t\tb.WriteByte(truth(cx, cy))\n\t\t}\n\t\tfmt.Printf(\"  |%s| |%s|\\n\", a.String(), b.String())\n\t}\n\tfmt.Printf(\"%-24s%10s%10s%10s\\n\", \"true cells\", \"mapped #\", \"mapped .\", \"unknown\")\n\tfor _, m := range []struct {\n\t\tname string\n\t\tg    *Grid\n\t}{{\"GPS pose\", &built}, {\"true pose\", &ideal}} {\n\t\tocc, free := score(m.g)\n\t\tfmt.Printf(\"%-24s%10d%10d%10d\\n\", \"obstacle, \"+m.name, occ[0], occ[1], occ[2])\n\t\tfmt.Printf(\"%-24s%10d%10d%10d\\n\", \"free or lower, \"+m.name, free[0], free[1], free[2])\n\t}\n\tbx, by := 0, 0\n\tfor cy := range H {\n\t\tfor cx := range W {\n\t\t\tif built.hits[cy][cx] > built.hits[by][bx] {\n\t\t\t\tbx, by = cx, cy\n\t\t\t}\n\t\t}\n\t}\n\th, p := built.hits[by][bx], built.passes[by][bx]\n\traw := float64(h)*lOcc + float64(p)*lFree\n\tfmt.Printf(\"busiest cell x %.0f..%.0f, y %.0f..%.0f: %d hits, %d beams through: log-odds %.1f, %.1f unclamped\\n\",\n\t\tx0+float64(bx)*cell, x0+float64(bx+1)*cell, y0+float64(by)*cell, y0+float64(by+1)*cell, h, p, built.L[by][bx], raw)\n\tfmt.Printf(\"beams through it before it reads free: %d clamped, %d unclamped\\n\",\n\t\tint(math.Ceil((built.L[by][bx]+0.3)/-lFree)), int(math.Ceil((raw+0.3)/-lFree)))\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Map a site and compare it with the truth","walkthrough":"The 185 scans gave 16650 readings, and 14166 of them, 85 percent, ended at max range and marked nothing: on an open site most beams hit nothing. The map shows the consequence. Free space appears only where beams ended on something. The tower is a ring with an unknown inside, because no beam enters a solid. The southern rows are blank: beams that missed the tree and the mast found nothing to end on, so they marked nothing. The shed, lower than 10 m, never shows: its cells read unknown. With the true pose, 33 obstacle cells read occupied, none read free and 15 stay unknown, and no free cell reads occupied. With the GPS pose the obstacles smear: 39 obstacle cells read occupied, 2 read free, 8 free cells read occupied, and parts of the tower's ring are two and three cells thick. The busiest cell, x 8..10, y -8..-6 on the tree's north face, took 131 hits and 7 beams through it."},{"body":"Without limits, that busiest cell reaches log-odds 108.5, and 273 beams would have to pass through it before it read free, long after the parked truck it saw had left. Clamping to [-2, 3.5], probabilities 0.12 and 0.97 as in OctoMap, caps both certainty and inertia: the program prints that the same cell reads free after 10 beams through it. The thresholds that turn log-odds into a symbol are a separate choice. Here 0.5 or more is occupied and -0.3 or less is free, so one hit marks a cell occupied, one miss marks it free, and anything between is undecided; higher thresholds demand more evidence. A map of a static site can live with loose clamps; a map that should forget needs tight ones. ArduPilot's object database forgets by time instead: it drops an obstacle OA_DB_EXPIRE seconds after the obstacle leaves the sensor's view. The map is also only as good as the pose. Every beam is placed at the position you believed the drone was at, and as the GPS rows of the table show, errors there smear obstacles. Survey drones keep the pose error below the cell size with RTK fixes or by fusing the lidar's own odometry.","title":"Clamping, thresholds and a world that changes"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. The console prints both maps and the table. Output replays flight.gfflight: the four obstacles appear as grey discs labelled with their heights, along with the loop's four waypoints and the trail. Add a leg along the south side and compare the map. Climb above the tree's 14 m and the tree vanishes from the map. Set lFree to -0.85, as strong as a hit, and grazing beams erode the obstacles: with the true pose only 29 obstacle cells read occupied instead of 33.","title":"Fly it in GopherForge"}],"takeaway":"An occupancy grid stores log-odds per cell. Add a constant for every beam that ends in a cell and for every beam that crosses it, trace beams with Bresenham's line, give readings without a return no hit, and clamp the values so the map can change. Keep unknown apart from free, remember the map is a slice at one altitude, and place every beam with a pose you trust, because pose error smears obstacles.","title":"Occupancy grids from rangefinder scans: log-odds, Bresenham rays and clamping","unitID":"drones-autonomy","wrongAnswers":["To keep the values inside a float32 without overflow","So that unknown cells stay at exactly zero"]},{"conceptTag":"drones.configuration-space","designGuide":{"cautions":["Unknown as free is safe only with replanning.","Coarse cells and big margins close narrow gaps."],"cost":"An inflation pass per map update, a written decision about unknown space, and clearance logged on every flight.","family":"drones","flow":["Survey into a grid","Inflate; decide unknown","A* and prune","Fly and log clearance"],"ratings":[],"strengths":["A point planner gets an airframe-safe path.","Range readings turn the margin into a test."]},"hint":"List everything that lies between a point on the grid and a real surface: the airframe, what the controller and the map get wrong, and where inside a cell things can be.","id":"drones.configuration-space","introduction":"The path-planning lesson searched a grid that someone else had drawn and inflated. Here the drone builds the map itself, so two decisions come before the search: how much room to leave around what it saw, and what to assume about what it never saw. Both decide whether the planned path is safe. A wrong answer to the second does not show on the map: the path looks clear because nobody looked.","nuance":"The airframe alone leaves no room for gusts or map error. On a grid the obstacle can be anywhere in its cell, so measure to the cell's edge, and the drone anywhere in its own, so add half a diagonal.","objective":"Turn a self-built occupancy grid into a configuration space by growing occupied cells by the airframe radius, a margin and half a cell, decide whether unknown cells count as free or blocked, plan on the result with A*, fly the plan and check the clearance with the rangefinder.","question":"A grid planner treats the drone as a point. By how much should occupied cells be grown so that a path through free cells keeps the airframe clear?","references":["https://en.wikipedia.org/wiki/Motion_planning","https://en.wikipedia.org/wiki/A*_search_algorithm","https://ardupilot.org/copter/docs/common-oa-bendyruler.html","https://ardupilot.org/copter/docs/common-object-avoidance-landing-page.html"],"reviewAnswer":"Airframe radius, a margin and half a cell diagonal","reviewPrompt":"Grow obstacles by how much?","sections":[{"body":"A planner that treats the drone as a point needs a map in which a point is safe exactly where the real airframe would be. That map is the configuration space: grow every obstacle by the vehicle's radius, and a point outside the grown obstacles stands for an airframe clear of the real ones. On a grid, grow by more. The simulator counts contact when the drone's centre comes within 0.3 m of a surface, so the airframe radius is 0.3 m. Add a margin for what the plan cannot know: the tracking error in gusts, the map's own error and, on a real vehicle, the position estimate's error. Then add half a cell's diagonal, 0.7 m for 1 m cells, because a free cell only says the drone is somewhere inside it. The program measures from each cell centre to the edge of an occupied cell, because the obstacle can be anywhere inside it, and blocks every cell within 2.5 m. ArduPilot's object avoidance has the same knob, OA_MARGIN_MAX, and its documentation calls 2 m typical.","title":"From the map to configuration space"},{"body":"The occupancy-grid lesson ended with a map that was mostly unknown, because beams without a return marked nothing. A planner must treat each unknown cell as one or the other. Treat it as free and the plan is short and optimistic, but it crosses space no sensor has seen. That is acceptable only if the vehicle keeps scanning and replans the moment a beam ends somewhere new, as exploration planners do. Treat it as blocked and the plan uses only space seen to be empty, which may make it longer or impossible. Here unknown cells are inflated too, because an obstacle in unseen space can stand right at its edge. This program also makes a choice the previous lesson did not: a beam without a return clears 25 m of free space. That is safe in this simulator, where Range sees every obstacle taller than the drone. It is not safe for a lidar that loses returns on glass or wet surfaces, and there open ground stays unknown.","code":"// CSpace blocks every cell whose centre lies within inflate of an occupied\n// cell, or of an unknown one unless unknownFree.\nfunc (m *Map) CSpace(unknownFree bool) *CSpace {\n\tvar c CSpace\n\tk := int(math.Ceil(inflate / cell))\n\tfor y := range H {\n\t\tfor x := range W {\n\t\t\tif l := m[y][x]; l <= -0.3 || unknownFree && l < 0.5 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor v := y - k; v <= y+k; v++ {\n\t\t\t\tfor u := x - k; u <= x+k; u++ {\n\t\t\t\t\tdx := math.Max(0, math.Abs(float64(u-x))-0.5) * cell // to the cell's edge\n\t\t\t\t\tdy := math.Max(0, math.Abs(float64(v-y))-0.5) * cell\n\t\t\t\t\tif (P{u, v}).In() && math.Hypot(dx, dy) < inflate {\n\t\t\t\t\t\tc[v][u] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn &c\n}","language":"go","title":"Unknown space: free or blocked","walkthrough":"Free cells, with log-odds of -0.3 or less, block nothing, and with unknownFree neither do undecided cells below 0.5. Every other cell blocks the cells around it whose centres lie closer than inflate to its square. dx and dy run from the neighbour's centre to the cell's nearest edge, so the cell itself and its eight neighbours are always blocked, and the corners of the 7 by 7 window are cut round. k = ceil(2.5 / 1) = 3 bounds the window."},{"body":"A hall of radius 5 m stands between home and a goal 40 m east, with a tank south-east of it and a tree south-west. A 20 m mast stands behind the hall. The drone surveys with an RTK-grade fix (GPSNoise 0.05 m) from two hover points, home and a point 24 m east and 14 m south, with three 360-beam sweeps at each, then comes back home. The mast hides behind the hall from home and behind the tank from the second point, so no beam reaches it. The program builds the configuration space twice and plans each with A*: the path-planning lesson's search, with a plain slice as the open list. It prunes each path by line of sight and flies it in its own simulation with the same seed, scanning 72 beams on every step. In the map, # is an occupied cell, + a cell blocked by inflation, a blank an unknown cell, o and * the two plans, and M the mast.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"slices\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tcell    = 1.0    // metres per cell\n\tW, H    = 48, 26 // cells\n\tx0, y0  = -4.0, -16.0\n\talt     = 8.0\n\tvehicle = 0.3  // airframe radius: the simulator's contact distance\n\tmargin  = 1.5  // tracking error in gusts plus what the map gets wrong\n\tclearTo = 25.0 // a beam without a return clears this far\n)\n\n// inflate is the configuration-space radius: the airframe, the margin and\n// half a cell's diagonal, because the obstacle may be anywhere in an\n// occupied cell and the drone anywhere in a free one.\nvar inflate = vehicle + margin + cell*math.Sqrt2/2\n\nvar obstacles = []drone.Obstacle{\n\t{Name: \"hall\", X: 16, Y: 0, Radius: 5, Height: 20},\n\t{Name: \"tank\", X: 27, Y: -4, Radius: 2.5, Height: 15},\n\t{Name: \"mast\", X: 28, Y: 5, Radius: 1, Height: 20},\n\t{Name: \"tree\", X: 6, Y: -9, Radius: 2, Height: 12},\n}\n\ntype P struct{ X, Y int }\n\nvar home, goal = P{4, 16}, P{44, 18}\n\ntype Map [H][W]float64 // log-odds, as in the occupancy-grid lesson\ntype CSpace [H][W]bool // true: the drone's centre must not be in this cell\n\nfunc cellOf(x, y float64) P {\n\treturn P{int(math.Floor((x - x0) / cell)), int(math.Floor((y - y0) / cell))}\n}\nfunc (p P) In() bool { return p.X >= 0 && p.Y >= 0 && p.X < W && p.Y < H }\nfunc (p P) Centre() drone.Vec3 {\n\treturn drone.Vec3{X: x0 + (float64(p.X)+0.5)*cell, Y: y0 + (float64(p.Y)+0.5)*cell, Z: alt}\n}\nfunc unknown(l float64) bool       { return l > -0.3 && l < 0.5 } // never seen, or undecided\nfunc (c *CSpace) Blocked(p P) bool { return !p.In() || c[p.Y][p.X] }\nfunc (m *Map) add(p P, l float64) {\n\tif p.In() {\n\t\tm[p.Y][p.X] = math.Max(-2, math.Min(3.5, m[p.Y][p.X]+l))\n\t}\n}\n\n// Ray traces one reading with Bresenham's line: free cells on the way and\n// an occupied cell at a hit; a beam without a return clears clearTo metres.\nfunc (m *Map) Ray(from drone.Vec3, heading, r float64) {\n\thit := r < drone.RangeMax\n\tif !hit {\n\t\tr = clearTo\n\t}\n\ta, b := cellOf(from.X, from.Y), cellOf(from.X+r*math.Cos(heading), from.Y+r*math.Sin(heading))\n\tdx, dy := max(b.X-a.X, a.X-b.X), -max(b.Y-a.Y, a.Y-b.Y)\n\tsx, sy := min(max(b.X-a.X, -1), 1), min(max(b.Y-a.Y, -1), 1)\n\tfor e := dx + dy; a != b; {\n\t\tm.add(a, -0.4)\n\t\te2 := 2 * e\n\t\tif e2 >= dy {\n\t\t\te, a.X = e+dy, a.X+sx\n\t\t}\n\t\tif e2 <= dx {\n\t\t\te, a.Y = e+dx, a.Y+sy\n\t\t}\n\t}\n\tm.add(b, map[bool]float64{true: 0.85, false: -0.4}[hit])\n}\n\n// CSpace blocks every cell whose centre lies within inflate of an occupied\n// cell, or of an unknown one unless unknownFree.\nfunc (m *Map) CSpace(unknownFree bool) *CSpace {\n\tvar c CSpace\n\tk := int(math.Ceil(inflate / cell))\n\tfor y := range H {\n\t\tfor x := range W {\n\t\t\tif l := m[y][x]; l <= -0.3 || unknownFree && l < 0.5 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor v := y - k; v <= y+k; v++ {\n\t\t\t\tfor u := x - k; u <= x+k; u++ {\n\t\t\t\t\tdx := math.Max(0, math.Abs(float64(u-x))-0.5) * cell // to the cell's edge\n\t\t\t\t\tdy := math.Max(0, math.Abs(float64(v-y))-0.5) * cell\n\t\t\t\t\tif (P{u, v}).In() && math.Hypot(dx, dy) < inflate {\n\t\t\t\t\t\tc[v][u] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn &c\n}\n\n// AStar is the path-planning lesson's search: 8-connected, octile heuristic,\n// no corner cutting; a plain slice serves as the open list.\nfunc AStar(c *CSpace, start, goal P) []P {\n\tcost, from, open := map[P]float64{start: 0}, map[P]P{}, []P{start}\n\tf := func(p P) float64 {\n\t\tdx, dy := math.Abs(float64(p.X-goal.X)), math.Abs(float64(p.Y-goal.Y))\n\t\treturn cost[p] + max(dx, dy) + (math.Sqrt2-1)*min(dx, dy)\n\t}\n\tfor len(open) > 0 {\n\t\tcur := slices.MinFunc(open, func(a, b P) int { return cmp.Compare(f(a), f(b)) })\n\t\topen = slices.DeleteFunc(open, func(p P) bool { return p == cur })\n\t\tif cur == goal {\n\t\t\tpath := []P{goal}\n\t\t\tfor p := goal; p != start; path = append([]P{p}, path...) {\n\t\t\t\tp = from[p]\n\t\t\t}\n\t\t\treturn path\n\t\t}\n\t\tfor _, d := range []P{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}} {\n\t\t\tn := P{cur.X + d.X, cur.Y + d.Y}\n\t\t\tg := cost[cur] + math.Hypot(float64(d.X), float64(d.Y))\n\t\t\tif old, seen := cost[n]; !c.Blocked(n) && !c.Blocked(P{n.X, cur.Y}) && !c.Blocked(P{cur.X, n.Y}) && (!seen || g < old) {\n\t\t\t\tcost[n], from[n] = g, cur\n\t\t\t\topen = append(open, n)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// Prune keeps only the cells that line of sight cannot skip, and returns\n// the length of the result.\nfunc Prune(c *CSpace, path []P) ([]P, float64) {\n\tclear := func(a, b P) bool {\n\t\tn := 4 * max(b.X-a.X, a.X-b.X, b.Y-a.Y, a.Y-b.Y, 1)\n\t\tfor i := 0; i <= n; i++ {\n\t\t\tt := float64(i) / float64(n)\n\t\t\tif c.Blocked(P{a.X + int(math.Round(t*float64(b.X-a.X))), a.Y + int(math.Round(t*float64(b.Y-a.Y)))}) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\tout, length := []P{path[0]}, 0.0\n\tfor i := 1; i < len(path); i++ {\n\t\tif last := out[len(out)-1]; i == len(path)-1 || !clear(last, path[i+1]) {\n\t\t\tout, length = append(out, path[i]), length+path[i].Centre().Sub(last.Centre()).Len()\n\t\t}\n\t}\n\treturn out, length\n}\n\n// survey maps from two hover points with three 360-beam sweeps each, then\n// comes back over home.\nfunc survey(sim *drone.Sim) *Map {\n\td, m := sim.Drone(), &Map{}\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(alt)\n\tfor i, p := range []drone.Vec3{home.Centre(), {X: 24.5, Y: -13.5, Z: alt}, home.Centre()} {\n\t\td.GoTo(p)\n\t\tsim.RunUntil(40, func(float64) bool { return d.Arrived() })\n\t\tfor sweep := 0; sweep < 3 && i < 2; sweep++ {\n\t\t\tpose := d.Telemetry().GPS\n\t\t\tfor i, r := range d.Scan(360) {\n\t\t\t\tm.Ray(pose, 2*math.Pi*float64(i)/360, r)\n\t\t\t}\n\t\t\tsim.Run(0.5, nil)\n\t\t}\n\t}\n\treturn m\n}\n\n// fly follows the waypoints and lands, scanning 72 beams on every step; it\n// returns the smallest reading.\nfunc fly(sim *drone.Sim, wps []P) float64 {\n\td, closest := sim.Drone(), drone.RangeMax\n\tfor i, p := range wps[1:] {\n\t\td.GoTo(p.Centre())\n\t\tsim.RunUntil(60, func(float64) bool {\n\t\t\tclosest = min(closest, slices.Min(d.Scan(72)))\n\t\t\tif i == len(wps)-2 {\n\t\t\t\treturn d.Arrived() || d.State().Mode == drone.Crashed\n\t\t\t}\n\t\t\treturn d.State().Pos.Sub(p.Centre()).Len() < 1 || d.State().Mode == drone.Crashed\n\t\t})\n\t}\n\td.Land()\n\tsim.RunUntil(30, func(float64) bool { return d.State().Pos.Z == 0 })\n\treturn closest\n}\n\nfunc main() {\n\tcfg := drone.Config{Wind: drone.Vec3{X: 1, Y: -2}, Gust: 1.5, MaxSpeed: 5, Seed: 11, GPSNoise: 0.05, Obstacles: obstacles}\n\tsims := []*drone.Sim{drone.New(cfg), drone.New(cfg)}\n\tm := survey(sims[0])\n\tsurvey(sims[1]) // the same seed flies the same survey and builds the same map\n\tfmt.Printf(\"occupied cells grown by %.1f m: %.1f airframe + %.1f margin + %.1f half-diagonal\\n\",\n\t\tinflate, vehicle, margin, cell*math.Sqrt2/2)\n\n\tspaces := []*CSpace{m.CSpace(true), m.CSpace(false)}\n\tvar plans, wps [2][]P\n\tfor i, name := range []string{\"unknown as free:\", \"unknown as blocked:\"} {\n\t\tif plans[i] = AStar(spaces[i], home, goal); plans[i] == nil {\n\t\t\tlog.Fatalf(\"%s no path\", name)\n\t\t}\n\t\tvar length float64\n\t\twps[i], length = Prune(spaces[i], plans[i])\n\t\tn := len(slices.DeleteFunc(slices.Clone(plans[i]), func(p P) bool { return !unknown(m[p.Y][p.X]) }))\n\t\tfmt.Printf(\"%-20s%d cells, %d unknown, %d waypoints, %.1f m\\n\", name, len(plans[i]), n, len(wps[i]), length)\n\t}\n\n\t// The careful planner's map with both plans and the mast no beam reached.\n\tvar rows [H][W]byte\n\tfor y := range H {\n\t\tfor x := range W {\n\t\t\trows[y][x] = '.'\n\t\t\tif l := m[y][x]; l >= 0.5 {\n\t\t\t\trows[y][x] = '#'\n\t\t\t} else if unknown(l) {\n\t\t\t\trows[y][x] = ' '\n\t\t\t} else if spaces[1][y][x] {\n\t\t\t\trows[y][x] = '+'\n\t\t\t}\n\t\t}\n\t}\n\tfor i, c := range []byte(\"o*\") {\n\t\tfor _, p := range plans[i] {\n\t\t\trows[p.Y][p.X] = c\n\t\t}\n\t}\n\tfor i, p := range []P{home, goal, cellOf(obstacles[2].X, obstacles[2].Y)} {\n\t\trows[p.Y][p.X] = \"HGM\"[i]\n\t}\n\tfor y := H - 1; y >= 0; y-- { // north up\n\t\tfmt.Printf(\"  |%s|\\n\", rows[y][:])\n\t}\n\n\tfor i, name := range []string{\"optimistic\", \"flight\"} {\n\t\tclosest := fly(sims[i], wps[i])\n\t\tevents := sims[i].Events()\n\t\tlast := events[len(events)-1]\n\t\tfmt.Printf(\"%s: %s at %.1f s; closest reading %.2f m, margin left %+.2f m\\n\",\n\t\t\tname, last.Text, last.T, closest, closest-vehicle-margin)\n\t\tif err := sims[i].SaveAs(name); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}","language":"go","title":"Plan both ways, fly both","walkthrough":"With unknown as free, A* finds 41 cells, 8 of them unknown, pruned to 3 waypoints and 42.3 m. The path goes north round the hall and straight through the unseen space behind it, past M. With unknown as blocked, the path needs 56 cells, 7 waypoints and 59.6 m, and it runs south of the tree, the hall and the tank through space the survey saw. Flown, the optimistic plan ends with 'hit mast at 27.1 s', a closest reading of 0.24 m and margin left -1.56 m. The careful plan lands at the goal at 44.8 s. Its closest reading on the whole flight was 2.93 m, which leaves 1.13 m beyond the 0.3 m airframe and the 1.5 m margin."},{"body":"The rangefinder makes the margin testable in flight. The closest return on any beam, minus the airframe radius, is the clearance. A program can log it, raise an alarm on it, or fail a simulation test on it, like the invariants in the simulation-testing lesson. A 72-beam scan leaves 5 degree gaps, 0.9 m wide at 10 m, so a thin pole can slip between beams at a distance, and real proximity sensors have similar blind wedges. The optimistic flight also shows the cure for its own failure. Seconds before the impact, as it rounded the hall, its beams were already ending on the mast, in cells the map had as unknown. A careful program treats such a return as a new map: it stops, adds the scan, rebuilds the configuration space and plans again, as the path-planning lesson did for a new restriction. Unknown as free with replanning is how exploration works. Unknown as free without replanning is a bet.","title":"Checking the margin, and replanning"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output lists two recordings, with the hall, tank, tree and mast drawn as grey discs: optimistic.gfflight ends at the mast, and flight.gfflight goes the long way round and lands at the goal. Set margin to 0.5 and the careful plan shortens from 59.6 m to 47.2 m. Set clearTo to 0, so that a beam without a return marks nothing, as in the previous lesson, and the program stops with 'unknown as blocked: no path'.","title":"Fly it in GopherForge"}],"takeaway":"Plan in configuration space: grow occupied cells by the airframe radius, a margin for tracking and map error, and half a cell's diagonal. Decide what unknown means before you plan. Blocked is safe but may find no path; free is short, and safe only while the vehicle keeps scanning and replans when a beam ends somewhere new. Measure the clearance in flight to prove the margin held.","title":"Configuration space: inflating your own map, deciding about unknown cells and flying the plan","unitID":"drones-autonomy","wrongAnswers":["Exactly one cell, whatever the cell size","The airframe radius only; the cells add no error"]},{"conceptTag":"drones.behaviour-trees","designGuide":{"cautions":["Conditions without hysteresis chatter at thresholds.","Restarted sequences repeat work unless steps are idempotent."],"cost":"Four node types, a blackboard, a fixed tick rate and a trace of every status change.","family":"drones","flow":["Conditions read the world","Safety branches first","Mission steps idempotent","Tick, trace, halt"],"ratings":[],"strengths":["A new reaction is one branch, not a row per state.","Priorities are visible in the order of the branches."]},"hint":"A Fallback lists alternatives in priority order. When does trying the next alternative stop making sense?","id":"drones.behaviour-trees","introduction":"The flight-modes lesson wrote the vehicle's modes as a transition table. A table works while every state can be listed, but autonomy adds reactions that apply everywhere: whatever the drone is doing, a low battery sends it home and an obstacle ahead stops it. In a table, each such reaction is a row from every state, plus a way back to whatever it interrupted. A behaviour tree writes each reaction once, as a branch in priority order, and evaluates the tree again on every control step. Game AI made behaviour trees popular, and robotics adopted them for the same reason: reactive behaviour that stays readable as it grows.","nuance":"Failure means this alternative does not apply, so the Fallback tries the next. Success or Running ends the tick there, which is why safety branches go first and halt the mission behind them.","objective":"Build a behaviour tree from Sequence, Fallback, Condition and Action nodes that return Success, Failure or Running, tick it at 10 Hz to fly 'inspect then return; on low battery return; on obstacle hold', trace its ticks deterministically and compare it with the flight-modes lesson's state machine.","question":"A reactive Fallback has three children: a battery-low branch, an obstacle branch and the mission. What does it return on a tick?","references":["https://en.wikipedia.org/wiki/Behavior_tree_(artificial_intelligence,_robotics_and_control)","https://github.com/BehaviorTree/BehaviorTree.CPP","https://docs.px4.io/main/en/flight_modes_mc/"],"reviewAnswer":"The first child status that is not Failure","reviewPrompt":"What does a Fallback return?","sections":[{"body":"Every node answers a tick with Success, Failure or Running, and Running means 'not finished, tick me again'. Conditions check the world and never command anything: battery below 30 percent, or an obstacle within 6 m ahead. Actions command the vehicle once when they start and then report progress: Running while the go-to flies, Success on arrival, Failure after a crash. A Sequence ticks its children in order and stops at the first that does not succeed, so it fits a guard followed by an action, or the steps of a mission. A Fallback, also called a Selector, ticks its children in order and stops at the first that does not fail, so its children are alternatives in priority order. Both are written here in their reactive form, like ReactiveSequence and ReactiveFallback in BehaviorTree.CPP. Every tick starts again from the first child, so conditions are checked again every 100 ms, and a running action is halted as soon as a condition before it changes.","code":"// Sequence ticks its children from the first on every tick and returns the\n// first status that is not Success (BehaviorTree.CPP's ReactiveSequence).\ntype Sequence []Node\n\n// Fallback ticks its children from the first on every tick and returns the\n// first status that is not Failure (ReactiveFallback): earlier children have\n// priority.\ntype Fallback []Node\n\nfunc (s Sequence) Tick() Status { return tick(s, Success) }\nfunc (f Fallback) Tick() Status { return tick(f, Failure) }\nfunc (s Sequence) Halt()        { halt(s) }\nfunc (f Fallback) Halt()        { halt(f) }\n\nfunc tick(children []Node, next Status) Status {\n\tfor i, c := range children {\n\t\tif st := c.Tick(); st != next {\n\t\t\thalt(children[i+1:]) // they may have been running on the last tick\n\t\t\treturn st\n\t\t}\n\t}\n\treturn next\n}","language":"go","title":"Four kinds of node, three answers","walkthrough":"The two composites differ in one value: a Sequence moves on while children return Success, a Fallback while they return Failure. Whatever stops the loop is returned, and every later child is halted, because one of them may have been running on the previous tick. When the obstacle condition starts to succeed, the obstacle branch returns Running, and the mission's go-to, further along the Fallback, is halted before the hold action commands the vehicle."},{"body":"The root is a Fallback of three branches, highest priority first. The first branch is battery below 30 percent, then return home. The second is an obstacle within 6 m on the line to the current target, then hold. The third is the mission: take off; inspect A, B and C with three seconds of photos each; return home. A reactive sequence restarts from its first child on every tick and after every halt, so mission steps must not repeat work. Each records its success on the blackboard, the state the nodes share, and answers Success at once from then on. The blackboard also carries the current target, and the obstacle condition looks along it with d.Range. That condition has hysteresis: it turns true below 6 m and false again only beyond 8 m. A hold stops the drone near the threshold, where 3 cm of sensor noise could flip a single-threshold condition on every tick and make the drone alternate between hold and go-to.","title":"The tree, and what Running means for a mission"},{"body":"Both flights tick the same tree at 10 Hz, one tick every five physics steps, to inspect a 40 m tower from three points 10 m away at 12 m altitude. The first flight starts on a full battery on a clear site. The second starts on 35 percent, with a crane standing on the leg from A to B. The trace prints a line whenever the ticked action, its status or the vehicle's mode changes, together with the condition that put a safety branch in charge.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\ntype Status int\n\nconst (\n\tFailure Status = iota\n\tSuccess\n\tRunning\n)\n\nfunc (s Status) String() string { return [...]string{\"FAILURE\", \"SUCCESS\", \"RUNNING\"}[s] }\n\n// Node is ticked on every control step. Halt stops a node that was running\n// when a branch before it takes over.\ntype Node interface {\n\tTick() Status\n\tHalt()\n}\n\n// Sequence ticks its children from the first on every tick and returns the\n// first status that is not Success (BehaviorTree.CPP's ReactiveSequence).\ntype Sequence []Node\n\n// Fallback ticks its children from the first on every tick and returns the\n// first status that is not Failure (ReactiveFallback): earlier children have\n// priority.\ntype Fallback []Node\n\nfunc (s Sequence) Tick() Status { return tick(s, Success) }\nfunc (f Fallback) Tick() Status { return tick(f, Failure) }\nfunc (s Sequence) Halt()        { halt(s) }\nfunc (f Fallback) Halt()        { halt(f) }\n\nfunc tick(children []Node, next Status) Status {\n\tfor i, c := range children {\n\t\tif st := c.Tick(); st != next {\n\t\t\thalt(children[i+1:]) // they may have been running on the last tick\n\t\t\treturn st\n\t\t}\n\t}\n\treturn next\n}\n\nfunc halt(nodes []Node) {\n\tfor _, n := range nodes {\n\t\tn.Halt()\n\t}\n}\n\n// Blackboard is what the nodes share.\ntype Blackboard struct {\n\tActive, Why string          // the action ticked last, and the condition behind it\n\tDone        map[string]bool // mission steps already achieved\n\tTarget      drone.Vec3      // where the vehicle is meant to fly\n}\n\n// Condition checks the world; it never commands the vehicle.\ntype Condition struct {\n\tbb   *Blackboard\n\tTest func() (bool, string)\n}\n\nfunc (c *Condition) Tick() Status {\n\tif ok, why := c.Test(); ok {\n\t\tc.bb.Why = why\n\t\treturn Success\n\t}\n\treturn Failure\n}\nfunc (c *Condition) Halt() {}\n\n// Action commands the vehicle once when it starts, then reports progress.\n// A mission step (Once) keeps reporting Success after it has succeeded, so a\n// sequence restarted from its first child skips what is already done.\ntype Action struct {\n\tName    string\n\tbb      *Blackboard\n\tOnce    bool\n\tStart   func() error\n\tCheck   func() Status\n\trunning bool\n}\n\nfunc (a *Action) Tick() Status {\n\tif a.Once && a.bb.Done[a.Name] {\n\t\treturn Success\n\t}\n\tif !a.running {\n\t\tif err := a.Start(); err != nil {\n\t\t\treturn Failure\n\t\t}\n\t\ta.running = true\n\t}\n\ta.bb.Active = a.Name\n\tst := a.Check()\n\tif st != Running {\n\t\ta.running = false\n\t\ta.bb.Done[a.Name] = a.Once && st == Success\n\t}\n\treturn st\n}\nfunc (a *Action) Halt() { a.running = false }\n\nconst alt = 12.0\n\n// tree is \"inspect then return; on low battery return; on obstacle hold\".\nfunc tree(sim *drone.Sim, d *drone.Drone, bb *Blackboard) Node {\n\t// until is Running until done holds, and Failure after a crash.\n\tuntil := func(done func() bool) func() Status {\n\t\treturn func() Status {\n\t\t\tswitch {\n\t\t\tcase d.State().Mode == drone.Crashed:\n\t\t\t\treturn Failure\n\t\t\tcase done():\n\t\t\t\treturn Success\n\t\t\t}\n\t\t\treturn Running\n\t\t}\n\t}\n\thome := func(branch string) *Action {\n\t\treturn &Action{Name: branch + \"/return home\", bb: bb, Once: true,\n\t\t\tStart: func() error { bb.Target = d.Home(); return d.ReturnHome() },\n\t\t\tCheck: until(func() bool { return d.State().Landed })}\n\t}\n\tinspect := func(name string, p drone.Vec3) *Action {\n\t\tsince := -1.0\n\t\treturn &Action{Name: \"mission/inspect \" + name, bb: bb, Once: true,\n\t\t\tStart: func() error { bb.Target, since = p, -1; return d.GoTo(p) },\n\t\t\tCheck: until(func() bool {\n\t\t\t\tif since < 0 && d.Arrived() {\n\t\t\t\t\tsince = sim.Time()\n\t\t\t\t}\n\t\t\t\treturn since >= 0 && sim.Time()-since >= 3 // three seconds of photos\n\t\t\t})}\n\t}\n\tnear := false\n\treturn Fallback{\n\t\tSequence{\n\t\t\t&Condition{bb, func() (bool, string) {\n\t\t\t\tb := d.Telemetry().Battery\n\t\t\t\treturn b < 30, fmt.Sprintf(\"battery %.0f%%\", b)\n\t\t\t}},\n\t\t\thome(\"battery\"),\n\t\t},\n\t\tSequence{\n\t\t\t&Condition{bb, func() (bool, string) {\n\t\t\t\tto := bb.Target.Sub(d.State().Pos).Horizontal()\n\t\t\t\tr := d.Range(math.Atan2(to.Y, to.X))\n\t\t\t\tnear = r < to.Len() && (r < 6 || near && r < 8) // hysteresis: no chatter\n\t\t\t\treturn near, fmt.Sprintf(\"obstacle %.1f m ahead\", r)\n\t\t\t}},\n\t\t\t&Action{Name: \"obstacle/hold\", bb: bb, Start: d.Hold, Check: func() Status { return Running }},\n\t\t},\n\t\tSequence{\n\t\t\t&Action{Name: \"mission/take off\", bb: bb, Once: true, Check: until(d.Arrived),\n\t\t\t\tStart: func() error {\n\t\t\t\t\tif err := d.Arm(); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn d.TakeOff(alt)\n\t\t\t\t}},\n\t\t\tinspect(\"A\", drone.Vec3{X: 30, Y: -10, Z: alt}),\n\t\t\tinspect(\"B\", drone.Vec3{X: 40, Z: alt}),\n\t\t\tinspect(\"C\", drone.Vec3{X: 30, Y: 10, Z: alt}),\n\t\t\thome(\"mission\"),\n\t\t},\n\t}\n}\n\nfunc fly(title, file string, cfg drone.Config) {\n\tsim := drone.New(cfg)\n\td := sim.Drone()\n\tbb := &Blackboard{Done: map[string]bool{}}\n\troot := tree(sim, d, bb)\n\tfmt.Println(title)\n\tlast, ticks := \"\", 0\n\tfor st := Running; st == Running && sim.Time() < 300; ticks++ {\n\t\tbb.Why = \"\"\n\t\tst = root.Tick() // 10 Hz: one tick every five physics steps\n\t\tif line := fmt.Sprintf(\"%-20s %-8s %-7s\", bb.Active, st, d.State().Mode); line != last {\n\t\t\tfmt.Printf(\"  %5.1f s  %s\\n\", sim.Time(), strings.TrimSpace(line+\" \"+bb.Why))\n\t\t\tlast = line\n\t\t}\n\t\tsim.Run(0.1, nil)\n\t}\n\tfmt.Printf(\"  %d ticks, battery %.0f%%\\n\", ticks, d.State().Battery)\n\tif err := sim.SaveAs(file); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\ttower := drone.Obstacle{Name: \"tower\", X: 30, Radius: 1.5, Height: 40}\n\tcrane := drone.Obstacle{Name: \"crane\", X: 37, Y: -3, Radius: 1.5, Height: 25}\n\twind := drone.Vec3{X: 2, Y: 1}\n\tfly(\"clear site, battery 100%:\", \"clear\", drone.Config{Wind: wind, Gust: 1, MaxSpeed: 5, Seed: 4,\n\t\tObstacles: []drone.Obstacle{tower}})\n\tfly(\"crane on the leg to B, battery 35%:\", \"flight\", drone.Config{Wind: wind, Gust: 1, MaxSpeed: 5, Seed: 4,\n\t\tBattery: 35, Obstacles: []drone.Obstacle{tower, crane}})\n}","language":"go","title":"Two flights, one tree","walkthrough":"On the clear site only the mission branch runs. After the take-off, each inspection shows GOTO and then HOLD while the photos are taken, the return home goes RTL and then LAND, and the root succeeds at 50.1 s after 502 ticks with 89 percent left. In the second flight the first four lines are the same. At 17.0 s, 0.9 s after inspect B started, 'obstacle 5.6 m ahead' puts obstacle/hold in charge and halts the go-to. The drone holds for 9.6 s, until the battery branch, earlier in the Fallback, takes over at 26.6 s with 'battery 29%' and flies home. The root succeeds at 46.7 s with 25 percent left, and B and C are never inspected. Neither safety branch knows about the other; their order sets the priority."},{"body":"As a transition table in the style of the flight-modes lesson, this behaviour needs a state per mission step (TAKEOFF, INSPECT_A, INSPECT_B, INSPECT_C, RETURN) plus HOLD and RTL. Battery low needs a row from each airborne state to RTL, and the obstacle a row from each moving state to HOLD. HOLD then needs a way back to the step it interrupted, which a flat table can express only with one HOLD state per step or a remembered history. Every new reaction multiplies the rows, while in the tree it is one more branch in the right place. The table still wins where it is strong: it lists every allowed transition, rejects everything else with a reason, and can be checked for completeness. Autopilots keep their own modes as explicit state machines, and the tree here commands those modes rather than replacing them. When the autopilot changes mode by itself, a condition should notice, just as the flight-modes lesson reconciles its table with the vehicle.","title":"The same behaviour as a state machine"},{"body":"A tree reacts only as fast as it is ticked. At 10 Hz a drone at 5 m/s moves 0.5 m between ticks, which is why the obstacle was 5.6 m ahead, not 6.0 m, when the hold began. Long actions never block a tick: they command, return Running and check again on the next tick. Halt must be cheap and must leave the vehicle ready for the next command. Here it only forgets that an action had started, and the branch that takes over sends the new command. The tree reads the world only through conditions and is ticked by the program, so a test can drive it with a scripted vehicle and assert the trace, and the two flights here are such tests. BehaviorTree.CPP, a C++ library whose main use is robotics, adds asynchronous actions, trees loaded from XML at run time, and logging that records every status change for replay and analysis, for example in its Groot2 editor.","title":"Tick rate, halting and tests"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output lists clear.gfflight, the full inspection, and flight.gfflight, in which the drone stops short of the crane and flies home on a low battery; the timeline shows each go-to, the hold and the return. Start the second flight on 60 percent and the hold lasts until 159.2 s, when the battery reaches 29 percent. Move the crane to Y: -15, off the leg, and the battery branch interrupts the go-to C instead, at 25.8 s.","title":"Fly it in GopherForge"}],"takeaway":"A behaviour tree ticks Sequences, Fallbacks, Conditions and Actions on every control step, and each node answers Success, Failure or Running. Put safety branches first in a reactive Fallback, guard each with a condition, and halt whatever they pre-empt. Give conditions hysteresis, and make mission steps idempotent so that restarting a sequence costs nothing. Keep the autopilot's own mode machine underneath.","title":"Behaviour trees for autonomy: sequences, fallbacks, conditions and actions ticked every step","unitID":"drones-autonomy","wrongAnswers":["Success only when all three children succeed","The mission's status, after ticking every branch"]},{"conceptTag":"drones.precision-landing","designGuide":{"cautions":["The last half metre is flown blind.","False detections need a jump test or a marker ID."],"cost":"A downward sensor, a 10 Hz centring loop with a gate and an abort counter, and LANDING_TARGET on the companion link.","family":"drones","flow":["Approach on GPS","Centre on the beacon","Descend inside the gate","Abort, climb, retry"],"ratings":[],"strengths":["Touchdown error drops from metres to centimetres.","Gates and aborts make sensor faults visible."]},"hint":"Think about what the gate already handles by pausing the descent, and what it cannot handle: no reading at all, or a reading that jumps far outside the gate low down.","id":"drones.precision-landing","introduction":"GPS puts a drone within a metre or two of a point. That is fine for a field, but not for a charging pad, a box on a ship or a dock with contacts. Precision landing adds a sensor that sees the pad itself, usually a downward camera that finds a light beacon or a printed marker, and reports where the pad is relative to the drone. The control problem is then simple. The hard part is deciding when to trust the sensor, when to keep descending and when to give up and climb.","nuance":"A small error only pauses the descent until the drone is centred again. Losing the pad, or a jump far outside the gate near the ground, means the sensor or the wind has won, so climb back to where the pad is easy to see.","objective":"Compare a GPS-only landing on a pad with a beacon-guided one in gusty wind: centre on the beacon's offset with a PI loop, descend only inside a gate that narrows with height, abort and climb back when the pad is out of view or the error jumps near the ground, and cap the retries.","question":"A beacon-guided landing descends while centring on the pad. Which events should make it stop, climb back and retry?","references":["https://docs.px4.io/main/en/advanced_features/precland","https://ardupilot.org/copter/docs/precision-landing-and-loiter.html","https://mavlink.io/en/services/landing_target.html"],"reviewAnswer":"Pad out of view too long, or error jumps near ground","reviewPrompt":"When does the landing abort?","sections":[{"body":"A GPS landing flies to the pad's coordinates and lands where the position estimate says the pad is, so the touchdown error is the estimate's error at that moment. A navigation filter smooths the receiver's jitter but not its slow wander, and the wander is the larger part. In this simulator the GPS error has a slow part of about 0.64 m per axis that wanders over about 20 s, plus 0.48 m of jitter, so averaging a few seconds of fixes removes the jitter but not the wander. One detail matters for the comparison. The simulator's autopilot flies on its true position, while a real autopilot flies on its estimate. To reproduce a real vehicle, landGPS moves the target by the estimate's error, taken as the GPS error averaged over 5 s, and then lands with the autopilot's own Land.","title":"What GPS alone can do"},{"body":"d.Beacon() returns the pad's offset from the drone when the pad lies within 40 degrees of straight down and the drone is between 0.5 and 30 m up, with noise of 2 cm plus 1 percent of the distance. Over MAVLink the same information travels in LANDING_TARGET, which a companion computer sends at 10 to 50 Hz, either as angles in the camera image or, in MAVLink 2, as a position. PX4 accepts the position only in MAV_FRAME_LOCAL_NED and ignores the angles; ArduPilot accepts it only in MAV_FRAME_BODY_FRD. The landing loop runs at 10 Hz. It commands a horizontal velocity of 1.2 times the offset plus 0.3 times its integral, which takes up the part of the gusts the velocity loop leaves. It descends only while the error is inside a gate of 0.2 m plus 8 percent of the height, 1.0 m at 10 m and 0.28 m at 1 m, and it slows to 0.5 m/s near the pad. Outside the gate it holds its height and centres. The camera loses the pad below 0.5 m, so the drone flies the last half metre straight down. Both flight stacks make the same choice close to the ground: PX4 keeps descending in its final approach, and ArduPilot keeps descending below PLND_ALT_MIN.","title":"Seeing the pad: offsets, gates and the last metre"},{"body":"Three pads stand 20 to 46 m from home, in a 5.4 m/s wind with 3 m/s gusts. Over each pad the drone takes off to 10 m and lands on GPS alone, then takes off again and lands on the beacon. Two faults are injected into the beacon below 3 m, each lasting 1.5 s: over pad 2 a glint blinds the camera, and over pad 3 a reflection is detected 1.5 m beside the pad. The program prints each touchdown's distance from the pad centre, the descent time and the number of aborts.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tapproach = 10.0 // m: where a landing starts and where a retry climbs back to\n\ttimeout  = 1.0  // s without the pad in view before an abort\n\tretries  = 3    // aborts before giving up on the sensor\n\tfinal    = 1.0  // m: below this, keep centring if the pad is in view and go down\n)\n\nvar pads = []drone.Vec3{{X: 20, Y: 5}, {X: 45, Y: -10}, {X: 30, Y: 25}}\n\n// faults are injected into the beacon over each pad: none, a glint that\n// blinds the camera, a reflection detected 1.5 m beside the pad.\nvar faults = []struct {\n\tblind bool\n\tshift drone.Vec3\n}{{}, {blind: true}, {shift: drone.Vec3{X: 1.5}}}\n\n// Sensor reports the pad's horizontal offset from the drone, if it sees it.\ntype Sensor func() (drone.Vec3, bool)\n\n// landGPS lands without the beacon, the way an autopilot does on GPS: it\n// holds the point its estimate says is over the pad and lands there. The\n// simulator's autopilot flies on the true position, so the program moves the\n// target by the estimate's error: the GPS error averaged over 5 s, because a\n// navigation filter removes the jitter but not the slow wander. It returns\n// when the descent began.\nfunc landGPS(sim *drone.Sim, d *drone.Drone, pad drone.Vec3) float64 {\n\tover := drone.Vec3{X: pad.X, Y: pad.Y, Z: approach}\n\td.GoTo(over)\n\tsim.RunUntil(60, func(float64) bool { return d.Arrived() })\n\tvar bias drone.Vec3\n\tsim.Run(5, func(float64) {\n\t\tbias = bias.Add(d.Telemetry().GPS.Sub(d.State().Pos).Horizontal().Scale(sim.Dt() / 5))\n\t})\n\td.GoTo(over.Sub(bias))\n\tsim.RunUntil(60, func(float64) bool { return d.Arrived() })\n\tsim.Run(5, nil) // settle\n\tstart := sim.Time()\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool { return d.State().Landed })\n\treturn start\n}\n\n// land descends onto a pad while centring on what the sensor reports. It\n// descends only inside a gate that narrows with height, aborts when the pad\n// is out of view for longer than timeout or the error grows near the ground,\n// climbs back to the approach height and tries again.\nfunc land(sim *drone.Sim, d *drone.Drone, sense Sensor) (aborts int) {\n\tlost, sum := 0.0, drone.Vec3{}\n\tfor !d.State().Landed && sim.Time() < 900 {\n\t\th := d.State().Pos.Z // height from a rangefinder or the barometer\n\t\toff, seen := sense()\n\t\te, gate := off.Len(), 0.2+0.08*h\n\t\twhy := \"\"\n\t\tswitch {\n\t\tcase h == 0:\n\t\t\td.Land() // on the ground: disarm\n\t\tcase h < final && !seen:\n\t\t\td.SetVelocity(drone.Vec3{Z: -1}, 0) // under the camera's range: straight down\n\t\tcase !seen:\n\t\t\tif lost += 0.1; lost >= timeout {\n\t\t\t\twhy = fmt.Sprintf(\"pad out of view for %.0f s\", timeout)\n\t\t\t} else {\n\t\t\t\td.SetVelocity(drone.Vec3{}, 0) // stop and look again\n\t\t\t}\n\t\tcase h < 4 && e > 3*gate:\n\t\t\twhy = fmt.Sprintf(\"off by %.2f m, gate %.2f m\", e, gate)\n\t\tdefault:\n\t\t\tlost = 0\n\t\t\tv := off.Scale(1.2).Add(sum.Scale(0.3)) // PI: the integral takes up the gusts' push\n\t\t\tif e < gate {\n\t\t\t\tsum = sum.Add(off.Scale(0.1))             // integrate only while centred\n\t\t\t\tv.Z = -math.Max(0.5, math.Min(1, 0.25*h)) // slower near the pad\n\t\t\t}\n\t\t\td.SetVelocity(v, 0)\n\t\t}\n\t\tif why != \"\" {\n\t\t\taborts++\n\t\t\tfmt.Printf(\"    %5.1f s  abort %d at %.1f m: %s; climb to %.0f m, retry\\n\", sim.Time(), aborts, h, why, approach)\n\t\t\tif aborts > retries {\n\t\t\t\td.Land() // give up on the sensor: land where it is\n\t\t\t\tsim.RunUntil(60, func(float64) bool { return d.State().Landed })\n\t\t\t\tbreak\n\t\t\t}\n\t\t\td.SetVelocity(drone.Vec3{Z: 2}, 0) // climb straight up, then search\n\t\t\tsim.RunUntil(10, func(float64) bool { return d.State().Pos.Z >= approach-0.5 })\n\t\t\tlost, sum = 0, drone.Vec3{}\n\t\t\tcontinue\n\t\t}\n\t\tsim.Run(0.1, nil)\n\t}\n\treturn aborts\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 5, Y: 2}, Gust: 3, MaxSpeed: 6, Seed: 21, Pads: pads})\n\td := sim.Drone()\n\tfmt.Println(\"three pads, 5.4 m/s wind with 3 m/s gusts; error = touchdown to pad centre\")\n\tvar sums [2]float64\n\tfor i, pad := range pads {\n\t\t// beacon is the downward camera with the fault this pad injects for\n\t\t// 1.5 s once the drone is below 3 m.\n\t\tf, began := faults[i], -1.0\n\t\tbeacon := func() (drone.Vec3, bool) {\n\t\t\toff, ok := d.Beacon()\n\t\t\tif began < 0 && d.State().Pos.Z < 3 {\n\t\t\t\tbegan = sim.Time()\n\t\t\t}\n\t\t\tif began >= 0 && sim.Time() < began+1.5 {\n\t\t\t\tif f.blind {\n\t\t\t\t\treturn drone.Vec3{}, false\n\t\t\t\t}\n\t\t\t\toff = off.Add(f.shift)\n\t\t\t}\n\t\t\treturn off.Horizontal(), ok\n\t\t}\n\t\tfor k, name := range []string{\"GPS\", \"beacon\"} {\n\t\t\tif err := d.Arm(); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\td.TakeOff(approach)\n\t\t\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\t\t\tvar start float64\n\t\t\taborts := 0\n\t\t\tif k == 0 {\n\t\t\t\tstart = landGPS(sim, d, pad)\n\t\t\t} else {\n\t\t\t\td.GoTo(drone.Vec3{X: pad.X, Y: pad.Y, Z: approach})\n\t\t\t\tsim.RunUntil(60, func(float64) bool { return d.Arrived() })\n\t\t\t\tstart, aborts = sim.Time(), land(sim, d, beacon)\n\t\t\t}\n\t\t\tmiss := d.State().Pos.Sub(pad).Horizontal().Len()\n\t\t\tsums[k] += miss\n\t\t\tfmt.Printf(\"  pad %d %-7s %.2f m off, descent %4.1f s, %d aborts\\n\", i+1, name, miss, sim.Time()-start, aborts)\n\t\t}\n\t}\n\tfmt.Printf(\"mean error: GPS %.2f m, beacon %.2f m\\n\", sums[0]/3, sums[1]/3)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Three pads, two landings each","walkthrough":"The GPS landings miss by 1.13, 1.37 and 1.24 m, a mean of 1.25 m, each after a 9.5 s descent. The beacon lands 0.09 m off on pad 1 in 13.8 s, slower because it descends only while centred. Over pad 2 the glint hides the pad at 2.8 m. After 1 s the loop aborts and climbs back to 10 m, where the pad is in view again, and the second descent lands 0.25 m off; the whole descent takes 27.0 s. Over pad 3 the false detection makes the error jump to 1.75 m at 3.0 m, more than three times the 0.44 m gate. The loop aborts the same way and lands 0.20 m off. The mean beacon error is 0.18 m. What scatter remains comes from the gusts, which the loop cannot fully cancel in the blind last half metre."},{"body":"A landing that cannot see its target, or sees it jump away near the ground, should not continue. The gate pauses the descent for small errors; an abort climbs back to a height where the pad is easy to see. Two rules trigger an abort here: the pad out of view for 1 s, and below 4 m an error above three times the gate, which is what a false detection or a strong gust produces. After three aborts the loop gives up on the sensor and lands where it is, the safe choice over a field. Both flight stacks expose the same decisions. PX4 waits PLD_BTOUT (5 s by default) before it declares the target lost and starts descending only inside PLD_HACC_RAD (0.2 m by default). In Required mode it climbs to PLD_SRCH_ALT to search, at most PLD_MAX_SRCH times. ArduPilot does not descend while the target is more than PLND_XY_DIST_MAX away. Its PLND_STRICT chooses what follows the retries, up to PLND_RET_MAX: either a normal landing, or a hover for a deck where landing beside the pad means landing in the water. The 1 s timeout here keeps the example short; a real one weighs the camera's dropouts against the drift while blind.","title":"Aborts, retries and when to give up"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output replays all six landings in flight.gfflight: the pads are teal squares, and the two aborts show as climbs back to 10 m in the altitude strip. Remove the faults, or set Gust to 0 to see how small the beacon's own error is. Widen the gate to 0.5 m plus 10 percent of the height and compare the touchdowns.","title":"Fly it in GopherForge"}],"takeaway":"GPS lands a drone within its estimate's slow wander, about a metre here, and a beacon that sees the pad brings that down to tens of centimetres. Centre on the beacon's offset with a PI loop, descend only inside a gate that narrows with height, and abort and climb back when the pad is out of view or the error jumps near the ground. Cap the retries, and go straight down for the part the sensor cannot see.","title":"Precision landing on a beacon: centring while descending, gates, aborts and retries","unitID":"drones-autonomy","wrongAnswers":["Any beacon reading that differs from the last by 2 cm","Only a GPS fix that disagrees with the beacon by 1 m"]},{"conceptTag":"drones.gps-denied","designGuide":{"cautions":["Hold is impossible without a position estimate.","The autopilot lands on its own timer, whatever you ask."],"cost":"A content check on every position stream, a written outage policy that matches the autopilot configuration, and routes planned for sky view.","family":"drones","flow":["Watch flag and repeats","Expect drift in wind","Agree with the failsafe","Plan to avoid outages"],"ratings":[],"strengths":["Content checks catch a frozen fix within 0.3 s.","Policy runs show which action suits a site."]},"hint":"The reports keep arriving on time, so look at what they say, not when they came. What would real GPS noise never do?","id":"drones.gps-denied","introduction":"GPS fails in ordinary places: between tall buildings, under a bridge, beside large steel structures, or near radio interference. Without a position, a multicopter autopilot still holds its attitude and, with a barometer, its height. What it loses is the ability to stay over a point, and in wind that means drifting downwind while the telemetry keeps looking healthy. The ground station has to notice the outage, and the program has to decide what to ask for. Whatever the program decides, the autopilot's own failsafe will act.","nuance":"Message age checks the link, not the source. Telemetry can be fresh while its position is frozen, so check the receiver's fix flag and treat exactly repeated positions as a dead source.","objective":"Detect a GPS outage at the ground station from the fix flag and repeated positions rather than message age, measure how far a drone drifts in wind when its autopilot can only keep level, watch the 'no GPS for 3 s: landing' failsafe act, and compare hold, land and climb policies in an urban canyon with the failsafe on and off.","question":"During a GPS outage the ground station still receives a position report every 0.2 s. Which checks reveal that the position is stale?","references":["https://docs.px4.io/main/en/config/safety","https://ardupilot.org/copter/docs/common-ekf-inav-failsafe.html","https://mavlink.io/en/messages/common.html#GPS_RAW_INT"],"reviewAnswer":"Fix flag, and identical positions in repeated reports","reviewPrompt":"How to spot a frozen GPS fix?","sections":[{"body":"Position and velocity both come from the receiver; the gyros and accelerometers keep the attitude, and the barometer the height. Position integrated from acceleration drifts within seconds, so the autopilot cannot hold a point for long. In the simulator, d.LoseGPS(seconds) takes the fix away: GPSFix() turns false, Telemetry().GPS and .Velocity freeze at the last report, and the autopilot keeps the drone level, so the wind accelerates it until it moves with the air. Real flight stacks first dead-reckon on their inertial sensors. PX4 declares the position lost when it has dead-reckoned for EKF2_NOAID_TOUT, or, for a hovering vehicle, when the horizontal error exceeds COM_POS_FS_EPH. Its position loss failsafe then puts a multicopter in an autonomous mode into Return, else Land, else Descend, which needs no position. In a manual position mode it switches to Altitude mode instead. ArduPilot's EKF failsafe fires when two of its compass, position and velocity variances stay above FS_EKF_THRESH for 1 s. By default FS_EKF_ACTION then lands, in the modes that need a position.","title":"What the vehicle knows without a fix"},{"body":"Telemetry keeps arriving during an outage, so the staleness check from the telemetry-streams lesson, the age of the newest report, finds nothing wrong: every report is fresh, but its content is old. Three checks do catch it. The first is the receiver's own flag: in MAVLink, fix_type in GPS_RAW_INT drops below GPS_FIX_TYPE_3D_FIX and satellites_visible falls; in the simulator, GPSFix() turns false. The second is repetition: real GPS noise never reports exactly the same position twice, so three identical reports mean a frozen source. The third is consistency: a position that does not move while the vehicle reports tilt, airspeed or a moving camera image is wrong. Apply the same checks to the fused position in GLOBAL_POSITION_INT, because an autopilot may keep publishing a dead-reckoned estimate for a while after the receiver went quiet.","title":"Spotting a stale fix at the ground station"},{"body":"The program first hovers at 20 m in a 5 m/s wind with gusts and takes the fix away for 20 s. A ground-station loop reads every 5 Hz report, counts identical reports and tracks the age of the newest one. It prints the first three reports, then one every 2 s, next to the true drift, which only the simulator knows. Then it flies a street six times: east at 10 m along a 26 m wide street between 25 m buildings, with a 4 m/s wind blowing across it. Between the rows and below the roofs, the program's world model takes the sky away. The program reacts to the lost fix with one of three policies: hold, land, or climb at 3 m/s. It flies each policy once with the simulator's failsafe on and once with it off. The runs with the failsafe off stand for an autopilot configured with that action, not for switching safety off.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst roof = 25.0 // height of the buildings along the street, m\n\n// openField hovers at 20 m in wind, loses GPS for 20 s and watches the\n// telemetry the way a ground station receives it.\nfunc openField() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 5}, Gust: 1.5, Seed: 8})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(20)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tsim.Run(2, nil)\n\tfmt.Println(\"hover at 20 m, 5 m/s wind: GPS lost for 20 s at +0.0 s\")\n\tfmt.Println(\"     t   report  GPS position         fix  same  true drift  mode\")\n\tt0, start := sim.Time(), d.State().Pos\n\td.LoseGPS(20)\n\tlast, same, flagAt, frozenAt, maxAge, reports := d.Telemetry(), 0, -1.0, -1.0, 0.0, 0\n\tsim.RunUntil(20, func(t float64) bool {\n\t\ttel := d.Telemetry()\n\t\tif !d.GPSFix() && flagAt < 0 {\n\t\t\tflagAt = t - t0 // the receiver's own flag, GPS_RAW_INT.fix_type in MAVLink\n\t\t}\n\t\tmaxAge = math.Max(maxAge, t-tel.Time) // how old the newest report is\n\t\tif tel.Time == last.Time {\n\t\t\treturn d.State().Landed\n\t\t}\n\t\tif tel.GPS == last.GPS && tel.Velocity == last.Velocity {\n\t\t\tsame++ // real GPS noise never repeats a position exactly\n\t\t} else {\n\t\t\tsame = 0\n\t\t}\n\t\tif same == 2 && frozenAt < 0 {\n\t\t\tfrozenAt = t - t0\n\t\t}\n\t\tif reports++; reports <= 3 || reports%10 == 0 { // the first three, then every 2 s\n\t\t\tfmt.Printf(\"  %+5.1f  %+5.1f  %-20v %-5v %4d  %6.1f m    %v\\n\", t-t0, tel.Time-t0, tel.GPS, d.GPSFix(), same,\n\t\t\t\td.State().Pos.Sub(start).Horizontal().Len(), d.State().Mode)\n\t\t}\n\t\tlast = tel\n\t\treturn d.State().Landed\n\t})\n\tfmt.Printf(\"detected: fix flag at %+.1f s, frozen position at %+.1f s; newest report never older than %.1f s\\n\",\n\t\tflagAt, frozenAt, maxAge)\n\tfor _, e := range sim.Events() {\n\t\tif e.T >= t0 {\n\t\t\tfmt.Printf(\"  %+5.1f s  %s\\n\", e.T-t0, e.Text)\n\t\t}\n\t}\n\tfmt.Printf(\"touched down %.1f m downwind of where the fix was lost\\n\", d.State().Pos.Sub(start).Horizontal().Len())\n\tif err := sim.SaveAs(\"open-field\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n// street is two rows of overlapping buildings: a 26 m wide street along X.\nfunc street() []drone.Obstacle {\n\tvar out []drone.Obstacle\n\tfor i := range 12 {\n\t\tx := 30 + 8*float64(i)\n\t\tout = append(out, drone.Obstacle{Name: fmt.Sprintf(\"north %d\", i+1), X: x, Y: 18, Radius: 5, Height: roof},\n\t\t\tdrone.Obstacle{Name: fmt.Sprintf(\"south %d\", i+1), X: x, Y: -18, Radius: 5, Height: roof})\n\t}\n\treturn out\n}\n\n// canyon flies east along the street at 10 m with the wind blowing across\n// it. Between the buildings and below the roofs the sky is blocked; when the\n// program sees the fix go, it applies its policy.\nfunc canyon(policy string, failsafe bool) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{Y: 4}, Gust: 1, MaxSpeed: 4, Seed: 5,\n\t\tObstacles: street(), NoFailsafe: !failsafe})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\td.GoTo(drone.Vec3{X: 150, Z: 10})\n\tlostAt, acted, hitAt := -1.0, false, -1.0\n\tsim.RunUntil(80, func(t float64) bool {\n\t\tp := d.State().Pos\n\t\t// The world: no satellites in view between the rows, below the roofs.\n\t\tif p.X > 25 && p.X < 125 && p.Z < roof+1 {\n\t\t\td.LoseGPS(1)\n\t\t}\n\t\t// The program: act once on a lost fix; after a climb, hold above the roofs.\n\t\tswitch {\n\t\tcase !d.GPSFix() && !acted:\n\t\t\tlostAt, acted = t, true\n\t\t\tswitch policy {\n\t\t\tcase \"hold\":\n\t\t\t\td.Hold()\n\t\t\tcase \"land\":\n\t\t\t\td.Land()\n\t\t\tcase \"climb\":\n\t\t\t\td.SetVelocity(drone.Vec3{Z: 3}, 0)\n\t\t\t}\n\t\tcase policy == \"climb\" && acted && d.GPSFix() && d.State().Mode == drone.Velocity:\n\t\t\td.Hold()\n\t\t}\n\t\tst := d.State()\n\t\tif st.Mode == drone.Crashed && hitAt < 0 {\n\t\t\thitAt = st.Pos.Z\n\t\t}\n\t\treturn st.Landed || st.Mode == drone.Crashed && st.Pos.Z == 0 || acted && d.GPSFix() && st.Mode == drone.Hold && t-lostAt > 15\n\t})\n\tvar notes []string\n\tfor _, e := range sim.Events() {\n\t\tif strings.HasPrefix(e.Text, \"hit\") {\n\t\t\te.Text += fmt.Sprintf(\" at %.1f m\", hitAt)\n\t\t}\n\t\tif lostAt >= 0 && e.T >= lostAt && !strings.HasPrefix(e.Text, \"GPS lost\") && e.Text != \"land\" {\n\t\t\tnotes = append(notes, fmt.Sprintf(\"%+.1f %s\", e.T-lostAt, e.Text))\n\t\t}\n\t}\n\tp := d.State().Pos\n\tfmt.Printf(\"  %-5s %-3s  %s; y %.1f m, z %.1f m\\n\", policy, map[bool]string{true: \"on\", false: \"off\"}[failsafe],\n\t\tstrings.Join(notes, \", \"), p.Y, p.Z)\n\treturn sim\n}\n\nfunc main() {\n\topenField()\n\tfmt.Println(\"\\nstreet: 10 m up, 26 m between 25 m buildings, 4 m/s wind across it\")\n\tfmt.Println(\"  policy, failsafe: seconds after the program saw the fix go; where it ended (y north)\")\n\tvar replay *drone.Sim\n\tfor _, failsafe := range []bool{true, false} {\n\t\tfor _, policy := range []string{\"hold\", \"land\", \"climb\"} {\n\t\t\tif sim := canyon(policy, failsafe); policy == \"climb\" && failsafe {\n\t\t\t\treplay = sim // the climb the failsafe cut short\n\t\t\t}\n\t\t}\n\t}\n\tif err := replay.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Lose the fix, then fly a street six times","walkthrough":"The fix flag drops at +0.0 s. The reported position, (0.5, -0.5, 21.1), repeats from the first report, so the third identical report marks it frozen at +0.3 s, yet the newest report is never older than 0.2 s. The true drift grows from 1.4 m at +1.9 s to 4.8, 8.8 and 13.0 m, and reaches 18.1 m at +9.9 s as the drone picks up the wind's speed. At +3.0 s the failsafe starts 'no GPS for 3 s: landing'. The descent from 20 m lasts until +16.9 s, and the drone touches down 40.6 m downwind of where the fix was lost. In the street with the failsafe on, both hold and climb end in 'hit north 4' at +10.4 s, 2.0 m and 5.5 m up: the failsafe turned both into a landing at +3.0 s, too late to reach the ground before the drift reached the buildings. Land, with the failsafe on or off, touches down at +9.5 s, 12.2 m north of the centre line; the buildings' faces start at 13 m. With the failsafe off, hold drifts into the buildings at 10.0 m. Only the climb gets out: the fix comes back above the roofs at +7.2 s, and the drone holds 28.7 m up, 7.4 m north."},{"body":"Each policy has a case. Hold is what an operator expects, and the one thing an autopilot cannot do without a position: the drone drifts exactly as if nothing had been commanded. Land shortens the time in the air and so limits the drift, but it lands wherever the wind has carried the drone, and a street may be a road. Climb looks for sky: above the roofs the fix comes back and the vehicle can hold again, provided it climbs faster than it drifts towards a wall. With the failsafe on, the program does not get the last word. After 3 s the autopilot lands whatever was commanded, so the climb is cut off halfway and the hold becomes a late landing, both worse than landing at once. That is deliberate. The failsafe runs on the flight controller because it must work when the companion computer, the link or the program is what failed, and it cannot know what a program meant. So make the program's policy agree with the configured action. Choose that action on purpose from what the autopilot offers (in ArduPilot, FS_EKF_ACTION: report only, Land, AltHold, or Land from any mode) and test it. Above all, plan routes that keep outages short: a street survey flown above the roofs never needs a canyon policy.","title":"A policy of your own, and why the failsafe acts anyway"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output lists two recordings. open-field.gfflight is the hover that drifts 40 m downwind as it descends. flight.gfflight is the climb the failsafe cut short: the replay draws the two rows of buildings as grey discs, and the flight ends at the north row. Lower the wind to 2 m/s, widen the street, or fly the street at 30 m, above the roofs, and see which policies still matter.","title":"Fly it in GopherForge"}],"takeaway":"Without GPS an autopilot keeps its attitude and its height, and drifts with the wind while telemetry keeps arriving with a frozen position. Detect the outage from the fix flag and from repeated values, not from message age. The autopilot's failsafe acts on its own timer whatever your program commands, so make your policy agree with it, choose and test the configured action, and plan routes that keep outages short.","title":"Flying without GPS: frozen telemetry, drift, the landing failsafe and your own policy","unitID":"drones-autonomy","wrongAnswers":["The age of the newest report exceeding 1 s","A drop in the telemetry link's signal strength"]},{"conceptTag":"drones.radio-link","designGuide":{"cautions":["Real links fade with terrain, antennas and interference.","Commands queued during an outage replay at the wrong time."],"cost":"A range test per site, a margin in the planner and a station that tracks report age and the time to the edge.","family":"drones","flow":["Range-test the site","Plan inside with margin","Watch age and edge time","Hands off during loss"],"ratings":[],"strengths":["The station predicts when and where the vehicle reappears.","Holding before the edge keeps the rest of the mission."]},"hint":"The vehicle keeps flying its last command while its own timer runs. Multiply the speed by the timeout, then add the braking.","id":"drones.radio-link","introduction":"The failsafes lesson treated link loss as a heartbeat timeout in code, and the ground-station lesson as a timer that every frame resets. In the field the questions are different. How far does the link reach at this site today? What does the screen show when it drops? Where will the vehicle be when its failsafe fires, and where will it come back into range? What should the operator do in the meantime, and what should they not do? This lesson answers them with the simulator's limited-range link.","nuance":"At 8 m/s a 5 s timeout carries it about 40 m past the edge before RTL even starts, plus a few metres of braking, so size the margin and check the way home for that overshoot, not for the edge.","objective":"Treat the radio link as a measured range around home, show what a ground station sees while reports stop arriving, follow the link-loss failsafe second by second, predict where the vehicle reappears, and plan and fly missions that stay inside the link with margin.","question":"A drone flies away from home at 8 m/s, loses its link 200 m out, and its failsafe returns home after 5 s without a link. Where does it start to turn back?","references":["https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/gcs-failsafe.html","https://mavlink.io/en/messages/common.html#RADIO_STATUS","https://ardupilot.org/copter/docs/common-rssi-received-signal-strength-indication.html"],"reviewAnswer":"Speed times the timeout beyond the edge, plus braking","reviewPrompt":"Where does link-loss RTL start?","sections":[{"body":"A radio link reaches as far as its link budget allows: transmit power, antenna gains and their orientation, a clear line of sight with room around it, the airframe shielding its own antenna in a turn, trees, terrain and whatever else transmits on the band. None of that is on the radio's datasheet, so operators range-test each site and watch the link's own health. SiK telemetry radios, for example, inject RADIO_STATUS into the MAVLink stream with local and remote RSSI, local and remote noise and a count of receive errors; RSSI falling towards the noise floor and errors rising are the early warning. The simulator reduces all of this to Config.LinkRange: a circle of that radius around each drone's home, measured horizontally. d.Link() reports whether the drone is inside it, the event log records 'link lost' and 'link restored', and with failsafes on a link lost for 5 s starts a return home. Real links fade over tens of metres instead of switching off at a line, which gives a watchful operator time the simulator does not.","title":"Range is measured, not read off a datasheet"},{"body":"A ground station cannot tell a fade from a crash, a flat battery or a switched-off radio: it only knows that reports have stopped. The one honest signal is the age of the last report, measured on the station's own clock. At 5 Hz, a second without a report is five missed in a row: grey the values out and say how old they are. After the same timeout the vehicle uses, declare the link lost. From then on nothing the operator sends can arrive, and status messages the vehicle sends during the outage are gone too; the vehicle's own log has them, and the station reads it after landing. In the program, the station receives d.Telemetry() only while d.Link() is true, and its commands go up only over a live link, so its view and the vehicle's log can be printed side by side.","title":"What the ground station sees"},{"body":"Follow a vehicle flying outwards at speed v when the link drops at the edge. It keeps flying its last command for the whole timeout T, so the failsafe fires about v times T beyond the edge. It then brakes, turns and flies back over the same distance, so the link returns roughly 2T + 2v/a after the last report, where a is the airframe's acceleration. That is the time the station can announce, and if the vehicle has not reappeared by then plus a margin, something other than the link has failed. Flight stacks make the timeout and the action parameters: PX4 triggers its data link loss failsafe after COM_DL_LOSS_T with the action in NAV_DLL_ACT (disabled, Hold, Return, Land, Disarm or Terminate), and by default holds for COM_FAIL_ACT_T seconds first so the operator can step in. ArduPilot's GCS failsafe fires after FS_GCS_TIMEOUT seconds without a ground-station heartbeat (5 by default), can be set to RTL, SmartRTL or Land, can let an Auto mission continue through FS_OPTIONS, and stays inactive if no ground station ever connected. Whatever the action, the airspace v times T past the edge and the straight line home from there must be safe to fly.","title":"The failsafe timeline"},{"body":"The tested range is 200 m and the plan keeps 40 m inside it. Check finds each plan's farthest waypoint; because distance from home is convex along a straight leg, the farthest point of any route is one of its waypoints. Flight 1 flies plan A, which the check rejects, and relies on the failsafe alone. Flight 2 flies the same plan with an operator who watches the reports: when the edge is less than 4 s away at the current outward speed, the station holds the vehicle and skips that waypoint. Flight 3 flies plan B. Lines marked station are what the ground station knows when it knows it; lines marked vehicle come from the vehicle's log.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tlinkRange = 200.0 // m, from a range test at this site, not the radio's datasheet\n\tmargin    = 40.0  // m the plan keeps inside it\n\ttimeout   = 5.0   // s, the vehicle's link-loss failsafe\n\tspeed     = 10.0  // m/s cruise\n\taccel     = 6.87  // m/s2, the airframe's horizontal acceleration\n\tlookahead = 4.0   // s, the operator holds when the edge is closer than this\n)\n\n// Station is the ground station. It sees the vehicle only through the\n// reports that reach it, so it keeps its own clock on their age.\ntype Station struct {\n\tlast  drone.Telemetry // latest report received\n\tstate string          // up, stale or lost\n}\n\nfunc (s *Station) Receive(tel drone.Telemetry) {\n\tif s.state != \"up\" {\n\t\tfmt.Printf(\"  %5.1f s  station  link back after %.1f s: %s %.0f m out, %.0f m up, %.0f%%\\n\",\n\t\t\ttel.Time, tel.Time-s.last.Time, tel.Mode, tel.GPS.Horizontal().Len(), tel.BaroAlt, tel.Battery)\n\t}\n\ts.last, s.state = tel, \"up\"\n}\n\n// Outward is the reported speed away from home, m/s.\nfunc (s *Station) Outward() float64 {\n\tp, v := s.last.GPS.Horizontal(), s.last.Velocity.Horizontal()\n\tif p.Len() < 1 {\n\t\treturn 0\n\t}\n\treturn (p.X*v.X + p.Y*v.Y) / p.Len()\n}\n\n// Tick runs on the station's own clock: stale after 1 s without a report,\n// lost after the same timeout the vehicle uses.\nfunc (s *Station) Tick(now float64) {\n\tage := now - s.last.Time\n\tp, out := s.last.GPS.Horizontal(), s.Outward()\n\tswitch {\n\tcase s.state == \"up\" && age >= 1:\n\t\ts.state = \"stale\"\n\t\tfmt.Printf(\"  %5.1f s  station  no report for 1 s: last %.0f m out, %s, moving out at %.1f m/s\\n\",\n\t\t\tnow, p.Len(), s.last.Mode, out)\n\tcase s.state == \"stale\" && age >= timeout:\n\t\ts.state = \"lost\"\n\t\t// The failsafe fires about timeout after the last report, the vehicle\n\t\t// brakes, turns and flies back over the same distance.\n\t\tback := s.last.Time + 2*timeout + 2*out/accel\n\t\tfmt.Printf(\"  %5.1f s  station  LINK LOST: no commands possible; expect the return near %.1f s\\n\", now, back)\n\t}\n}\n\n// Check plans against the link. Distance from home is convex along a\n// straight leg, so the farthest point of a route is always a waypoint.\nfunc Check(name string, plan []drone.Vec3) bool {\n\tfar := 0.0\n\tfor _, p := range plan {\n\t\tfar = math.Max(far, p.Horizontal().Len())\n\t}\n\tok := far <= linkRange-margin\n\tverdict := \"go\"\n\tif !ok {\n\t\tverdict = \"NO-GO\"\n\t}\n\tfmt.Printf(\"%s: farthest waypoint %.1f m from home, limit %.0f m (%.0f m range - %.0f m margin): %s\\n\",\n\t\tname, far, linkRange-margin, linkRange, margin, verdict)\n\treturn ok\n}\n\n// fly flies a plan. With guard, the operator holds and skips the leg when\n// the reports show the link edge less than lookahead seconds away.\nfunc fly(plan []drone.Vec3, guard bool) *drone.Sim {\n\tsim := drone.New(drone.Config{LinkRange: linkRange, Wind: drone.Vec3{X: -2, Y: 1}, Gust: 1, MaxSpeed: speed, Seed: 12})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(30)\n\tst := &Station{last: d.Telemetry(), state: \"up\"}\n\tnext, reached, sentAt, seenTel, seenEv, far := 0, 0, -1.0, -1.0, 0, 0.0\n\tsim.RunUntil(400, func(t float64) bool {\n\t\tif tel := d.Telemetry(); tel.Time != seenTel {\n\t\t\tseenTel = tel.Time\n\t\t\tif d.Link() { // the downlink works only in range\n\t\t\t\tst.Receive(tel)\n\t\t\t}\n\t\t}\n\t\tst.Tick(t)\n\t\t// The vehicle's own log, which the station reads after landing.\n\t\tdist := d.State().Pos.Horizontal().Len()\n\t\tfar = math.Max(far, dist)\n\t\tevents := sim.Events()\n\t\tfor _, e := range events[seenEv:] {\n\t\t\tif strings.HasPrefix(e.Text, \"arrived\") {\n\t\t\t\treached++\n\t\t\t}\n\t\t\tif strings.Contains(e.Text, \"link\") || strings.Contains(e.Text, \"return\") || e.Text == \"landed\" {\n\t\t\t\tfmt.Printf(\"  %5.1f s  vehicle  %-35s %5.1f m out\\n\", e.T, e.Text, dist)\n\t\t\t}\n\t\t}\n\t\tseenEv = len(events)\n\t\tif guard && st.state == \"up\" && st.last.Mode == drone.GoingTo && st.last.Time > sentAt {\n\t\t\tif r := st.last.GPS.Horizontal().Len(); r+st.Outward()*lookahead > linkRange {\n\t\t\t\tfmt.Printf(\"  %5.1f s  station  link edge %.1f s away (%.0f m out at %.1f m/s): hold, skip waypoint %d\\n\",\n\t\t\t\t\tt, (linkRange-r)/st.Outward(), r, st.Outward(), next)\n\t\t\t\td.Hold()\n\t\t\t\tsentAt = t\n\t\t\t}\n\t\t}\n\t\t// The operator sends the next waypoint when the vehicle reports HOLD;\n\t\t// commands go up only over a live link.\n\t\tif st.state == \"up\" && st.last.Mode == drone.Hold && st.last.Time > sentAt && d.Link() {\n\t\t\tsentAt = t\n\t\t\tif next < len(plan) {\n\t\t\t\td.GoTo(plan[next])\n\t\t\t\tnext++\n\t\t\t} else {\n\t\t\t\td.ReturnHome()\n\t\t\t}\n\t\t}\n\t\treturn d.State().Landed\n\t})\n\ts := d.State()\n\tfmt.Printf(\"  reached %d of %d waypoints, farthest %.1f m from home, landed %.1f m from home with %.0f%%\\n\",\n\t\treached, len(plan), far, s.Pos.Horizontal().Len(), s.Battery)\n\treturn sim\n}\n\nfunc main() {\n\tplanA := []drone.Vec3{{X: 100, Y: 100, Z: 30}, {X: 240, Y: 60, Z: 30}, {X: 100, Y: -40, Z: 30}}\n\tplanB := []drone.Vec3{{X: 100, Y: 100, Z: 30}, {X: 150, Y: 40, Z: 30}, {X: 100, Y: -40, Z: 30}}\n\tCheck(\"plan A\", planA)\n\tCheck(\"plan B\", planB)\n\n\tfmt.Println(\"\\nflight 1: plan A anyway, the failsafe alone\")\n\tif err := fly(planA, false).SaveAs(\"failsafe\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"\\nflight 2: plan A, the operator watching the edge\")\n\tif err := fly(planA, true).SaveAs(\"operator\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"\\nflight 3: plan B\")\n\tif err := fly(planB, true).Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Three flights against a 200 m link","walkthrough":"Plan A's farthest waypoint is 247.4 m from home against a 160 m limit, NO-GO; plan B's is 155.2 m. In flight 1 the vehicle logs 'link lost' at 38.0 s, 200.3 m out. The station learns nothing until 38.8 s (no report for 1 s, last seen 199 m out in GOTO, moving out at 7.8 m/s) and declares LINK LOST at 42.8 s, expecting the return near 50.1 s. The failsafe fires at 43.0 s, 241.3 m out; the link is restored at 49.5 s and the station sees RTL 198 m out at 49.6 s, 11.8 s after the last report. The drone reached 245.3 m, 1 of 3 waypoints, and landed at home with 74%. In flight 2 the station holds at 34.4 s, 172 m out with the edge 3.9 s away, skips waypoint 2 and finishes the rest: 2 of 3 waypoints, never beyond 176.4 m, 77%. Plan B reaches all 3, at most 155.6 m out, and lands with 78%."},{"body":"The failsafe is the last line, and it ends the mission. Operators work earlier. They plan inside the tested range with a margin that covers fading and the failsafe's overshoot. They watch the trend (report age, RSSI against noise, distance and time to the edge) and pull back before the edge, as flight 2 did, keeping the rest of the mission. When the link does drop, they take their hands off: commands cannot arrive, and commands queued during the outage replay later into a situation that has changed. They note the last position, heading and time, keep visual contact where the rules require it, and announce when and where the vehicle should reappear. If it has not by then, they start the lost-aircraft procedure. When the link returns, they confirm the mode and the battery before sending anything, because the vehicle may be on its way home. And they choose the failsafe action and return altitude per site: Return over open ground, Hold or Land where the way home crosses something.","title":"What operators do that the failsafe cannot"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go, then tap Run. Output lists three recordings: failsafe.gfflight crosses the dashed link circle, carries on for 5 s and turns home; operator.gfflight stops short of the circle and goes on to the last waypoint; flight.gfflight stays well inside it. Change lookahead to 1 s, or the margin to 0, and watch where the station stops the drone and how close it comes to the edge.","title":"Fly it in GopherForge"}],"takeaway":"Measure the link range at each site and plan inside it with a margin for fading and for the overshoot of speed times the failsafe timeout. Let the station judge the link by the age of the last report, predict when the vehicle should reappear, send nothing while the link is down, and pull back before the edge rather than waiting for the failsafe to end the mission.","title":"Radio links in operations: tested range, what the station sees, the failsafe timeline and margins","unitID":"drones-operations","wrongAnswers":["At 200 m, the moment the link drops","Where the station declares the link lost, 1 s later"]},{"conceptTag":"drones.flight-logs","designGuide":{"cautions":["A sampled mode column misses changes shorter than a row.","Summing noisy GPS overstates the distance flown."],"cost":"A logger in the flight loop, a CSV or binary writer, and a rule set whose thresholds are tested against injected faults.","family":"drones","flow":["Sample at a fixed rate","Log events when they occur","Compute metrics per flight","Run rules, test with faults"],"ratings":[],"strengths":["Rules check every flight, not just the ones that went wrong.","Fixed-rate rows make windows and integrals simple."]},"hint":"Compare the 1 m check with how far a GPS fix wanders from the true position while the drone holds still.","id":"drones.flight-logs","introduction":"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.","nuance":"The autopilot holds on its own estimate and reports HOLD; a raw GPS fix within 1 m fails about half the time, and every resend flips the mode. Use the autopilot's arrival or a radius above the GPS error.","objective":"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.","question":"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?","references":["https://docs.px4.io/main/en/log/flight_log_analysis.html","https://docs.px4.io/main/en/dev_log/ulog_file_format.html","https://ardupilot.org/copter/docs/common-downloading-and-analyzing-data-logs-in-mission-planner.html","https://pkg.go.dev/encoding/csv"],"reviewAnswer":"A 1 m acceptance check tighter than the GPS error","reviewPrompt":"What caused the mode flapping?","sections":[{"body":"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.","title":"Samples and events"},{"body":"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.","title":"CSV for people, summaries for the console"},{"body":"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.","title":"Metrics from one flight"},{"body":"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.","code":"package main\n\nimport (\n\t\"encoding/csv\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Row is one fixed-rate sample: the position the autopilot flies on (the true\n// state here, the EKF estimate in a real log) and what the sensors said.\ntype Row struct {\n\tT        float64\n\tPos, GPS drone.Vec3\n\tBaro     float64\n\tBattery  float64 // the battery monitor, %\n\tMode     drone.Mode\n}\n\n// Change is a mode change, logged when it happens rather than sampled.\ntype Change struct {\n\tT        float64\n\tFrom, To drone.Mode\n}\n\ntype Log struct {\n\tRows    []Row\n\tChanges []Change\n}\n\n// CSV writes the rows for a spreadsheet or a plotting tool.\nfunc (l *Log) CSV() (string, error) {\n\tvar b strings.Builder\n\tw := csv.NewWriter(&b)\n\tw.Write([]string{\"t\", \"x\", \"y\", \"z\", \"gps_x\", \"gps_y\", \"gps_z\", \"baro\", \"battery\", \"mode\"})\n\tf := func(v float64) string { return strconv.FormatFloat(v, 'f', 2, 64) }\n\tfor _, r := range l.Rows {\n\t\tw.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),\n\t\t\tf(r.Baro), f(r.Battery), r.Mode.String()})\n\t}\n\tw.Flush()\n\treturn b.String(), w.Error()\n}\n\n// BatteryDrop flags a fall of more than 2 points within 1 s: the airframe\n// cannot drain faster than about 1 %/s, so it is a cell, a connector or the sensor.\nfunc BatteryDrop(l *Log) (out []string) {\n\tlast := -10.0\n\tfor i := 5; i < len(l.Rows); i++ {\n\t\tif drop := l.Rows[i-5].Battery - l.Rows[i].Battery; drop > 2 && l.Rows[i].T-last > 5 {\n\t\t\tlast = l.Rows[i].T\n\t\t\tout = append(out, fmt.Sprintf(\"%5.1f s  battery fell %.1f points in 1 s\", last, drop))\n\t\t}\n\t}\n\treturn out\n}\n\n// Divergence flags GPS more than 5 m from the position the autopilot uses.\nfunc Divergence(l *Log) (out []string) {\n\tstart, worst := math.Inf(1), 0.0\n\tfor i, r := range l.Rows {\n\t\td := r.GPS.Sub(r.Pos).Horizontal().Len()\n\t\tif d > 5 {\n\t\t\tstart, worst = math.Min(start, r.T), math.Max(worst, d)\n\t\t}\n\t\tif worst > 0 && (d <= 5 || i == len(l.Rows)-1) {\n\t\t\tout = append(out, fmt.Sprintf(\"%5.1f s  GPS off the position for %.1f s, up to %.1f m\", start, r.T-start, worst))\n\t\t\tstart, worst = math.Inf(1), 0\n\t\t}\n\t}\n\treturn out\n}\n\n// Flapping flags 6 or more mode changes, each less than 5 s after the last.\nfunc Flapping(l *Log) (out []string) {\n\tc := l.Changes\n\tfor i := 0; i+5 < len(c); {\n\t\tj := i\n\t\tfor j+1 < len(c) && c[j+1].T-c[j].T < 5 {\n\t\t\tj++\n\t\t}\n\t\tif j-i+1 >= 6 {\n\t\t\tout = 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))\n\t\t}\n\t\ti = j + 1\n\t}\n\treturn out\n}\n\nfunc report(rule string, found []string) {\n\tif len(found) == 0 {\n\t\tfmt.Printf(\"  %-15s none\\n\", rule)\n\t}\n\tfor _, f := range found {\n\t\tfmt.Printf(\"  %-15s %s\\n\", rule, f)\n\t}\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 4}, Gust: 1, MaxSpeed: 10, Seed: 2})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(20)\n\twps := []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}}\n\tvar lg Log\n\ti, sent, logged, mode, outage := -1, -10.0, -1.0, d.State().Mode, false\n\t// The flight controller logs a mode change when it happens.\n\tchanged := func(t float64) {\n\t\tif m := d.State().Mode; m != mode {\n\t\t\tlg.Changes = append(lg.Changes, Change{t, mode, m})\n\t\t\tmode = m\n\t\t}\n\t}\n\tsim.RunUntil(300, func(t float64) bool {\n\t\tchanged(t)\n\t\tst, tel := d.State(), d.Telemetry()\n\t\tif tel.Time != logged { // one row per 5 Hz report\n\t\t\tlogged = tel.Time\n\t\t\tlg.Rows = append(lg.Rows, Row{t, st.Pos, tel.GPS, tel.BaroAlt, st.Battery, st.Mode})\n\t\t}\n\t\t// The mission code, with a bug: when the drone reports HOLD it checks\n\t\t// the GPS within 1 m of the waypoint, less than the GPS error, and\n\t\t// sends the waypoint again if the check fails.\n\t\tif tel.Mode == drone.Hold && t-sent >= 1 && i < len(wps) {\n\t\t\tif i < 0 || tel.GPS.Sub(wps[i]).Horizontal().Len() < 1 {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tif i < len(wps) {\n\t\t\t\td.GoTo(wps[i])\n\t\t\t} else {\n\t\t\t\td.Land()\n\t\t\t}\n\t\t\tsent = t\n\t\t\tchanged(t)\n\t\t}\n\t\tif !outage && i == len(wps)-1 && st.Pos.Horizontal().Len() < 45 {\n\t\t\toutage = true\n\t\t\td.LoseGPS(6) // under a bridge\n\t\t}\n\t\treturn st.Landed\n\t})\n\n\ttext, err := lg.CSV()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlines := strings.Split(strings.TrimSpace(text), \"\\n\")\n\tfmt.Printf(\"log: %d rows at 5 Hz, %d mode changes, CSV %d bytes\\n\", len(lg.Rows), len(lg.Changes), len(text))\n\tfmt.Printf(\"  %s\\n  %s\\n  ...\\n  %s\\n\", lines[0], lines[1], lines[len(lines)-1])\n\n\tvar dist, gpsDist, maxAlt float64\n\tinMode := make([]float64, drone.Crashed+1)\n\tfor k, r := range lg.Rows {\n\t\tif k > 0 {\n\t\t\tdist += r.Pos.Sub(lg.Rows[k-1].Pos).Horizontal().Len()\n\t\t\tgpsDist += r.GPS.Sub(lg.Rows[k-1].GPS).Horizontal().Len()\n\t\t}\n\t\tmaxAlt = math.Max(maxAlt, r.Baro)\n\t\tinMode[r.Mode] += 0.2\n\t}\n\tfirst, last := lg.Rows[0], lg.Rows[len(lg.Rows)-1]\n\tused := first.Battery - last.Battery\n\tfmt.Printf(\"metrics\\n  %.1f s, %.0f m flown (%.0f m by summing GPS), max altitude %.1f m (baro)\\n\", last.T, dist, gpsDist, maxAlt)\n\tfmt.Print(\"  time per mode:\")\n\tfor m, s := range inMode {\n\t\tif s > 0 {\n\t\t\tfmt.Printf(\" %s %.1f s\", drone.Mode(m), s)\n\t\t}\n\t}\n\tfmt.Printf(\"\\n  battery used %.1f points, %.1f per km; landed %.1f m from home\\n\", used, used/(dist/1000), last.Pos.Horizontal().Len())\n\tfmt.Println(\"anomalies\")\n\treport(\"battery drop\", BatteryDrop(&lg))\n\treport(\"GPS divergence\", Divergence(&lg))\n\treport(\"mode flapping\", Flapping(&lg))\n\tfor _, e := range sim.Events() {\n\t\tif strings.Contains(e.Text, \"GPS\") {\n\t\t\tfmt.Printf(\"  vehicle event   %5.1f s  %s\\n\", e.T, e.Text)\n\t\t}\n\t}\n\n\t// The simulator has no failing cells, so test the battery rule on a copy\n\t// of the log with a fault injected.\n\tbad := Log{Rows: append([]Row(nil), lg.Rows...)}\n\tfor k := 150; k < len(bad.Rows); k++ { // from 30 s on, at 5 rows a second\n\t\tbad.Rows[k].Battery -= 6\n\t}\n\tfmt.Println(\"the same log with the battery reading 6 points low from 30 s\")\n\treport(\"battery drop\", BatteryDrop(&bad))\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A flight with two problems","walkthrough":"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."},{"body":"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.","title":"Anomaly rules and their thresholds"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Flight logs: fixed-rate records, events, CSV export, per-flight metrics and anomaly rules","unitID":"drones-operations","wrongAnswers":["The autopilot's position loop is unstable","The log rate is too low to show the real modes"]},{"conceptTag":"drones.energy-planning","designGuide":{"cautions":["Outside the calibrated airspeeds the fit is a guess.","Cold or ageing packs drain faster than the calibration."],"cost":"A calibration flight per airframe and pack type, a small least-squares fit, and a planner that predicts every leg.","family":"drones","flow":["Fly calibration legs","Fit drain vs airspeed","Predict legs per wind case","Go if margin and reserve fit"],"ratings":[],"strengths":["Turns a wind forecast into a go or no-go before take-off.","Per-leg comparison shows where the model is wrong."]},"hint":"Expand the airspeed squared on each leg and sum over the loop: what does the term with the wind direction add up to when you end where you started?","id":"drones.energy-planning","introduction":"The failsafes lesson budgeted the way home in flight, every second. Before take-off the question is wider: will this whole mission, in today's wind, land with the reserve, and how sure are we? Answering it needs a consumption model of this airframe and pack, measured rather than guessed, a prediction for every leg, and an honest margin for what the model does not know. The same model then tells you after the flight where it was wrong.","nuance":"Airspeed squared is v squared minus 2v times u.w plus w squared; summed over a loop at constant ground speed the middle term is zero. A headwind leg capped at the top airspeed slows down and breaks the symmetry.","objective":"Calibrate a drain model from short test legs at known airspeeds, fit it by least squares, predict a planned route leg by leg in several wind cases including the airspeed limit, decide go or no-go with a landing reserve and a model margin, then fly the mission and compare prediction with use.","question":"A closed loop is flown at one ground speed and drain is modelled as A + B times airspeed squared. How does the direction of an 8 m/s wind change the predicted use?","references":["https://docs.px4.io/main/en/config/battery.html","https://en.wikipedia.org/wiki/Simple_linear_regression","https://ardupilot.org/copter/docs/failsafe-battery.html"],"reviewAnswer":"No effect unless a leg hits the airspeed limit","reviewPrompt":"Wind direction on a closed loop?","sections":[{"body":"Hovering costs power because the rotors hold the weight up; flying through the air costs more, because the airframe must tilt and push against drag, and drag grows with the square of the airspeed. Airspeed, not ground speed: the same leg costs more into a headwind, both because the airspeed is higher and because it takes longer. Climbing adds the work of lifting. Measuring what was used is its own problem. PX4 recommends fusing a voltage-based estimate, load-compensated with the pack's internal resistance, with a current-based count of the charge consumed, and setting BAT1_CAPACITY to about 90 percent of the label. The simulator reports an exact percentage, which here stands in for such an estimate.","title":"What drains a multicopter"},{"body":"Fly a calibration in a known, steady wind: a hover, then legs at steady velocity downwind, upwind and across, at the speeds the missions will use and faster. On each leg, wait for the acceleration to settle, then measure the drain over a fixed window. Each leg gives one point, airspeed against drain in percent per second. Fit drain = A + B times airspeed squared by least squares: an ordinary straight-line regression on airspeed squared, a few lines of Go. Check the residuals, and write down the range of airspeeds the calibration covered, because outside it the fit is a guess. Measure the take-off and the landing separately, as costs in points. Repeat the calibration per airframe and pack type, in the cold, and as packs age.","title":"Calibrate with short legs"},{"body":"For each leg, split the wind into the part along the leg and the part across it. The autopilot flies the cruise ground speed unless the top airspeed cannot reach it: the ground speed is the smaller of the cruise speed and the along-wind component plus the square root of the top airspeed squared minus the crosswind squared, as in the failsafes lesson. The airspeed is the ground velocity minus the wind; the time is the length over the ground speed plus a few seconds for braking into the waypoint and accelerating out. The leg costs the drain at that airspeed times the time. Run it for every wind the forecast allows, not just the mean. One result surprises people: on a closed loop flown at one ground speed, the quadratic model makes the wind's direction cancel, because the cross term sums to the route's total displacement, which is zero. Only the wind's speed costs, B times its square every second, until a headwind leg hits the airspeed limit and slows down.","title":"Predict a route in several winds"},{"body":"The program calibrates in a 3 m/s wind with seven legs, fits the model and prints it. It then predicts a 6-leg route at 10 m/s and 25 m in five wind cases, and calls the flight go when the prediction plus 10 percent still lands with 25 percent, above the 20 percent return-home failsafe; it flags cases that need airspeeds beyond the calibration. Finally it flies the route in 4 m/s from the west with 1.5 m/s gusts and compares each step with its prediction.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\talt     = 25.0 // m, mission altitude\n\tcruise  = 10.0 // m/s ground speed the autopilot flies\n\tmaxAir  = 18.0 // m/s, the airframe's top airspeed\n\tstop    = 2.5  // s per waypoint: braking into it and accelerating out\n\treserve = 25.0 // % on the ground, above the 20% return-home failsafe\n\tmargin  = 0.10 // model error allowance on the predicted use\n)\n\n// Model is drain = A + B*airspeed^2 in %/s, plus measured take-off and\n// landing costs in points.\ntype Model struct{ A, B, Climb, Descent, MaxAir float64 }\n\nfunc (m Model) Drain(air float64) float64 { return m.A + m.B*air*air }\n\n// Leg predicts one straight leg: the ground speed the autopilot can hold\n// (the airspeed limit caps it against a headwind), the airspeed, the cost.\nfunc (m Model) Leg(from, to, wind drone.Vec3) (cost, secs, air float64) {\n\tseg := to.Sub(from).Horizontal()\n\tu := seg.Scale(1 / seg.Len())\n\talong, across := wind.X*u.X+wind.Y*u.Y, wind.X*u.Y-wind.Y*u.X\n\tgs := math.Min(cruise, along+math.Sqrt(math.Max(0, maxAir*maxAir-across*across)))\n\tif gs < 1 {\n\t\treturn math.Inf(1), math.Inf(1), maxAir\n\t}\n\tair = u.Scale(gs).Sub(wind).Len()\n\tsecs = seg.Len()/gs + stop\n\treturn m.Drain(air)*seg.Len()/gs + m.Drain(wind.Len())*stop, secs, air\n}\n\n// Predict returns the take-off, each leg and the landing, in points.\nfunc (m Model) Predict(route []drone.Vec3, wind drone.Vec3) (costs []float64, secs, worstAir float64) {\n\tcosts = append(costs, m.Climb)\n\tfor i := 1; i < len(route); i++ {\n\t\tc, s, air := m.Leg(route[i-1], route[i], wind)\n\t\tcosts, secs, worstAir = append(costs, c), secs+s, math.Max(worstAir, air)\n\t}\n\treturn append(costs, m.Descent), secs, worstAir\n}\n\n// Calibrate flies short legs at steady velocity in a known wind, measures\n// the drain on each after it settles, and fits A and B by least squares.\nfunc Calibrate(wind drone.Vec3) Model {\n\tsim := drone.New(drone.Config{Wind: wind, Gust: 0.5, MaxSpeed: 15, Seed: 4})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar m Model\n\tb := d.State().Battery\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tm.Climb = b - d.State().Battery\n\tvar xs, ys []float64\n\tfmt.Printf(\"calibration in %.0f m/s wind from the west, %.0f m up\\n  %-22s %8s %10s\\n\", wind.Len(), alt, \"leg\", \"airspeed\", \"drain\")\n\tfor _, leg := range []struct {\n\t\tname string\n\t\tv    drone.Vec3\n\t}{{\"hover\", drone.Vec3{}}, {\"east 10 m/s, downwind\", drone.Vec3{X: 10}}, {\"west 10 m/s, upwind\", drone.Vec3{X: -10}},\n\t\t{\"north 10 m/s, across\", drone.Vec3{Y: 10}}, {\"south 10 m/s, across\", drone.Vec3{Y: -10}},\n\t\t{\"west 14 m/s, upwind\", drone.Vec3{X: -14}}, {\"east 14 m/s, downwind\", drone.Vec3{X: 14}}} {\n\t\tif leg.v.Len() == 0 {\n\t\t\td.Hold()\n\t\t} else {\n\t\t\td.SetVelocity(leg.v, 0)\n\t\t}\n\t\tsim.Run(4, nil) // settle\n\t\tb, t := d.State().Battery, sim.Time()\n\t\tsim.Run(10, nil)\n\t\tdrain := (b - d.State().Battery) / (sim.Time() - t)\n\t\tair := leg.v.Sub(wind).Len()\n\t\txs, ys, m.MaxAir = append(xs, air*air), append(ys, drain), math.Max(m.MaxAir, air)\n\t\tfmt.Printf(\"  %-22s %6.1f m/s %6.3f %%/s\\n\", leg.name, air, drain)\n\t}\n\td.GoTo(drone.Vec3{Z: alt})\n\tsim.RunUntil(60, func(float64) bool { return d.Arrived() })\n\tb = d.State().Battery\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool { return d.State().Landed })\n\tm.Descent = b - d.State().Battery\n\n\tvar mx, my, sxy, sxx, rms float64\n\tfor i := range xs {\n\t\tmx, my = mx+xs[i]/float64(len(xs)), my+ys[i]/float64(len(xs))\n\t}\n\tfor i := range xs {\n\t\tsxy, sxx = sxy+(xs[i]-mx)*(ys[i]-my), sxx+(xs[i]-mx)*(xs[i]-mx)\n\t}\n\tm.B = sxy / sxx\n\tm.A = my - m.B*mx\n\tfor i := range xs {\n\t\trms += math.Pow(ys[i]-m.Drain(math.Sqrt(xs[i])), 2) / float64(len(xs))\n\t}\n\tfmt.Printf(\"  take-off to %.0f m %.1f points, landing %.1f points\\n\", alt, m.Climb, m.Descent)\n\tfmt.Printf(\"  fit: drain = %.3f + %.5f * airspeed^2 %%/s, rms error %.3f, calibrated up to %.0f m/s\\n\", m.A, m.B, math.Sqrt(rms), m.MaxAir)\n\tif err := sim.SaveAs(\"calibration\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn m\n}\n\nfunc sum(xs []float64) (s float64) {\n\tfor _, x := range xs {\n\t\ts += x\n\t}\n\treturn s\n}\n\nfunc main() {\n\tm := Calibrate(drone.Vec3{X: 3})\n\troute := []drone.Vec3{{Z: alt}, {X: 300, Z: alt}, {X: 300, Y: 100, Z: alt}, {Y: 100, Z: alt},\n\t\t{Y: 200, Z: alt}, {X: 300, Y: 200, Z: alt}, {Z: alt}}\n\tlength := 0.0\n\tfor i := 1; i < len(route); i++ {\n\t\tlength += route[i].Sub(route[i-1]).Len()\n\t}\n\tfmt.Printf(\"\\nplan: %d legs, %.0f m at %.0f m/s; go if %.0f%% more than predicted still lands with %.0f%%\\n\",\n\t\tlen(route)-1, length, cruise, margin*100, reserve)\n\tfmt.Printf(\"  %-18s %7s %10s %9s\\n\", \"wind\", \"time\", \"predicted\", \"verdict\")\n\tfor _, c := range []struct {\n\t\tname string\n\t\tw    drone.Vec3\n\t}{{\"calm\", drone.Vec3{}}, {\"4 m/s from west\", drone.Vec3{X: 4}}, {\"8 m/s from north\", drone.Vec3{Y: -8}},\n\t\t{\"8 m/s from west\", drone.Vec3{X: 8}}, {\"12 m/s from west\", drone.Vec3{X: 12}}} {\n\t\tcosts, secs, worst := m.Predict(route, c.w)\n\t\tneed := sum(costs)\n\t\tverdict := \"go\"\n\t\tif need*(1+margin)+reserve > 100 {\n\t\t\tverdict = \"NO-GO\"\n\t\t}\n\t\tif worst > m.MaxAir+0.5 {\n\t\t\tverdict += fmt.Sprintf(\", extrapolated to %.0f m/s\", worst)\n\t\t}\n\t\tfmt.Printf(\"  %-18s %5.0f s %9.1f%%  %s\\n\", c.name, secs, need, verdict)\n\t}\n\n\twind := drone.Vec3{X: 4}\n\tfmt.Println(\"\\nflown in 4 m/s from the west with 1.5 m/s gusts\")\n\tpredicted, _, _ := m.Predict(route, wind)\n\tsim := drone.New(drone.Config{Wind: wind, Gust: 1.5, MaxSpeed: cruise, Seed: 6})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tactual := []float64{d.State().Battery}\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tactual = append(actual, d.State().Battery)\n\tfor _, p := range route[1:] {\n\t\td.GoTo(p)\n\t\tsim.RunUntil(120, func(float64) bool { return d.Arrived() })\n\t\tactual = append(actual, d.State().Battery)\n\t}\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool { return d.State().Landed })\n\tactual = append(actual, d.State().Battery)\n\tfmt.Printf(\"  %-12s %9s %7s\\n\", \"step\", \"predicted\", \"actual\")\n\tfor i, p := range predicted {\n\t\tname := fmt.Sprintf(\"leg %d\", i)\n\t\tif i == 0 {\n\t\t\tname = \"take-off\"\n\t\t} else if i == len(predicted)-1 {\n\t\t\tname = \"landing\"\n\t\t}\n\t\tfmt.Printf(\"  %-12s %9.1f %7.1f\\n\", name, p, actual[i]-actual[i+1])\n\t}\n\tused := actual[0] - actual[len(actual)-1]\n\tfmt.Printf(\"  total %.1f predicted, %.1f used (%+.1f%%), landed with %.1f%%\\n\", sum(predicted), used, (used/sum(predicted)-1)*100, d.State().Battery)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Calibrate, plan, fly, compare","walkthrough":"The hover in 3 m/s of wind drains 0.194 %/s, the 10 m/s legs 0.255 downwind (7.0 m/s airspeed), 0.447 upwind (13.0) and 0.351 and 0.349 across (10.4), and the 14 m/s legs 0.658 upwind (17.0) and 0.365 downwind (11.0). The fit is drain = 0.172 + 0.00166 * airspeed^2 with an rms error of 0.005, calibrated up to 17 m/s; the take-off to 25 m costs 2.5 points and the landing 2.9. The 1461 m plan takes 161 s and needs 57.3% in calm air and 61.5% in 4 m/s from the west: go. Both 8 m/s cases need 74.3%, because the loop cancels the direction, and are NO-GO, extrapolated to 18 m/s. At 12 m/s the upwind legs slow down, the flight takes 198 s and needs 107.1%. In the flown mission every step is within 0.5 points of its prediction; the largest miss is leg 3, the 300 m upwind leg, 15.4 against 15.9. In total 61.5 was predicted and 62.4 used (+1.4%), and the drone landed with 37.6%."},{"body":"Write the rule down before looking at the number: go if the predicted use times one plus the margin, plus the reserve, fits in the charge at take-off. The reserve is what you want on the ground and must sit above the return-home threshold, or the failsafe ends the mission early. The margin covers what the model ignores: gusts above the forecast, a colder or older pack, a detour, a go-around at the landing site. Start with 10 to 20 percent and tighten it only as logged flights show the model's real error, as the per-leg comparison here does. Plan with the forecast's upper wind, not its mean, and treat a case outside the calibrated airspeeds as no-go until it is calibrated. Log the decision with its inputs. In flight, the failsafes lesson's budget takes over: a plan that was go at take-off can still turn back early if the wind rises.","title":"Go, no-go and the margin"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go, then tap Run. Output lists calibration.gfflight, the hover and the out-and-back test legs at two speeds, and flight.gfflight, the survey loop flown in 4 m/s of wind; the HUD's battery shows where the upwind legs cost more. Fly the mission in 8 m/s from the west instead and compare the actual use with the 74.3% the model predicted outside its calibration.","title":"Fly it in GopherForge"}],"takeaway":"Calibrate drain against airspeed with short steady legs, fit it by least squares and note the range it covers. Predict every leg from the wind, the airspeed limit and the stops, decide go or no-go with a written rule of margin plus a reserve above the return threshold, and compare each flight with its prediction to learn the model's real error.","title":"Energy planning before take-off: calibrating consumption, predicting a mission and go/no-go","unitID":"drones-operations","wrongAnswers":["A wind along the longest legs costs the most","A crosswind adds nothing on any leg"]},{"conceptTag":"drones.preflight-checks","designGuide":{"cautions":["Sampling a leg can miss a corner thinner than the step.","A passing check is only as good as the site survey."],"cost":"A check per limit over every leg, typed errors carrying the data to fix them, and a re-check after every edit.","family":"drones","flow":["Limits from rules and site","Check every leg and point","Join typed errors","Auto-fix safe, ask the rest"],"ratings":[],"strengths":["The operator sees every problem in one pass.","Typed errors let code repair only what is safe to repair."]},"hint":"Draw an L-shaped fence, put one waypoint in each arm, and join them with a straight line.","id":"drones.preflight-checks","introduction":"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.","nuance":"Being inside at both ends says nothing about a concave shape in between; test the segment against every edge or sample it finely. Obstacles stand between waypoints too, so check them along the legs.","objective":"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.","question":"Both ends of a mission leg are inside a concave, L-shaped geofence. Why can the leg still breach the fence?","references":["https://www.easa.europa.eu/en/domains/drones-air-mobility/operating-drone/open-category-low-risk-civil-drones","https://www.faa.gov/newsroom/small-unmanned-aircraft-systems-uas-regulations-part-107","https://pkg.go.dev/errors","https://docs.px4.io/main/en/flying/missions.html"],"reviewAnswer":"A straight leg can cut through a concave fence's notch","reviewPrompt":"Why check every leg?","sections":[{"body":"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.","title":"What to check, and against what"},{"body":"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.","title":"Every leg, not just the waypoints"},{"body":"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.","code":"err := Check(plan, battery) // errors.Join of typed problems, or nil\nvar low *EnergyError\nif errors.As(err, &low) { // found anywhere inside the joined error\n\tfmt.Printf(\"fit a bigger pack: %.1f%% needed\\n\", low.Need)\n}\nfor _, e := range err.(interface{ Unwrap() []error }).Unwrap() {\n\tvar h *HeightError\n\tif errors.As(e, &h) {\n\t\tplan[h.WP-1].Z = h.Limit // every height problem, not just the first\n\t}\n}","language":"go","title":"Collect, type and join errors","walkthrough":"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."},{"body":"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.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"slices\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tlegalMax  = 120.0 // m above ground: EASA open category (FAA Part 107: 400 ft, 121.9 m)\n\theightPad = 5.0   // m under it for barometer error and overshoot\n\thClear    = 8.0   // m horizontal clearance from an obstacle...\n\tvClear    = 10.0  // m ...unless the leg stays this far above its top\n\tlinkRange = 250.0 // m, from a range test at this site\n\tlinkPad   = 40.0  // m inside it\n\treserve   = 25.0  // % left on the ground\n)\nconst cruise, cruiseDrain, hoverDrain, climbCost, stop = 10.0, 0.34, 0.19, 0.10, 2.5 // energy-planning lesson\n\nvar (\n\tfence = []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}}\n\tmast  = drone.Obstacle{Name: \"mast\", X: 100, Y: 6, Radius: 2, Height: 45}\n)\n\ntype FenceError struct {\n\tLeg int\n\tAt  drone.Vec3\n}\ntype HeightError struct {\n\tWP         int\n\tAlt, Limit float64\n}\ntype ObstacleError struct {\n\tLeg       int\n\tMiss, Alt float64\n}\ntype LinkError struct {\n\tWP          int\n\tDist, Limit float64\n}\ntype EnergyError struct{ Need, Have float64 }\n\nfunc (e *FenceError) Error() string { return fmt.Sprintf(\"leg %d leaves the fence at %v\", e.Leg, e.At) }\nfunc (e *HeightError) Error() string {\n\treturn fmt.Sprintf(\"waypoint %d at %.0f m is above the %.0f m limit\", e.WP, e.Alt, e.Limit)\n}\nfunc (e *ObstacleError) Error() string {\n\treturn fmt.Sprintf(\"leg %d passes %.1f m from the mast at %.0f m\", e.Leg, e.Miss, e.Alt)\n}\nfunc (e *LinkError) Error() string {\n\treturn fmt.Sprintf(\"waypoint %d is %.1f m from home, over %.0f m\", e.WP, e.Dist, e.Limit)\n}\nfunc (e *EnergyError) Error() string {\n\treturn fmt.Sprintf(\"needs %.1f%% of a %.0f%% pack\", e.Need, e.Have)\n}\n\n// legs are the lines flown: from take-off, through the waypoints, and RTL home.\nfunc legs(plan []drone.Vec3) [][2]drone.Vec3 {\n\tpts := append(append([]drone.Vec3{{Z: plan[0].Z}}, plan...), drone.Vec3{Z: math.Max(plan[len(plan)-1].Z, 15)})\n\tvar out [][2]drone.Vec3\n\tfor i := 1; i < len(pts); i++ {\n\t\tout = append(out, [2]drone.Vec3{pts[i-1], pts[i]})\n\t}\n\treturn out\n}\n\n// miss is the horizontal gap between a leg and the side of an obstacle.\nfunc miss(o drone.Obstacle, a, b drone.Vec3) float64 {\n\tab, t := b.Sub(a), 0.0\n\tif l2 := ab.X*ab.X + ab.Y*ab.Y; l2 > 0 {\n\t\tt = math.Max(0, math.Min(1, ((o.X-a.X)*ab.X+(o.Y-a.Y)*ab.Y)/l2))\n\t}\n\treturn math.Hypot(a.X+ab.X*t-o.X, a.Y+ab.Y*t-o.Y) - o.Radius\n}\n\n// energy is the charge the plan uses: take-off, legs, stops and the descent.\nfunc energy(plan []drone.Vec3) float64 {\n\tuse, ls := plan[0].Z*climbCost, legs(plan)\n\tfor _, l := range ls {\n\t\tuse += l[1].Sub(l[0]).Horizontal().Len()/cruise*cruiseDrain + math.Max(0, l[1].Z-l[0].Z)*climbCost + stop*hoverDrain\n\t}\n\treturn use + ls[len(ls)-1][1].Z/2*hoverDrain // descent at about 2 m/s\n}\n\n// Check collects every problem with the plan instead of stopping at the first.\nfunc Check(plan []drone.Vec3, battery float64) error {\n\tvar errs []error\n\tfor i, wp := range plan {\n\t\tif limit := legalMax - heightPad; wp.Z > limit {\n\t\t\terrs = append(errs, &HeightError{i + 1, wp.Z, limit})\n\t\t}\n\t\tif d, limit := wp.Horizontal().Len(), linkRange-linkPad; d > limit {\n\t\t\terrs = append(errs, &LinkError{i + 1, d, limit})\n\t\t}\n\t}\n\tfor i, l := range legs(plan) {\n\t\tn := int(l[1].Sub(l[0]).Horizontal().Len()) + 1\n\t\tfor k := 0; k <= n; k++ { // every metre of every leg: the fence is concave\n\t\t\tif p := l[0].Add(l[1].Sub(l[0]).Scale(float64(k) / float64(n))); !drone.Inside(fence, p) {\n\t\t\t\terrs = append(errs, &FenceError{i + 1, p})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif m, low := miss(mast, l[0], l[1]), math.Min(l[0].Z, l[1].Z); m < hClear && low < mast.Height+vClear {\n\t\t\terrs = append(errs, &ObstacleError{i + 1, m, low})\n\t\t}\n\t}\n\tif need := energy(plan) + reserve; need > battery {\n\t\terrs = append(errs, &EnergyError{need, battery})\n\t}\n\treturn errors.Join(errs...)\n}\n\n// Fix repairs, by type, what a program can repair safely and leaves the\n// rest to the operator.\nfunc Fix(plan []drone.Vec3, err error) []drone.Vec3 {\n\tplan = slices.Clone(plan)\n\tfor _, e := range err.(interface{ Unwrap() []error }).Unwrap() {\n\t\tvar h *HeightError\n\t\tvar l *LinkError\n\t\tswitch {\n\t\tcase errors.As(e, &h):\n\t\t\tplan[h.WP-1].Z = h.Limit\n\t\t\tfmt.Printf(\"  fixed: waypoint %d lowered to %.0f m\\n\", h.WP, h.Limit)\n\t\tcase errors.As(e, &l):\n\t\t\tk := (l.Limit - 5) / l.Dist\n\t\t\tplan[l.WP-1].X, plan[l.WP-1].Y = plan[l.WP-1].X*k, plan[l.WP-1].Y*k\n\t\t\tfmt.Printf(\"  fixed: waypoint %d pulled in to %v\\n\", l.WP, plan[l.WP-1])\n\t\t}\n\t}\n\treturn plan\n}\n\nfunc report(name string, err error) {\n\tlist := err.(interface{ Unwrap() []error }).Unwrap() // what errors.Join returns\n\tfmt.Printf(\"%s: %d problems\\n\", name, len(list))\n\tfor _, e := range list {\n\t\tfmt.Println(\"  -\", e)\n\t}\n}\n\nfunc fly(plan []drone.Vec3, battery float64) *drone.Sim {\n\tsim := drone.New(drone.Config{Geofence: fence, Ceiling: legalMax, Obstacles: []drone.Obstacle{mast}, LinkRange: linkRange,\n\t\tBattery: battery, Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1, MaxSpeed: cruise, Seed: 5})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttop, gap, bad := 0.0, math.Inf(1), 0\n\twatch := func(float64) bool {\n\t\ts := d.State()\n\t\ttop, gap = math.Max(top, s.Pos.Z), math.Min(gap, math.Hypot(s.Pos.X-mast.X, s.Pos.Y-mast.Y)-mast.Radius)\n\t\tif !drone.Inside(fence, s.Pos) || !d.Link() {\n\t\t\tbad++\n\t\t}\n\t\treturn d.Arrived() || s.Landed || s.Mode == drone.Crashed\n\t}\n\td.TakeOff(plan[0].Z)\n\tsim.RunUntil(60, watch)\n\tfor _, wp := range plan {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(120, watch)\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(180, watch)\n\ts := d.State()\n\tfmt.Printf(\"  flown: highest %.1f m, closest to the mast %.1f m, steps outside the fence or the link %d\\n\", top, gap, bad)\n\tfmt.Printf(\"  %s %.1f m from home; used %.1f%%, the plan said %.1f%%\\n\", s.Mode, s.Pos.Horizontal().Len(), battery-s.Battery, energy(plan))\n\treturn sim\n}\n\nfunc main() {\n\tfmt.Printf(\"limits: under %.0f m (%.0f m legal), within %.0f m (%.0f m link), %.0f m from the mast, %.0f%% reserve\\n\",\n\t\tlegalMax-heightPad, legalMax, linkRange-linkPad, linkRange, hClear, reserve)\n\tplanA := []drone.Vec3{{X: 180, Z: 40}, {X: 210, Y: 60, Z: 40}, {X: 60, Y: 150, Z: 40}, {X: 60, Y: 150, Z: 130}}\n\terr := Check(planA, 60)\n\treport(\"plan A on a 60% pack\", err)\n\tfixed := Fix(planA, err)\n\terr = Check(fixed, 60)\n\treport(\"plan A, fixed\", err)\n\tbattery := 60.0\n\tvar low *EnergyError\n\tif errors.As(err, &low) { // As finds it inside the joined error\n\t\tbattery = 100 // the operator fits a full pack\n\t}\n\t// The operator's edits: a detour south of the mast and a turn inside the fence's corner.\n\tplanB := slices.Insert(slices.Clone(fixed), 2, drone.Vec3{X: 75, Y: 55, Z: 40})\n\tplanB = slices.Insert(planB, 0, drone.Vec3{X: 100, Y: -20, Z: 40})\n\tif err := Check(planB, battery); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"plan B on a %.0f%% pack: no problems, %d waypoints, needs %.1f%% with the reserve\\n\", battery, len(planB), energy(planB)+reserve)\n\tif err := fly(planB, battery).Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Check, fix, check again, fly","walkthrough":"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."},{"body":"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.","title":"What a program may fix, and what it may not"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Preflight checks as code: fence legs, height limits, obstacle clearance, link and energy with errors.Join","unitID":"drones-operations","wrongAnswers":["Ray casting misclassifies points inside concave shapes","The autopilot checks the fence only at waypoints"]},{"conceptTag":"drones.remote-id","designGuide":{"cautions":["This teaching format is not ASTM F3411; real devices differ.","Plausibility checks do not authenticate the sender."],"cost":"A fixed binary layout, a clock synchronised to UTC, and a receiver that keeps each sender's last good position.","family":"drones","flow":["Encode the message set","Broadcast at least 1 Hz","Check age, jumps, gaps","Show the track and its age"],"ratings":[],"strengths":["Fixed-size binary structs make encoding short and exact.","Dropping implausible frames keeps one bad frame out of the track."]},"hint":"The FAA's rule allows at most 1.0 s from measuring a position to broadcasting it. Compare the time mark with a clock you trust.","id":"drones.remote-id","introduction":"Remote ID is a drone's digital licence plate: while it flies it broadcasts who it is, where it is and where its control station is, so that people nearby, the authorities and other airspace users can see it. For a developer it is also a small protocol problem: a fixed message set, scaled integers in a few bytes, a strict clock, and a receiver that must decide which frames to believe. This lesson builds both ends with a teaching format, and is explicit about which parts are the regulators' requirements and which are the model's.","nuance":"A frame measured 3 s ago may be a delayed or replayed copy, and using it moves the track backwards. Drop it, count it, and keep showing the last fresh position with its age.","objective":"State what standard Remote ID broadcasts and how often according to the FAA, and what EASA says the European broadcast carries; encode a simplified message set (identity, position and altitude, velocity, control station, time mark, emergency status) with encoding/binary; and build a receiver that checks freshness, plausibility and missing fields on simulator telemetry.","question":"A Remote ID receiver gets a location frame whose time mark is 3 s older than its own UTC clock. What should it do with it?","references":["https://www.faa.gov/uas/getting_started/remote_id","https://www.faa.gov/sites/faa.gov/files/2021-08/RemoteID_Final_Rule.pdf","https://www.easa.europa.eu/en/document-library/general-publications/remote-identification-will-become-mandatory-drones-across","https://pkg.go.dev/encoding/binary"],"reviewAnswer":"Drop it and keep the last fresh position","reviewPrompt":"What to do with a stale RID frame?","sections":[{"body":"In the US, drones that are registered or required to be registered must comply with the Remote ID rule, 14 CFR Part 89, in one of three ways: a Standard Remote ID drone, a broadcast module (then the pilot must be able to see the drone throughout the flight), or flying inside an FAA-Recognized Identification Area. The FAA says a Standard Remote ID drone broadcasts from takeoff to shutdown: its ID (serial number, or in future a session ID), its location and altitude, its velocity, the control station's location and elevation, a time mark and its emergency status. A broadcast module sends the take-off location instead of the control station and no emergency status. The rule's performance requirements ask for at least one message per second, position and altitude broadcast no later than 1.0 s after they were measured, positions accurate to within 100 feet with 95 percent probability, and no take-off unless the broadcast works. In the EU, EASA's open-category page says that drones operating in the open category, with limited exceptions, need a remote identification system, and EASA's announcement for 1 January 2024 lists the drone's serial number, the operator registration number, the drone's location and the remote pilot's position, or the take-off point if that is not available.","title":"What the rules ask for"},{"body":"The program's format is a model for learning, not ASTM F3411, the standard real Remote ID equipment implements over Bluetooth and Wi-Fi; real devices differ in layout, scaling and message split. Here a frame is a type byte, a 2-byte sender address that plays the part of a radio's MAC address, and a fixed-size body. Identity carries a kind (serial number or session ID) and 20 ASCII bytes. Location carries the time mark in milliseconds after midnight UTC, latitude and longitude in degrees times 10 million, geometric altitude in decimetres, velocity east, north and up in centimetres per second, the control station's position and altitude, and the emergency status, with 0, 0 meaning the station has no position yet. Because every field has a fixed size, binary.Append encodes the struct in one call and binary.Decode reads it back, both since Go 1.23. On real aircraft the autopilot feeds a Remote ID module: PX4 sends it OPEN_DRONE_ID MAVLink messages such as OPEN_DRONE_ID_LOCATION at 1 Hz, and both PX4 and ArduPilot can refuse to arm when the module reports a problem.","title":"A teaching format in encoding/binary"},{"body":"Anything can arrive over a broadcast: delayed frames, corrupted ones, nonsense. A receiver keeps a track per sender with the last position it accepted, and checks each location frame against it. Freshness compares the time mark with the receiver's own clock, synchronised to UTC from GNSS or the network: a position measured more than about a second ago, the latency the FAA allows, is dropped rather than drawn. Rate compares the gap since the last frame with one second. Plausibility divides the distance from the last accepted position by the time between the time marks: faster than the aircraft can fly, here 45 m/s, about the 100 mph that Part 107 allows, and the frame is dropped while the track keeps its last good position, so one bad frame cannot drag the track two kilometres away and back. Missing fields are reported as a list that shrinks as identity and station position arrive, and the emergency status is reported whenever it changes.","title":"A receiver decides what to believe"},{"body":"The drone takes off to 40 m and flies towards a point 199 m away, beyond its 150 m control link, so the link-loss failsafe brings it home. Once a second the program builds a location frame from the drone's telemetry, around a home at 47.3977419, 8.5456320 and 488 m, and every third second puts the identity frame ahead of it; while the control link is down it sets the emergency status to 1. The receiver starts listening at 1 s, the operator's phone has no position for the first 4 s, and three faults are injected on the way: a 3 s old frame delivered late at 25 s, a position corrupted by 2 km at 50 s, and a fade from 60 to 62 s.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// A TEACHING FORMAT, not ASTM F3411 or any certified Remote ID encoding. It carries the\n// elements the FAA lists for standard Remote ID: identity, position and geometric altitude,\n// velocity, control station position and altitude, a time mark and an emergency status. A frame\n// is a type byte, a 2-byte sender address (a radio's MAC address does this) and a fixed-size body.\nconst TypeIdentity, TypeLocation = 1, 2\n\ntype Identity struct {\n\tKind uint8    // 1 serial number, 2 session ID\n\tID   [20]byte // ASCII, zero padded\n}\n\ntype Location struct {\n\tTimeMs         uint32 // time mark: when the position was measured, ms after 00:00 UTC\n\tLat, Lon       int32  // degrees x 1e7\n\tAltDm          int16  // geometric altitude, decimetres\n\tVE, VN, VU     int16  // velocity east, north, up, cm/s\n\tStnLat, StnLon int32  // control station; 0, 0 while it has no position\n\tStnAltDm       int16\n\tEmergency      uint8 // 0 none, 1 lost link\n}\n\nfunc Encode(kind uint8, sender uint16, body any) []byte {\n\tb, err := binary.Append(binary.LittleEndian.AppendUint16([]byte{kind}, sender), binary.LittleEndian, body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn b\n}\n\nconst (\n\tlat0, lon0, elev = 47.3977419, 8.5456320, 488.0 // home, and its height\n\tearth            = 6378137.0                    // m\n\tday0             = 36000000                     // 10:00:00 UTC in ms, when the simulation starts\n\tmaxSpeed         = 45.0                         // m/s, about 100 mph\n)\n\nfunc toLatLon(p drone.Vec3) (int32, int32) {\n\tlat := lat0 + p.Y/earth*180/math.Pi\n\tlon := lon0 + p.X/(earth*math.Cos(lat0*math.Pi/180))*180/math.Pi\n\treturn int32(math.Round(lat * 1e7)), int32(math.Round(lon * 1e7))\n}\n\n// metres between two encoded positions, on a local flat plane\nfunc metres(aLat, aLon, bLat, bLon int32) float64 {\n\tn := float64(bLat-aLat) / 1e7 * math.Pi / 180 * earth\n\te := float64(bLon-aLon) / 1e7 * math.Pi / 180 * earth * math.Cos(lat0*math.Pi/180)\n\treturn math.Hypot(n, e)\n}\n\n// Track is what a receiver knows about one sender.\ntype Track struct {\n\tID                string\n\tLoc               Location // the last location accepted\n\tMissing           string   // fields not received yet\n\tHeardAt           float64  // receiver time of the last location frame\n\tAccepted, Dropped int\n}\n\nfunc (t *Track) warn(now float64, format string, args ...any) {\n\tfmt.Printf(\"  %5.1f s  %-16s %s\\n\", now, t.ID, fmt.Sprintf(format, args...))\n}\n\n// Receive validates a frame: freshness against the receiver's own clock,\n// plausibility against the last accepted position, and missing fields.\nfunc Receive(tracks map[uint16]*Track, now float64, f []byte) {\n\tsender := binary.LittleEndian.Uint16(f[1:3])\n\tt := tracks[sender]\n\tif t == nil {\n\t\tt = &Track{HeardAt: now}\n\t\ttracks[sender] = t\n\t}\n\tif f[0] == TypeIdentity {\n\t\tvar id Identity\n\t\tif _, err := binary.Decode(f[3:], binary.LittleEndian, &id); err == nil {\n\t\t\tt.ID = strings.TrimRight(string(id.ID[:]), \"\\x00\")\n\t\t}\n\t\treturn\n\t}\n\tvar l Location\n\tif _, err := binary.Decode(f[3:], binary.LittleEndian, &l); f[0] != TypeLocation || err != nil {\n\t\treturn\n\t}\n\tif gap := now - t.HeardAt; gap > 1.5 {\n\t\tt.warn(now, \"no location for %.1f s, under 1 per second\", gap)\n\t}\n\tt.HeardAt = now\n\tif age := float64(day0+int64(math.Round(now*1000))-int64(l.TimeMs)) / 1000; age > 1 {\n\t\tt.Dropped++\n\t\tt.warn(now, \"stale: measured %.1f s ago; dropped\", age)\n\t\treturn\n\t}\n\tif t.Accepted > 0 {\n\t\tdt := float64(l.TimeMs-t.Loc.TimeMs) / 1000\n\t\tif d := metres(t.Loc.Lat, t.Loc.Lon, l.Lat, l.Lon); d/dt > maxSpeed {\n\t\t\tt.Dropped++\n\t\t\tt.warn(now, \"moved %.0f m in %.1f s, %.0f m/s; dropped\", d, dt, d/dt)\n\t\t\treturn\n\t\t}\n\t}\n\tvar missing []string\n\tif t.ID == \"\" {\n\t\tmissing = append(missing, \"identity\")\n\t}\n\tif l.StnLat == 0 && l.StnLon == 0 {\n\t\tmissing = append(missing, \"control station position\")\n\t}\n\tif m := strings.Join(missing, \", \"); m != t.Missing {\n\t\tt.Missing = m\n\t\tt.warn(now, \"missing: %s\", cmp.Or(m, \"nothing now\"))\n\t}\n\tif l.Emergency != t.Loc.Emergency {\n\t\tt.warn(now, \"emergency status %d (0 none, 1 lost link)\", l.Emergency)\n\t}\n\tt.Loc = l\n\tt.Accepted++\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{LinkRange: 150, Wind: drone.Vec3{X: 2, Y: -1}, Gust: 1, MaxSpeed: 8, Seed: 7})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(40)\n\tid := Identity{Kind: 1}\n\tcopy(id.ID[:], \"GF-1581F4A7C2D90\")\n\tconst me = 0x0B17 // this drone's sender address\n\ttracks := map[uint16]*Track{}\n\tvar history [][]byte\n\tsent, out := 0, false\n\tfor k := 0; k == 0 || !d.State().Landed; k++ { // one broadcast per second\n\t\tnow, tel := sim.Time(), d.Telemetry()\n\t\tloc := Location{TimeMs: uint32(day0 + math.Round(tel.Time*1000)), AltDm: int16(math.Round((elev + tel.GPS.Z) * 10)),\n\t\t\tVE: int16(tel.Velocity.X * 100), VN: int16(tel.Velocity.Y * 100), VU: int16(tel.Velocity.Z * 100), StnAltDm: (elev + 1.5) * 10}\n\t\tloc.Lat, loc.Lon = toLatLon(tel.GPS)\n\t\tif k >= 4 { // the operator's phone needs a few seconds for a fix\n\t\t\tloc.StnLat, loc.StnLon = toLatLon(drone.Vec3{X: -3, Y: -2})\n\t\t}\n\t\tif !d.Link() {\n\t\t\tloc.Emergency = 1\n\t\t}\n\t\tframes := [][]byte{Encode(TypeLocation, me, &loc)}\n\t\thistory = append(history, frames[0])\n\t\tif k%3 == 0 { // the identity never changes: every 3 s, ahead of the location\n\t\t\tframes = append([][]byte{Encode(TypeIdentity, me, &id)}, frames...)\n\t\t}\n\t\tsent += len(frames)\n\t\tif k == 1 {\n\t\t\tfmt.Printf(\"location frame, %d bytes:\\n  % x\\n\", len(history[1]), history[1])\n\t\t\tfmt.Printf(\"  time %d ms, %.7f, %.7f, %.1f m, velocity %d %d %d cm/s, emergency %d\\nreceiver\\n\",\n\t\t\t\tloc.TimeMs, float64(loc.Lat)/1e7, float64(loc.Lon)/1e7, float64(loc.AltDm)/10, loc.VE, loc.VN, loc.VU, loc.Emergency)\n\t\t}\n\t\tswitch {\n\t\tcase k == 0: // the receiver starts listening at 1 s\n\t\t\tframes = nil\n\t\tcase k == 25: // a frame from 3 s ago arrives late, ahead of the current one\n\t\t\tframes = append([][]byte{history[k-3]}, frames...)\n\t\tcase k == 50: // a corrupted position, 2 km off\n\t\t\tbad := loc\n\t\t\tbad.Lat += 180000\n\t\t\tframes[len(frames)-1] = Encode(TypeLocation, me, &bad)\n\t\tcase k >= 60 && k < 63: // a fade: nothing arrives\n\t\t\tframes = nil\n\t\t}\n\t\tfor _, f := range frames {\n\t\t\tReceive(tracks, now, f)\n\t\t}\n\t\tif t := tracks[me]; k%20 == 0 && k > 0 {\n\t\t\tl := t.Loc\n\t\t\tfmt.Printf(\"  %5.1f s  %-16s %.7f, %.7f, %.1f m, %.1f m/s, pilot %.0f m away\\n\", now, t.ID, float64(l.Lat)/1e7, float64(l.Lon)/1e7,\n\t\t\t\tfloat64(l.AltDm)/10, math.Hypot(float64(l.VE), float64(l.VN))/100, metres(l.Lat, l.Lon, l.StnLat, l.StnLon))\n\t\t}\n\t\tsim.Run(1, func(float64) {\n\t\t\tif d.Arrived() && !out {\n\t\t\t\tout = true\n\t\t\t\td.GoTo(drone.Vec3{X: 60, Y: 190, Z: 40}) // beyond the 150 m control link\n\t\t\t}\n\t\t})\n\t}\n\tt := tracks[me]\n\tfmt.Printf(\"frames sent %d; locations accepted %d, dropped %d\\n\", sent, t.Accepted, t.Dropped)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Broadcast from the simulator, receive with faults","walkthrough":"The location frame of 1 s is 34 bytes: 02 is the type, 17 0b the sender 0x0B17 little-endian, e8 54 25 02 the time mark 36001000 ms, then latitude 47.3977456 and longitude 8.5456223 times 1e7, 22 13 for 489.8 m, velocity -3, 0 and 266 cm/s on the climb, eight zero bytes for a control station without a position, 1f 13 for its 489.5 m, and emergency 0. At 1.0 s the receiver reports both the identity and the control station position missing; the identity arrives at 3.0 s and the station's fix at 4.0 s, when nothing is missing any more. At 25.0 s a frame measured 3.0 s ago is dropped as stale. At 36.0 s the emergency status becomes 1: the drone is beyond its control link and says so, while its own ground station sees nothing; it returns to 0 at 48.0 s. At 50.0 s a jump of 1995 m in 1.0 s is dropped, and the fade shows at 63.0 s as no location for 4.0 s. The status lines put the pilot 34 m away at 20 s, 193 m at 40 s and 3 m at 80 s. 119 frames were sent; 84 locations were accepted and 2 dropped."},{"body":"Remote ID is a public broadcast by design, and the rules limit what the public learns from it. The FAA keeps the link between a serial number or session ID and the registration database to itself, available to law enforcement on request; EASA says anyone can read the broadcast with a smartphone app, but only enforcement authorities can associate the operator registration number with a name. A receiver should show what it heard, how old it is and what it dropped, and leave identification to them. The plausibility checks catch errors and crude spoofing, but they do not authenticate anyone: a careful forger can send frames that pass them. Treat a track as a claim. For operators, Remote ID is a preflight item: verify that the module works and that the control station has its position before take-off, and never fly with a broadcast you know is wrong.","title":"Privacy, trust and limits"},{"body":"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 encoded frame and everything the receiver reported; Output replays flight.gfflight with the drone crossing the dashed 150 m link circle, turning back when the link-loss failsafe fires and landing at home. Move the faults, lower maxSpeed to 10 m/s, or send the identity every 10 s, and watch which checks fire.","title":"Fly it in GopherForge"}],"takeaway":"Standard Remote ID broadcasts identity, position, altitude, velocity, the control station, a time mark and an emergency status at least once a second, from take-off to shutdown. Fixed-size structs make a teaching format short with encoding/binary; a receiver should drop stale and implausible frames, keep the last good position, report missing fields, and treat every track as an unauthenticated claim.","title":"Remote ID: the broadcast message set, a binary teaching format and a validating receiver","unitID":"drones-operations","wrongAnswers":["Accept it, since the position itself is plausible","Replace the track with it, since newer frames may be lost"]},{"conceptTag":"drones.strategic-deconfliction","designGuide":{"cautions":["Buffers smaller than real tracking and timing errors void the plan.","A strategic plan does not replace tactical separation in flight."],"cost":"A volume builder with performance buffers, an atomic reservation store and a conformance monitor on live telemetry.","family":"drones","flow":["Plan segmented 4D volumes","Check time, height, ground","Reserve, move or reject","Fly and check conformance"],"ratings":[],"strengths":["Most conflicts are settled before any drone takes off.","Segmented volumes free the sky as soon as a leg is flown."]},"hint":"A corridor that crosses a survey area at the same height is harmless if the survey has already landed. Which dimensions must overlap together?","id":"drones.strategic-deconfliction","introduction":"The fleets lesson kept drones apart in flight: altitude layers and a monitor that reacts when two aircraft get close. That is the tactical layer, and it works with seconds of warning. The strategic layer works before take-off: every operation declares the airspace it will use and when, and a service accepts only plans whose volumes do not overlap. Done well, most conflicts are settled on the ground; done badly, two plans that each look fine on their own meet over the same field.","nuance":"Overlap in one or two dimensions is not a conflict: a later window or a higher band separates the plans. Only when time, altitude band and buffered footprint all overlap can the drones meet.","objective":"Describe each operation as segmented 4D volumes (footprint, altitude band, time window), detect conflicts by overlap in time, altitude and buffered footprint, reserve intents first come, first served by moving or rejecting newcomers, then fly the accepted plans with several drones and verify conformance and separation.","question":"A strategic deconfliction service compares two operation volumes. When does it report a conflict?","references":["https://www.faa.gov/uas/advanced_operations/traffic_management","https://www.faa.gov/researchdevelopment/trafficmanagement/utm-concept-operations-version-20-utm-conops-v20","https://www.easa.europa.eu/en/regulations/u-space","https://github.com/interuss/dss"],"reviewAnswer":"When time, altitude and footprint all overlap","reviewPrompt":"When do two 4D volumes conflict?","sections":[{"body":"An operation is described by the airspace it will occupy: a footprint on the ground (an area to survey, or a corridor along a route), an altitude band and a time window. Each dimension is padded for what can go wrong: the footprint by the vehicle's navigation and tracking error, the band by barometer and altitude-hold error, the window by late take-offs, headwinds and slow climbs. Splitting a flight into segments (a climb above home, a cruise corridor, a descent at the destination) frees each piece of sky as soon as it is flown. The FAA's UTM Concept of Operations v2.0 describes Operation Volumes as 4D blocks of airspace with entry and exit times, stacked in sequence along the flight, with performance buffers applied by the service supplier. EASA's guidance to the U-space regulation, Implementing Regulation (EU) 2021/664, describes a flight authorisation request the same way: a series of 4D volumes with a base and ceiling, lateral and longitudinal limits and entry and exit times, each including the flight's uncertainties.","title":"Operations as 4D volumes"},{"body":"Two volumes conflict only if they overlap in time, in altitude and on the ground at once. Time and altitude are intervals, and half-open intervals [From, To) overlap exactly when a.From < b.To and b.From < a.To, so a volume that opens when another closes is not a conflict and back-to-back reservations work. The footprint test is geometry: the distance between two corridors is the smallest distance between their segments (zero if two segments cross), an area polygon also conflicts when a point of the other footprint lies inside it, and the pair conflicts when that distance is below the sum of the two buffers. Run the interval tests first: they cost two comparisons and reject almost every pair in a busy schedule, so the segment geometry runs only for volumes that share time and height. Store volumes in absolute time and metres, and decide once whether buffers grow the footprint or the minimum distance; adding them twice wastes airspace, forgetting them loses separation.","title":"Conflict: three overlaps, cheapest first"},{"body":"A reservation service must decide in a fixed order and never change its mind about accepted plans. EASA's acceptable means of compliance and guidance material ask U-space service providers to reject a request that conflicts with an earlier one of the same or higher priority, to process requests of equal priority in the order they were submitted, to keep a change that would cause a conflict from replacing the accepted authorisation, and to record rejections with their reasons. The FAA ConOps lists the ways to resolve a conflict: move a volume's entry and exit times, change its lateral or vertical limits, or both, and negotiate between operators when that fails. The program's Registry follows the simplest policy: it tries the intent as filed, then later in 5 s steps up to the delay its operator accepts, and otherwise rejects it with the conflicting intent's ID. The check and the insert must be one atomic step, under one mutex or in one database transaction; two requests that both check before either inserts will both be accepted. Between service suppliers this coordination is distributed: in the US the FAA names the Discovery and Synchronization Service (DSS) as the component that connects them, and InterUSS publishes an open-source DSS written in Go.","title":"Reserve, move or reject"},{"body":"The program files four intents in order: alpha surveys a 60 by 60 m field at 30 m (one area volume, 0 to 40 m, until 80 s); bravo flies a delivery corridor straight across the field at 30 m; charlie crosses it at 50 m; delta wants to photograph a point inside the field at 20 m. corridor() builds the climb, cruise and descent volumes from nominal climb, cruise and descent times. Reserve moves or rejects. Then Fly flies the plans in one simulation, twice: once as filed, ignoring the decisions, and once as reserved. Every 0.2 s it checks each airborne drone against its own volumes with the same conflict function, using a point-sized probe, and keeps the closest approach of every pair.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"slices\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Volume is a 4D block of airspace: a footprint grown by Half metres, an altitude\n// band [Lo, Hi) and a time window [From, To) in s. The footprint is a polyline (a\n// corridor's centre line, a point given twice) or, with Area, a closed polygon.\ntype Volume struct {\n\tPath     []drone.Vec3\n\tArea     bool\n\tHalf     float64\n\tLo, Hi   float64\n\tFrom, To float64\n}\n\n// Intent is an operation filed before flight, and the route flown (from home).\ntype Intent struct {\n\tID, Drone       string\n\tStart, MaxDelay float64\n\tVolumes         []Volume\n\tRoute           []drone.Vec3\n}\n\nconst speed = 8.0 // m/s, the cruise speed the plans assume\n\n// corridor plans a flight from home to dest at alt as three volumes: the\n// climb above home, the cruise corridor and the descent at dest. Windows\n// come from nominal performance, padded by 5 s each way.\nfunc corridor(id, name string, home, dest drone.Vec3, alt, start, maxDelay float64) Intent {\n\tt1 := start + alt/2.5 + 2\n\tt2 := t1 + dest.Sub(home).Len()/speed + 3\n\tt3 := t2 + alt/2 + 6\n\treturn Intent{ID: id, Drone: name, Start: start, MaxDelay: maxDelay,\n\t\tRoute: []drone.Vec3{home, {X: dest.X, Y: dest.Y, Z: alt}},\n\t\tVolumes: []Volume{\n\t\t\t{Path: []drone.Vec3{home, home}, Half: 5, Lo: 0, Hi: alt + 5, From: start - 5, To: t1 + 5},\n\t\t\t{Path: []drone.Vec3{home, dest}, Half: 8, Lo: alt - 5, Hi: alt + 5, From: t1 - 5, To: t2 + 5},\n\t\t\t{Path: []drone.Vec3{dest, dest}, Half: 5, Lo: 0, Hi: alt + 5, From: t2 - 5, To: t3 + 5},\n\t\t}}\n}\n\nfunc cross(o, a, b drone.Vec3) float64 { return (a.X-o.X)*(b.Y-o.Y) - (a.Y-o.Y)*(b.X-o.X) }\n\n// pointSeg is the horizontal distance from p to the segment ab.\nfunc pointSeg(p, a, b drone.Vec3) float64 {\n\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\tt := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/max(ab.X*ab.X+ab.Y*ab.Y, 1e-9)))\n\treturn ap.Sub(ab.Scale(t)).Len()\n}\n\n// segDist is the distance between segments ab and cd: 0 if they cross.\nfunc segDist(a, b, c, d drone.Vec3) float64 {\n\tif cross(a, b, c)*cross(a, b, d) < 0 && cross(c, d, a)*cross(c, d, b) < 0 {\n\t\treturn 0\n\t}\n\treturn min(pointSeg(a, c, d), pointSeg(b, c, d), pointSeg(c, a, b), pointSeg(d, a, b))\n}\n\n// gap is the horizontal distance between two footprints, 0 if they overlap.\nfunc gap(a, b Volume) float64 {\n\tif a.Area && drone.Inside(a.Path, b.Path[0]) || b.Area && drone.Inside(b.Path, a.Path[0]) {\n\t\treturn 0\n\t}\n\tbest := math.Inf(1)\n\tfor i := 1; i < len(a.Path); i++ {\n\t\tfor j := 1; j < len(b.Path); j++ {\n\t\t\tbest = min(best, segDist(a.Path[i-1], a.Path[i], b.Path[j-1], b.Path[j]))\n\t\t}\n\t}\n\treturn best\n}\n\n// conflict: overlapping in time, in altitude and on the ground, cheapest first.\nfunc conflict(a, b Volume) bool {\n\treturn a.From < b.To && b.From < a.To && a.Lo < b.Hi && b.Lo < a.Hi && gap(a, b) < a.Half+b.Half\n}\n\n// Registry reserves intents first come, first served.\ntype Registry struct{ accepted []Intent }\n\nfunc (r *Registry) conflictWith(in Intent) string {\n\tfor _, old := range r.accepted {\n\t\tfor _, a := range in.Volumes {\n\t\t\tif slices.ContainsFunc(old.Volumes, func(b Volume) bool { return conflict(a, b) }) {\n\t\t\t\treturn old.ID\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// Reserve accepts an intent as filed or, in 5 s steps, as late as its\n// operator allows. Accepted intents are never moved for a newcomer.\nfunc (r *Registry) Reserve(in Intent) (Intent, string, bool) {\n\tfirst := r.conflictWith(in)\n\tfor delay := 0.0; delay <= in.MaxDelay; delay += 5 {\n\t\ttry := in\n\t\ttry.Start, try.Volumes = in.Start+delay, slices.Clone(in.Volumes)\n\t\tfor k := range try.Volumes {\n\t\t\ttry.Volumes[k].From += delay\n\t\t\ttry.Volumes[k].To += delay\n\t\t}\n\t\tif r.conflictWith(try) == \"\" {\n\t\t\tr.accepted = append(r.accepted, try)\n\t\t\tif delay == 0 {\n\t\t\t\treturn try, \"accepted\", true\n\t\t\t}\n\t\t\treturn try, fmt.Sprintf(\"conflicts with %s: moved +%.0f s\", first, delay), true\n\t\t}\n\t}\n\treturn in, fmt.Sprintf(\"rejected: conflicts with %s up to +%.0f s\", first, in.MaxDelay), false\n}\n\n// Fly flies the plans and prints closest approaches and conformance.\nfunc Fly(sim *drone.Sim, plans []Intent) {\n\tds := []*drone.Drone{sim.Drone()}\n\tfor _, p := range plans[1:] {\n\t\tds = append(ds, sim.AddDrone(p.Drone, p.Route[0]))\n\t}\n\tleg, in, n, closest := make([]int, len(plans)), make([]int, len(plans)), make([]int, len(plans)), map[[2]int]drone.Vec3{}\n\tfor ; sim.Time() < 150; sim.Run(0.2, nil) {\n\t\tt := sim.Time()\n\t\tfor i, p := range plans {\n\t\t\tswitch d := ds[i]; {\n\t\t\tcase leg[i] == 0 && t >= p.Start-1e-9:\n\t\t\t\td.Arm()\n\t\t\t\td.TakeOff(p.Route[1].Z)\n\t\t\t\tleg[i] = 1\n\t\t\tcase leg[i] > 0 && leg[i] < len(p.Route) && d.Arrived():\n\t\t\t\td.GoTo(p.Route[leg[i]])\n\t\t\t\tleg[i]++\n\t\t\tcase leg[i] == len(p.Route) && d.Arrived():\n\t\t\t\td.Land()\n\t\t\t\tleg[i]++\n\t\t\t}\n\t\t\tst := ds[i].State()\n\t\t\tif st.Landed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Conformance is a conflict test of a point against its own volumes.\n\t\t\tn[i]++\n\t\t\tprobe := Volume{Path: []drone.Vec3{st.Pos, st.Pos}, Lo: st.Pos.Z, Hi: st.Pos.Z + 0.01, From: t, To: t + 0.01}\n\t\t\tif slices.ContainsFunc(p.Volumes, func(v Volume) bool { return conflict(probe, v) }) {\n\t\t\t\tin[i]++\n\t\t\t}\n\t\t\tfor j := range i {\n\t\t\t\toff, k := st.Pos.Sub(ds[j].State().Pos), [2]int{j, i}\n\t\t\t\tif c, ok := closest[k]; !ds[j].State().Landed && (!ok || off.Len() < c.Len()) {\n\t\t\t\t\tclosest[k] = off\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range plans {\n\t\tfor j := range i {\n\t\t\tif c, ok := closest[[2]int{j, i}]; ok {\n\t\t\t\tfmt.Printf(\"  %-7s %-7s closest %5.1f m (%4.1f m horizontal, %4.1f m vertical)\\n\", ds[j].Name, ds[i].Name, c.Len(), c.Horizontal().Len(), math.Abs(c.Z))\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"  %-7s %-7s never airborne together\\n\", ds[j].Name, ds[i].Name)\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"  samples inside own volumes: %v of %v\\n\", in, n)\n}\n\nfunc main() {\n\tfield := []drone.Vec3{{X: -10, Y: -30}, {X: 50, Y: -30}, {X: 50, Y: 30}, {X: -10, Y: 30}, {X: -10, Y: -30}}\n\tfiled := []Intent{\n\t\t{ID: \"survey\", Drone: \"alpha\", Volumes: []Volume{{Path: field, Area: true, Half: 5, Lo: 0, Hi: 40, From: -5, To: 80}},\n\t\t\tRoute: []drone.Vec3{{}, {Y: -20, Z: 30}, {X: 40, Y: -20, Z: 30}, {X: 40, Y: 20, Z: 30}, {Y: 20, Z: 30}, {Z: 30}}},\n\t\tcorridor(\"delivery\", \"bravo\", drone.Vec3{X: -50, Y: -40}, drone.Vec3{X: 100, Y: 40}, 30, 2, 90),\n\t\tcorridor(\"inspection\", \"charlie\", drone.Vec3{X: 70, Y: -50}, drone.Vec3{X: -20, Y: 50}, 50, 15, 30),\n\t\tcorridor(\"photo\", \"delta\", drone.Vec3{X: 20, Y: -70}, drone.Vec3{X: 20, Y: 10}, 20, 20, 30),\n\t}\n\treg, plans := Registry{}, []Intent{}\n\tfmt.Println(\"intent      drone    filed   volumes  decision\")\n\tfor _, in := range filed {\n\t\tgot, decision, ok := reg.Reserve(in)\n\t\tfmt.Printf(\"%-11s %-8s %4.0f s  %d        %s\\n\", in.ID, in.Drone, in.Start, len(in.Volumes), decision)\n\t\tif ok {\n\t\t\tplans = append(plans, got)\n\t\t}\n\t}\n\tworld := drone.Config{Wind: drone.Vec3{X: 3, Y: -2}, Gust: 1, MaxSpeed: speed, Seed: 9}\n\tfmt.Println(\"flown as filed, without deconfliction:\")\n\tFly(drone.New(world), filed)\n\tfmt.Println(\"flown as reserved:\")\n\tsim := drone.New(world)\n\tFly(sim, plans)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Reserve, then fly","walkthrough":"The survey is accepted. The delivery conflicts with it: its cruise volume opens 9 s after take-off (12 s of climb plus 2 s of padding minus the 5 s buffer), so it must start at 71 s or later, and the first 5 s step that fits is +70 s, take-off at 72 s. The inspection is accepted as filed because its 45 to 55 m cruise band lies above the survey's 0 to 40 m. The photo flight would need about +55 s and its operator accepts 30, so it is rejected with the reason. Flown as filed, alpha and bravo pass 0.9 m apart at the same height. Alpha and delta, whose volumes also conflicted, happen to stay 22.4 m apart: a conflict is a risk the plan no longer excludes, not a predicted collision. Flown as reserved, alpha and bravo are never airborne together, alpha and charlie are never closer than 33.6 m (21.1 m horizontally, 26.2 m vertically), and every sample of every drone lies inside its own volumes: 300, 267 and 328 of 300, 267 and 328."},{"body":"A plan protects only while the aircraft stays inside it, so the strategic layer needs conformance monitoring in flight: compare each position report with the active volumes, as the program does with a point probe, and alert when a drone leaves them. The FAA ConOps has the service supplier change such an operation's state to Non-Conforming or Rogue and share it with the USS network, so that affected operators are notified; EASA's guidance notes that the 4D volumes of a flight authorisation may be used by a conformance monitoring service. Size volumes from measured performance: EASA's guidance expects flights to stay inside their authorised volumes about 95 percent of the time, and warns that thresholds can also be too wide and waste airspace. When an operation is delayed or rerouted, file the change as a new request against everyone else's plans before flying it. Strategic deconfliction does not replace the tactical layer: a gust, a late take-off or an aircraft outside the system still needs the separation monitor and the failsafes from the earlier lessons.","title":"Conformance, and when plans change"},{"body":"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 decisions and both comparisons; Output replays the reserved schedule: alpha mows the field, charlie crosses high above it, and bravo crosses the field only after alpha has landed. Raise the photo flight's maximum delay from 30 to 60 s and it is moved by 55 s instead of rejected; or move charlie's corridor down to 30 m: it now shares the survey's band and is rejected as well.","title":"Fly it in GopherForge"}],"takeaway":"Describe every operation as segmented 4D volumes with buffers for navigation and timing, and call two volumes in conflict only when time, altitude and buffered footprint all overlap. Reserve atomically and in order, move or reject the newcomer rather than an accepted plan, and verify in flight that each drone stays inside its own volumes; tactical separation remains the next layer.","title":"Strategic deconfliction: 4D volumes, reservations and flying the accepted plans","unitID":"drones-operations","wrongAnswers":["When their footprints overlap, whatever the times","When either the windows or the altitude bands overlap"]},{"conceptTag":"drones.fleet-backend","designGuide":{"cautions":["The key must be stored atomically with the mission it created.","An API that ignores radio range accepts unflyable missions."],"cost":"A mission store with an idempotency table, a dispatcher loop with a state machine, and handler tests on httptest recorders.","family":"drones","flow":["Validate and store by key","Queue, assign, fly","Fail on any failsafe","Expose state over GET"],"ratings":[],"strengths":["Client retries never create a second flight.","Illegal transitions fail loudly instead of corrupting state."]},"hint":"The first request may well have succeeded; only its response was lost. What must the retry get so that no second drone takes off?","id":"drones.fleet-backend","introduction":"Behind every delivery or inspection service sits a backend: clients create missions, a dispatcher hands them to vehicles, and everyone polls for progress. Mobile networks lose responses, so clients retry, and a retried POST that creates a second mission sends a second drone. The dispatcher must also tell the truth about outcomes: a mission that ended in a failsafe has failed, even if the drone landed safely at home.","nuance":"Same key and same body: replay the stored response. Same key with another body: 422. A retry while the first request is still running: 409. Only a new key creates a new mission.","objective":"Build a mission API with Go 1.22 ServeMux method and wildcard patterns, make POST safe to retry with an Idempotency-Key, dispatch missions to drones through an explicit queued, assigned, flying, done or failed state machine driven by the autopilot, and exercise it all through httptest without opening a socket.","question":"A POST /missions times out on the client, which retries with the same Idempotency-Key and the same body. What should the server return?","references":["https://go.dev/blog/routing-enhancements","https://pkg.go.dev/net/http/httptest#ResponseRecorder","https://github.com/ietf-wg-httpapi/idempotency","https://pkg.go.dev/net/http#ServeMux"],"reviewAnswer":"The stored first response, not a new mission","reviewPrompt":"What does a retried POST return?","sections":[{"body":"Since Go 1.22, http.ServeMux patterns can name a method and contain wildcards, so most mission APIs need no router library. \"POST /missions\" matches only POST; \"GET /missions/{id}\" matches one path segment after /missions/ and the handler reads it with r.PathValue(\"id\"). GET patterns also match HEAD. When the path matches but the method does not, the mux answers 405 Method Not Allowed with an Allow header listing the methods that would work. When two patterns overlap, the more specific one wins, and registering two that overlap with neither more specific panics at start-up rather than routing at random. The GODEBUG setting httpmuxgo121=1 restores the old behaviour while you migrate.","code":"mux := http.NewServeMux()\nmux.HandleFunc(\"POST /missions\", srv.create)\nmux.HandleFunc(\"GET /missions/{id}\", srv.get) // r.PathValue(\"id\")\n\n// In production the same mux sits behind a server with timeouts.\nserver := &http.Server{Addr: \":8080\", Handler: mux, ReadHeaderTimeout: 5 * time.Second}\nlog.Fatal(server.ListenAndServe())","language":"go","title":"Routes with Go 1.22 patterns","walkthrough":"Two lines register the whole API; the method and the wildcard live in the pattern, not in an if inside the handler. DELETE /missions/m1 never reaches a handler: the mux answers 405 with Allow: GET, HEAD. The http.Server sets ReadHeaderTimeout because with it and ReadTimeout left at zero there is no timeout at all, and a slow client could hold a connection open indefinitely. The lesson program skips the listener entirely."},{"body":"POST is not idempotent: sending it twice may create two missions. The IETF HTTPAPI working group's Idempotency-Key draft standardises the usual fix. The client sends a unique key with the request and reuses it on every retry; the server stores the key with the result and answers a duplicate with the stored result instead of acting again. The draft asks for 400 when a required key is missing, 422 when a key is reused with a different payload (detected with a fingerprint, such as a checksum of the body), and 409 when a retry arrives while the first request is still being processed; it also asks servers to document when keys expire. Store the key in the same atomic step that creates the mission, under one lock or in one transaction with a unique index on the key, and scope keys to the client that sent them. The program compares raw bodies, so the same JSON with different spacing counts as a different payload; comparing a canonical form is kinder to clients.","title":"Idempotency-Key: a retry is not a new mission"},{"body":"A mission moves through queued, assigned, flying, and then done or failed, and the table next lists the only legal moves; move panics on any other, because an impossible transition is a bug to find, not a state to store. Queued missions wait for an idle drone: on the ground, at least 50 percent charge and not already assigned. A flying mission follows its vehicle through climb, outbound, hover and return phases. The autopilot outranks the dispatcher: if the drone switches to a return or a landing that the dispatcher did not command, the mission has failed, and the reason is the autopilot's own latest note, read from sim.Events() as a ground station reads STATUSTEXT. The drone stays busy until it is on the ground, so a failed mission never frees a vehicle that is still flying home. Write every transition to an append-only log as well; it is the first thing anyone asks for when a customer calls.","title":"A dispatch state machine"},{"body":"main registers the routes, then sends requests straight into mux.ServeHTTP with httptest.NewRequest and an httptest.NewRecorder: no port, no socket, nothing for the WASI sandbox of the app to refuse. It creates three missions, retries one, misuses the key, forgets it, asks for a mission outside the service area, a mission that does not exist and a method the API does not have. Then the main loop calls Dispatch every 0.2 s of simulated time with two drones and a 100 m radio range, and polls GET /missions/m3 at 20 s, 60 s and at the end.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// State is where a mission is in dispatch; next lists the legal moves.\ntype State string\n\nconst Queued, Assigned, Flying, Done, Failed State = \"queued\", \"assigned\", \"flying\", \"done\", \"failed\"\n\nvar next = map[State][]State{Queued: {Assigned}, Assigned: {Flying, Failed}, Flying: {Done, Failed}}\n\n// Mission is the stored record and the JSON the API returns.\ntype Mission struct {\n\tID      string     `json:\"id\"`\n\tTarget  [2]float64 `json:\"target\"`\n\tAlt     float64    `json:\"alt\"`\n\tHover   float64    `json:\"hover\"`\n\tState   State      `json:\"state\"`\n\tDrone   string     `json:\"drone,omitempty\"`\n\tPhase   string     `json:\"phase,omitempty\"`\n\tPos     []float64  `json:\"pos,omitempty\"`\n\tBattery float64    `json:\"battery,omitempty\"`\n\tReason  string     `json:\"reason,omitempty\"`\n\tvehicle *drone.Drone\n\tsince   float64\n}\n\n// Server holds the missions and, per Idempotency-Key, the request body and\n// the first response. net/http serves each request on its own goroutine\n// and the dispatcher runs beside them, so one mutex guards all of it.\ntype Server struct {\n\tmu       sync.Mutex\n\tmissions []*Mission\n\tkeys     map[string][2]string\n}\n\n// reply writes v as JSON; a string becomes an RFC 9457 problem document.\nfunc reply(w http.ResponseWriter, status int, v any) string {\n\tkind := \"application/json\"\n\tif title, ok := v.(string); ok {\n\t\tkind, v = \"application/problem+json\", map[string]any{\"status\": status, \"title\": title}\n\t}\n\tbody, _ := json.Marshal(v)\n\tw.Header().Set(\"Content-Type\", kind)\n\tw.WriteHeader(status)\n\tw.Write(body)\n\treturn string(body)\n}\n\nfunc (s *Server) create(w http.ResponseWriter, r *http.Request) {\n\tkey := r.Header.Get(\"Idempotency-Key\")\n\tif key == \"\" {\n\t\treply(w, http.StatusBadRequest, \"Idempotency-Key header required\")\n\t\treturn\n\t}\n\tbody, _ := io.ReadAll(io.LimitReader(r.Body, 4096)) // longer bodies fail to decode\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif old, ok := s.keys[key]; ok && old[0] == string(body) {\n\t\treply(w, http.StatusCreated, json.RawMessage(old[1])) // the first answer again\n\t\treturn\n\t} else if ok {\n\t\treply(w, http.StatusUnprocessableEntity, \"Idempotency-Key reused with another body\")\n\t\treturn\n\t}\n\tvar req struct {\n\t\tTarget     [2]float64 `json:\"target\"`\n\t\tAlt, Hover float64\n\t}\n\tdec := json.NewDecoder(bytes.NewReader(body))\n\tdec.DisallowUnknownFields() // a client cannot send \"state\":\"done\"\n\tif err := dec.Decode(&req); err != nil {\n\t\treply(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tif req.Alt < 10 || req.Alt > 60 || req.Hover > 60 || math.Hypot(req.Target[0], req.Target[1]) > 150 {\n\t\treply(w, http.StatusUnprocessableEntity, \"outside the service area (150 m, 10..60 m up)\")\n\t\treturn\n\t}\n\tm := &Mission{ID: fmt.Sprintf(\"m%d\", len(s.missions)+1), Target: req.Target, Alt: req.Alt, Hover: req.Hover, State: Queued}\n\ts.missions = append(s.missions, m)\n\tw.Header().Set(\"Location\", \"/missions/\"+m.ID)\n\ts.keys[key] = [2]string{string(body), reply(w, http.StatusCreated, m)}\n}\n\nfunc (s *Server) get(w http.ResponseWriter, r *http.Request) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif i := slices.IndexFunc(s.missions, func(m *Mission) bool { return m.ID == r.PathValue(\"id\") }); i >= 0 {\n\t\treply(w, http.StatusOK, s.missions[i])\n\t\treturn\n\t}\n\treply(w, http.StatusNotFound, \"no mission \"+r.PathValue(\"id\"))\n}\n\nfunc move(sim *drone.Sim, m *Mission, to State, why string) {\n\tif !slices.Contains(next[m.State], to) {\n\t\tpanic(fmt.Sprintf(\"%s: illegal %s -> %s\", m.ID, m.State, to))\n\t}\n\tfmt.Printf(\"%6.1f s  %s %-8s -> %-8s %s\\n\", sim.Time(), m.ID, m.State, to, why)\n\tm.State = to\n}\n\n// lastNote is the autopilot's latest note about d, as STATUSTEXT would say.\nfunc lastNote(sim *drone.Sim, d *drone.Drone) (note string) {\n\tfor _, e := range sim.Events() {\n\t\tif e.Drone >= 0 && sim.Drones()[e.Drone] == d {\n\t\t\tnote = e.Text\n\t\t}\n\t}\n\treturn note\n}\n\n// Dispatch moves every mission one step: a queued one gets the first idle\n// drone, a flying one follows its vehicle, and a failsafe fails it.\nfunc Dispatch(s *Server, sim *drone.Sim) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tidle := func(x *drone.Drone) bool {\n\t\treturn x.State().Landed && x.State().Battery >= 50 &&\n\t\t\t!slices.ContainsFunc(s.missions, func(m *Mission) bool { return m.vehicle == x && m.State == Assigned })\n\t}\n\tfor _, m := range s.missions {\n\t\td := m.vehicle\n\t\tswitch m.State {\n\t\tcase Queued:\n\t\t\tif i := slices.IndexFunc(sim.Drones(), idle); i >= 0 {\n\t\t\t\tm.vehicle, m.Drone = sim.Drones()[i], sim.Drones()[i].Name\n\t\t\t\tmove(sim, m, Assigned, \"to \"+m.Drone)\n\t\t\t}\n\t\tcase Assigned:\n\t\t\tif err := d.Arm(); err != nil {\n\t\t\t\tmove(sim, m, Failed, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\td.TakeOff(m.Alt)\n\t\t\tm.Phase = \"climb\"\n\t\t\tmove(sim, m, Flying, fmt.Sprintf(\"take off, battery %.0f%%\", d.State().Battery))\n\t\tcase Flying:\n\t\t\tswitch st := d.State(); {\n\t\t\tcase st.Mode == drone.Crashed || (st.Mode == drone.Returning || st.Mode == drone.Landing) && m.Phase != \"return\":\n\t\t\t\tm.Reason = lastNote(sim, d)\n\t\t\t\tmove(sim, m, Failed, m.Reason)\n\t\t\tcase m.Phase == \"climb\" && d.Arrived():\n\t\t\t\td.GoTo(drone.Vec3{X: m.Target[0], Y: m.Target[1], Z: m.Alt})\n\t\t\t\tm.Phase = \"outbound\"\n\t\t\tcase m.Phase == \"outbound\" && d.Arrived():\n\t\t\t\tm.Phase, m.since = \"hover\", sim.Time()\n\t\t\tcase m.Phase == \"hover\" && sim.Time()-m.since >= m.Hover:\n\t\t\t\td.ReturnHome()\n\t\t\t\tm.Phase = \"return\"\n\t\t\tcase m.Phase == \"return\" && st.Landed:\n\t\t\t\tmove(sim, m, Done, fmt.Sprintf(\"landed %.1f m from home, battery %.0f%%\", st.Pos.Sub(d.Home()).Len(), st.Battery))\n\t\t\t}\n\t\t}\n\t\tif d != nil && !d.State().Landed { // progress for GET\n\t\t\tst, r := d.State(), func(v float64) float64 { return math.Round(v*10)/10 + 0 }\n\t\t\tm.Pos, m.Battery = []float64{r(st.Pos.X), r(st.Pos.Y), r(st.Pos.Z)}, math.Round(st.Battery)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: 1}, Gust: 1, MaxSpeed: 8, LinkRange: 100, Seed: 12})\n\tsim.AddDrone(\"bravo\", drone.Vec3{X: 6})\n\tsrv := &Server{keys: map[string][2]string{}}\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST /missions\", srv.create)\n\tmux.HandleFunc(\"GET /missions/{id}\", srv.get)\n\t// No listener: requests go straight to the mux, so this runs in a WASI\n\t// sandbox without sockets too. A real server calls http.ListenAndServe.\n\tcall := func(method, path, key, body string) {\n\t\treq := httptest.NewRequest(method, path, strings.NewReader(body))\n\t\tif key != \"\" {\n\t\t\treq.Header.Set(\"Idempotency-Key\", key)\n\t\t\tpath += \" key=\" + key\n\t\t}\n\t\trec := httptest.NewRecorder()\n\t\tmux.ServeHTTP(rec, req)\n\t\tresp := strings.TrimSpace(rec.Body.String())\n\t\tif a := rec.Header().Get(\"Allow\"); a != \"\" {\n\t\t\tresp = \"Allow: \" + a + \", \" + resp\n\t\t}\n\t\tfmt.Printf(\"%s\\n    -> %d %s\\n\", strings.TrimSpace(method+\" \"+path+\" \"+body), rec.Code, resp)\n\t}\n\tcall(\"POST\", \"/missions\", \"k-101\", `{\"target\":[40,30],\"alt\":20,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"k-101\", `{\"target\":[40,30],\"alt\":20,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"k-101\", `{\"target\":[40,-30],\"alt\":20,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"\", `{\"target\":[10,10],\"alt\":20,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"k-102\", `{\"target\":[-35,45],\"alt\":25,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"k-103\", `{\"target\":[130,20],\"alt\":20,\"hover\":5}`)\n\tcall(\"POST\", \"/missions\", \"k-104\", `{\"target\":[400,0],\"alt\":20,\"hover\":5}`)\n\tcall(\"GET\", \"/missions/m9\", \"\", \"\")\n\tcall(\"DELETE\", \"/missions/m1\", \"\", \"\")\n\n\tfor sim.Time() < 120 {\n\t\tDispatch(srv, sim)\n\t\tif t := math.Round(sim.Time() * 5); t == 5*20 || t == 5*60 {\n\t\t\tcall(\"GET\", \"/missions/m3\", \"\", \"\")\n\t\t}\n\t\tsim.Run(0.2, nil)\n\t}\n\tcall(\"GET\", \"/missions/m3\", \"\", \"\")\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"The backend, exercised through httptest","walkthrough":"The retry with key k-101 and the same body returns the same 201 response with id m1, and the next mission is m2, so no second mission was created; the same key with another body gets 422, a POST without a key 400, a target 400 m away 422, GET /missions/m9 404, all as problem documents. DELETE is answered by the mux itself: 405 with Allow: GET, HEAD and its plain-text body. At 0.0 s m1 goes to alpha and m2 to bravo, both flying at 0.2 s; m3 stays queued, and the GET at 20 s says so. When m1 lands at 43.0 s, 0.2 m from home with 90 percent, the same pass hands m3 to alpha, which takes off at 43.2 s. The GET at 60 s shows m3 outbound at (61.8, 9.4, 20) with 86 percent. Its target (130, 20) lies inside the 150 m service area but beyond the 100 m radio range: at 69.8 s the autopilot's note 'link lost for 5 s: return to home' fails the mission, and the last GET shows state failed with that reason while alpha lands at home with 75 percent."},{"body":"The recorder keeps handlers honest about status codes, headers and bodies, which is most of what an API test needs; table-driven tests can send hundreds of requests per second this way. httptest.NewServer adds a real listener on the loopback interface when a test must exercise an HTTP client, timeouts or TLS, and that needs sockets. In production the dispatcher becomes its own goroutine on a ticker with a context for shutdown, the store moves to a database whose transactions take over the mutex's job, and clients retry with backoff and jitter, reusing the key. The failure of m3 shows the last point: validate missions against everything that can make them unflyable, such as radio range, battery, geofences and other operations, before accepting them, or the API promises flights the fleet cannot fly.","title":"From recorder to production"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Nothing listens on a port, so the program runs unchanged in the app's sandbox. The console shows every request and transition; Output replays both drones, with the dashed circle of the radio range and alpha turning back from m3 at its edge. Add a check in create that rejects targets beyond 100 m with 422 and run it again: m3 is refused at the API instead of failing in the air.","title":"Fly it in GopherForge"}],"takeaway":"Route with Go 1.22 method and wildcard patterns, make POST safe to retry by storing the Idempotency-Key with the first response in the same atomic step that creates the mission, and drive missions through an explicit state machine in which any autopilot failsafe fails the mission. Test handlers through httptest recorders, and validate missions against what the fleet can actually fly.","title":"A fleet backend in Go: a mission API, idempotent POST and a dispatch state machine","unitID":"drones-operations","wrongAnswers":["A new mission, since the first response was lost","409 Conflict, because that key was already used"]},{"conceptTag":"drones.property-testing","designGuide":{"cautions":["A generator that never makes the hard cases proves nothing.","Properties hold only inside an envelope you must write down."],"cost":"A seeded generator, a property checker, a greedy shrinker and CI time for a few hundred simulated flights per commit.","family":"drones","flow":["Generate worlds from seeds","Check properties per run","Shrink the failing seed","Keep it as a regression"],"ratings":[],"strengths":["Finds combinations nobody would write into a table.","A shrunk counterexample points straight at the cause."]},"hint":"Shrinking searches for the smallest world that still shows the bug. Which result of a re-flight tells you that a simplification removed nothing that mattered?","id":"drones.property-testing","introduction":"The simulation-testing lesson checked a table of hand-picked worlds, and a table holds only the cases someone thought of. Property-based testing turns the question around: state what must be true in every world, let a generator produce hundreds of worlds nobody would have written down, and when one breaks a property, shrink it until only the cause is left. Flight software suits it, because its invariants are short and its failures hide in combinations of geometry and weather.","nuance":"Keep a change only if the same property still fails; a different failure is a different bug. Whatever survives, here one leg, one obstacle and a gust, points at the cause.","objective":"Generate scenarios from seeds, state invariants that must hold in every world, find a failing seed for a deliberately weak obstacle planner, shrink it to a minimal counterexample, verify the fixed planner across every seed, and express the same property as a Go fuzz target.","question":"A property test found a failing seed with three waypoints, wind and gusts. How does shrinking decide which simplifications to keep?","references":["https://go.dev/doc/security/fuzz/","https://pkg.go.dev/testing#F.Fuzz","https://en.wikipedia.org/wiki/QuickCheck","https://pkg.go.dev/math/rand/v2#PCG"],"reviewAnswer":"Only changes after which the same property still fails","reviewPrompt":"What does shrinking keep?","sections":[{"body":"A property is a statement about every run, not the expected result of one. The program checks four. Fence: never more than 2 m outside the geofence. Obstacles: never closer to a wall than 0.3 m, the distance at which the simulator counts a touch. Reserve: always end on the ground, not crashed, with at least 10 percent charge. Explained: the mission completes, or the timeline holds a note with a reason, from an autopilot failsafe or from the mission's own decision. None of them says how far the drone gets or how long it takes, so tuning does not break them, and the last one turns 'the mission quietly gave up' into a failure. The idea comes from QuickCheck, a Haskell library from 2000; Go's testing/quick package is frozen, and today Go's built-in fuzzing serves the same purpose, as the last code section shows.","title":"Properties, not expected outputs"},{"body":"Generate builds a whole scenario from one seed with a math/rand/v2 PCG source: wind up to 8 m/s from any direction, gusts up to 3 m/s, 30 to 100 percent charge, a square fence whose sides lie 50 to 90 m from home, two to five waypoints and up to three obstacles of 2 to 6 m radius. Two choices matter more than the ranges. The generator aims at trouble: each obstacle stands a few metres to either side of a random leg, because obstacles placed uniformly would rarely be near a route and almost every world would be easy. And it states the envelope: no obstacle within its radius plus 8 m of home or a waypoint, nothing outside the wind range. Properties are promised only inside the envelope, so write it down; a failure outside it is a new requirement, not a bug. Keep the seed in every report: it reproduces the whole world, and the simulator is seeded from it too.","title":"Generators: a seed is a world"},{"body":"Plan routes a leg around every obstacle tall enough to hit, keeping clear metres from its wall: it steps sideways from the obstacle's centre, checks that both new legs are clear, recurses for other obstacles and backtracks when a detour lands next to another one. Fly flies the mission with that planner and turns home along the planned path below 30 percent charge, before the autopilot's 20 percent return home flies a straight line through whatever stands in the way. The weak planner keeps 0.3 m, only the airframe; the fixed one keeps 3 m. main runs the weak one over 300 seeds, shrinks the first failure, then runs the fixed one over the same 300 and flies the minimal world with both.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"maps\"\n\t\"math\"\n\t\"math/rand/v2\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst cruise = 15.0 // m\n\n// Scenario is one generated world and mission.\ntype Scenario struct {\n\tSeed      uint64\n\tWind      drone.Vec3\n\tGust      float64\n\tBattery   float64\n\tFence     float64 // half side of a square fence around home, m\n\tWaypoints []drone.Vec3\n\tObstacles []drone.Obstacle\n}\n\nfunc (sc Scenario) String() string {\n\treturn fmt.Sprintf(\"wind %v gust %.1f, battery %.0f%%, fence ±%.0f m, waypoints %d, obstacles %d\",\n\t\tsc.Wind, sc.Gust, sc.Battery, sc.Fence, len(sc.Waypoints), len(sc.Obstacles))\n}\n\n// Generate builds a scenario from a seed: the same seed, the same world.\n// Obstacles stand a few metres to either side of a random leg.\nfunc Generate(seed uint64) Scenario {\n\tr := rand.New(rand.NewPCG(seed, 7))\n\tu := func(lo, hi float64) float64 { return lo + (hi-lo)*r.Float64() }\n\tw, dir := u(0, 8), u(0, 2*math.Pi)\n\tsc := Scenario{Seed: seed, Wind: drone.Vec3{X: w * math.Cos(dir), Y: w * math.Sin(dir)}, Gust: u(0, 3), Battery: u(30, 100), Fence: u(50, 90)}\n\tfor range 2 + r.IntN(4) {\n\t\tm := sc.Fence - 20\n\t\tsc.Waypoints = append(sc.Waypoints, drone.Vec3{X: u(-m, m), Y: u(-m, m), Z: cruise})\n\t}\n\troute := append([]drone.Vec3{{Z: cruise}}, sc.Waypoints...)\n\tfor range 1 + r.IntN(3) {\n\t\ti := r.IntN(len(route) - 1)\n\t\ta, b := route[i], route[i+1]\n\t\to := drone.Obstacle{Name: fmt.Sprintf(\"obstacle %d\", len(sc.Obstacles)+1), Radius: u(2, 6), Height: u(10, 40)}\n\t\tside := drone.Vec3{X: a.Y - b.Y, Y: b.X - a.X}\n\t\tc := a.Add(b.Sub(a).Scale(u(0.25, 0.75))).Add(side.Scale(u(-1, 1) * (o.Radius + 4) / side.Len()))\n\t\to.X, o.Y = c.X, c.Y\n\t\tif !slices.ContainsFunc(route, func(q drone.Vec3) bool { return q.Sub(c).Horizontal().Len() < o.Radius+8 }) {\n\t\t\tsc.Obstacles = append(sc.Obstacles, o)\n\t\t}\n\t}\n\treturn sc\n}\n\n// pointSeg is the horizontal distance from p to the segment ab.\nfunc pointSeg(p, a, b drone.Vec3) float64 {\n\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\tt := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/max(ab.X*ab.X+ab.Y*ab.Y, 1e-9)))\n\treturn ap.Sub(ab.Scale(t)).Len()\n}\n\n// Plan returns waypoints from a to b (b included) that keep clear metres\n// from every obstacle tall enough to hit, or false when it finds none.\nfunc Plan(a, b drone.Vec3, obs []drone.Obstacle, clear float64, depth int) ([]drone.Vec3, bool) {\n\tab := b.Sub(a).Horizontal()\n\tfor _, o := range obs {\n\t\tc, need := drone.Vec3{X: o.X, Y: o.Y, Z: a.Z}, o.Radius+clear\n\t\tif o.Height < a.Z-1 || pointSeg(c, a, b) >= need {\n\t\t\tcontinue\n\t\t}\n\t\tif depth == 0 {\n\t\t\treturn nil, false\n\t\t}\n\t\tn := drone.Vec3{X: -ab.Y, Y: ab.X}.Scale(1 / ab.Len()) // sideways, the leg's side first\n\t\tif ab.X*(c.Y-a.Y)-ab.Y*(c.X-a.X) > 0 {\n\t\t\tn = n.Scale(-1)\n\t\t}\n\t\tfor _, l := range []float64{1.2, 1.5, 2, 2.5} {\n\t\t\tfor _, d := range []drone.Vec3{c.Add(n.Scale(l * need)), c.Add(n.Scale(-l * need))} {\n\t\t\t\tp1, ok1 := Plan(a, d, obs, clear, depth-1)\n\t\t\t\tif p2, ok2 := Plan(d, b, obs, clear, depth-1); ok1 && ok2 {\n\t\t\t\t\treturn append(p1, p2...), true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil, false\n\t}\n\treturn []drone.Vec3{b}, true\n}\n\n// Result is what one flight measured.\ntype Result struct {\n\tReached            int     // mission waypoints reached\n\tOutside            float64 // furthest outside the fence, m\n\tClearance, Planned float64 // closest to an obstacle's surface: flown, planned\n\tBattery            float64 // at the end, %\n\tLanded             bool\n\tNotes              []drone.Event // the timeline\n}\n\n// Fly runs the mission with a planner that keeps clear metres from obstacles,\n// and turns home on its planned path below 30% before any failsafe does.\nfunc Fly(sc Scenario, clear float64) (*drone.Sim, Result) {\n\tf := sc.Fence\n\tsim := drone.New(drone.Config{Wind: sc.Wind, Gust: sc.Gust, Battery: sc.Battery, MaxSpeed: 8, Seed: int64(sc.Seed),\n\t\tGeofence: []drone.Vec3{{X: -f, Y: -f}, {X: f, Y: -f}, {X: f, Y: f}, {X: -f, Y: f}}, Obstacles: sc.Obstacles})\n\td, r := sim.Drone(), Result{Clearance: math.Inf(1), Planned: math.Inf(1)}\n\trun := func(limit float64, done func() bool) {\n\t\tsim.RunUntil(limit, func(float64) bool {\n\t\t\tp := d.State().Pos\n\t\t\tr.Outside = max(r.Outside, math.Abs(p.X)-f, math.Abs(p.Y)-f)\n\t\t\tfor _, o := range sc.Obstacles {\n\t\t\t\tif p.Z < o.Height {\n\t\t\t\t\tr.Clearance = min(r.Clearance, math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn done()\n\t\t})\n\t}\n\td.Arm()\n\td.TakeOff(cruise)\n\trun(30, d.Arrived)\n\there, goals := drone.Vec3{Z: cruise}, append(slices.Clone(sc.Waypoints), drone.Vec3{Z: cruise})\n\tfor i := 0; i < len(goals) && d.State().Mode == drone.Hold; i++ {\n\t\tif i < len(sc.Waypoints) && d.State().Battery < 30 {\n\t\t\tsim.Mark(\"battery under 30%: home on the planned path\")\n\t\t\ti = len(sc.Waypoints)\n\t\t}\n\t\tpath, ok := Plan(here, goals[i], sc.Obstacles, clear, 3)\n\t\tif !ok {\n\t\t\tsim.Mark(fmt.Sprintf(\"no safe path to goal %d: landing here\", i+1))\n\t\t\tbreak\n\t\t}\n\t\tfor _, p := range path {\n\t\t\tfor _, o := range sc.Obstacles {\n\t\t\t\tr.Planned = min(r.Planned, pointSeg(drone.Vec3{X: o.X, Y: o.Y}, here, p)-o.Radius)\n\t\t\t}\n\t\t\tif here = p; d.State().Mode == drone.Hold { // else a failsafe flies it: never override\n\t\t\t\td.GoTo(p)\n\t\t\t\trun(90, func() bool { return d.State().Mode != drone.GoingTo })\n\t\t\t}\n\t\t}\n\t\tif d.State().Mode == drone.Hold && i < len(sc.Waypoints) {\n\t\t\tr.Reached++\n\t\t}\n\t}\n\tif d.State().Mode == drone.Hold {\n\t\td.Land()\n\t}\n\trun(300, func() bool { return d.State().Landed || d.State().Mode == drone.Crashed })\n\tr.Battery, r.Landed, r.Notes = d.State().Battery, d.State().Landed, sim.Events()\n\treturn sim, r\n}\n\n// Check returns the properties a flight broke: they must hold in every world.\nfunc Check(sc Scenario, r Result) []string {\n\tvar bad []string\n\tif r.Outside > 2 {\n\t\tbad = append(bad, fmt.Sprintf(\"fence: %.1f m outside\", r.Outside))\n\t}\n\tif r.Clearance < 0.3 {\n\t\tbad = append(bad, fmt.Sprintf(\"obstacle: touched, %.3f m from its surface\", r.Clearance))\n\t}\n\tif !r.Landed || r.Battery < 10 {\n\t\tbad = append(bad, fmt.Sprintf(\"reserve: landed %v with %.1f%%\", r.Landed, r.Battery))\n\t}\n\tif r.Reached < len(sc.Waypoints) && !slices.ContainsFunc(r.Notes, func(e drone.Event) bool { return strings.Contains(e.Text, \": \") }) {\n\t\tbad = append(bad, fmt.Sprintf(\"explained: stopped at %d of %d with no reason\", r.Reached, len(sc.Waypoints)))\n\t}\n\treturn bad\n}\n\n// Shrink simplifies a failing scenario one change at a time and keeps a\n// change only while the same property still fails.\nfunc Shrink(sc Scenario, clear float64, property string) Scenario {\n\tfor changed := true; changed; {\n\t\tvar whats []string\n\t\tvar tries []Scenario\n\t\tfor i := range sc.Waypoints {\n\t\t\tc := sc\n\t\t\tc.Waypoints = slices.Delete(slices.Clone(sc.Waypoints), i, i+1)\n\t\t\twhats, tries = append(whats, fmt.Sprint(\"drop waypoint \", sc.Waypoints[i])), append(tries, c)\n\t\t}\n\t\tfor i := range sc.Obstacles {\n\t\t\tc := sc\n\t\t\tc.Obstacles = slices.Delete(slices.Clone(sc.Obstacles), i, i+1)\n\t\t\twhats, tries = append(whats, \"drop \"+sc.Obstacles[i].Name), append(tries, c)\n\t\t}\n\t\tcalm, half, still, easy := sc, sc, sc, sc\n\t\tcalm.Wind, half.Wind, still.Gust, easy.Battery, easy.Fence = drone.Vec3{}, sc.Wind.Scale(0.5), 0, 100, 100\n\t\twhats = append(whats, \"no wind\", \"half the wind\", \"no gust\", \"full battery, fence ±100 m\")\n\t\ttries = append(tries, calm, half, still, easy)\n\t\tchanged = false\n\t\tfor k, c := range tries {\n\t\t\tif c.String() == sc.String() { // nothing left to simplify here\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, r := Fly(c, clear); slices.ContainsFunc(Check(c, r), func(b string) bool { return strings.HasPrefix(b, property) }) {\n\t\t\t\tfmt.Printf(\"  %-36s still fails\\n\", whats[k])\n\t\t\t\tsc, changed = c, true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn sc\n}\n\nfunc second(_ *drone.Sim, r Result) Result { return r }\n\nfunc main() {\n\tconst seeds = 300\n\tconst weak, fixed = 0.3, 3.0 // metres each planner keeps from an obstacle's surface\n\tfirst, failing := Scenario{}, 0\n\tfor seed := uint64(1); seed <= seeds; seed++ {\n\t\tif sc := Generate(seed); len(Check(sc, second(Fly(sc, weak)))) > 0 {\n\t\t\tif failing++; failing == 1 {\n\t\t\t\tfirst = sc\n\t\t\t\tfmt.Printf(\"weak planner (%.1f m), seed %d: %v\\n  %s\\n\", weak, seed, sc, strings.Join(Check(sc, second(Fly(sc, weak))), \"; \"))\n\t\t\t}\n\t\t}\n\t}\n\tsmall := Generate(1)\n\tif failing == 0 {\n\t\tfmt.Printf(\"weak planner passes all %d seeds\\n\", seeds)\n\t} else {\n\t\tfmt.Printf(\"weak planner fails %d of %d seeds; shrinking seed %d:\\n\", failing, seeds, first.Seed)\n\t\tsmall = Shrink(first, weak, \"obstacle\")\n\t\tr := second(Fly(small, weak))\n\t\tfmt.Printf(\"minimal: %v\\n  waypoints %v\\n\", small, small.Waypoints)\n\t\tfor _, o := range small.Obstacles {\n\t\t\tfmt.Printf(\"  %s at (%.1f, %.1f), radius %.1f m, %.0f m tall\\n\", o.Name, o.X, o.Y, o.Radius, o.Height)\n\t\t}\n\t\tfmt.Printf(\"  planned to pass %.2f m from it; %s\\n\", r.Planned, strings.Join(Check(small, r), \"; \"))\n\t}\n\n\tpassed, worst, low, stopped := 0, math.Inf(1), 100.0, map[string]int{}\n\tfor seed := uint64(1); seed <= seeds; seed++ {\n\t\tsc := Generate(seed)\n\t\tr := second(Fly(sc, fixed))\n\t\tif len(Check(sc, r)) == 0 {\n\t\t\tpassed++\n\t\t}\n\t\tworst, low = min(worst, r.Clearance), min(low, r.Battery)\n\t\tfor _, e := range r.Notes {\n\t\t\tif k := strings.Index(e.Text, \": \"); k > 0 && r.Reached < len(sc.Waypoints) {\n\t\t\t\tstopped[e.Text[:k]]++\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"fixed planner (%.0f m): %d of %d seeds pass; closest %.2f m to a surface, lowest landing charge %.1f%%\\n\", fixed, passed, seeds, worst, low)\n\tfor _, k := range slices.Sorted(maps.Keys(stopped)) {\n\t\tfmt.Printf(\"  stopped early, with a reason: %d x %q\\n\", stopped[k], k)\n\t}\n\tweakSim, _ := Fly(small, weak)\n\tfixedSim, _ := Fly(small, fixed)\n\tif err := weakSim.SaveAs(\"weak\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := fixedSim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Find, shrink, fix","walkthrough":"The first failure is seed 33: one obstacle, three waypoints, wind (3.8, -4.5) and gusts of 2.6 m/s. The drone comes 0.250 m from the wall, which counts as a touch, and the crash breaks two more properties: no landing, and a mission that stopped with no reason. The weak planner fails 8 of the 300 seeds. Shrinking drops two waypoints, the wind, and sets a full battery and a 100 m fence, and each world still fails; 'no gust' never appears, because without the gust the drone no longer touches the wall. The minimal world has one waypoint at (-28.2, 14.8), one 3.9 m obstacle at (-15.6, 3.4) and a 2.6 m/s gust: the plan passes 0.35 m from the wall and the gust pushes the drone to 0.296 m. The fixed planner passes all 300 seeds; no drone came closer than 2.53 m to a wall, the lowest landing charge was 20.1 percent, and 29 missions stopped early, every one with the note 'battery under 30%'. weak.gfflight ends in the crash after 8.9 s; flight.gfflight flies the same world around the obstacle and lands with 92 percent."},{"body":"Shrinking is greedy: try one simplification at a time (drop a waypoint, drop an obstacle, calm the wind, stop the gusts, fill the battery), keep it only if the same property still fails, and repeat until nothing more can be removed. Checking the same property matters, because a simpler world that fails differently is a different bug. What survives is the diagnosis. Here the steady wind went and the gust stayed: the simulator's velocity loop learns to cancel steady wind, while gusts push the drone off its line before the loop catches up, so the margin must cover the airframe, the 1 m within which the autopilot counts a waypoint as reached and starts the next leg from wherever it is, and the tracking error in gusts. That is the 3 m budget; the fixed planner's closest pass, 2.53 m, shows that the flights used at most 0.47 m of it. The generator found two more bugs while this lesson was written: a detour point placed beside a second obstacle, and a low-battery return home flown straight through an obstacle. The planner's backtracking and the 30 percent turn-back are their fixes. Keep every shrunk counterexample as a regression case.","title":"What the minimal case says"},{"body":"A lesson program is package main, but in a repository the same Fly and Check sit in a test. A fuzz target receives raw parameters rather than a seed: Go's fuzzer mutates the bytes of its inputs, guided by code coverage, and minimizes any failing input. Fed a single seed, every mutation would be an unrelated world and minimization would only find a smaller number; fed the wind, the gust and the geometry, small mutations make small changes and minimization shrinks the values themselves. Fuzz arguments may only be strings, byte slices, integers, floats and bools, so the target assembles the scenario itself and must reject NaN and infinities, which the fuzzer will try.","code":"func FuzzMissionProperties(f *testing.F) {\n\tf.Add(0.0, 0.0, 2.6, -28.2, 14.8, -15.6, 3.4, 3.9) // the shrunk counterexample\n\tf.Fuzz(func(t *testing.T, windX, windY, gust, wx, wy, ox, oy, radius float64) {\n\t\tfor _, v := range []float64{windX, windY, gust, wx, wy, ox, oy, radius} {\n\t\t\tif math.IsNaN(v) || math.IsInf(v, 0) {\n\t\t\t\tt.Skip()\n\t\t\t}\n\t\t}\n\t\tsc := Scenario{Seed: 1, Wind: drone.Vec3{X: windX, Y: windY}, Gust: gust, Battery: 100, Fence: 100,\n\t\t\tWaypoints: []drone.Vec3{{X: wx, Y: wy, Z: cruise}},\n\t\t\tObstacles: []drone.Obstacle{{Name: \"obstacle\", X: ox, Y: oy, Radius: radius, Height: 30}}}\n\t\tif !InEnvelope(sc) {\n\t\t\tt.Skip() // the properties are promised only inside the envelope\n\t\t}\n\t\tif _, r := Fly(sc, 3); len(Check(sc, r)) > 0 {\n\t\t\tt.Errorf(\"%v: %v\", sc, Check(sc, r))\n\t\t}\n\t})\n}","language":"go","title":"The same property as a fuzz target","walkthrough":"f.Add puts the shrunk counterexample into the seed corpus, so plain go test runs it on every commit like a unit test. go test -fuzz=FuzzMissionProperties then mutates the eight floats; InEnvelope, which you write, rejects winds above 8 m/s, radii outside 2 to 6 m and obstacles within reach of home or the waypoint, exactly as Generate does. A failing input is minimized and written under testdata/fuzz/FuzzMissionProperties, where go test runs it from then on. Fuzz on AMD64 or ARM64, where coverage instrumentation is available."},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. It flies more than 600 short missions, so give it a moment on an older phone, or lower seeds to 100. Output lists two recordings of the minimal world: weak.gfflight clips the grey obstacle and falls, flight.gfflight detours around it and lands at home. Change weak to 1.0 m: it passes all 300 seeds here. Decide whether 300 worlds are enough evidence to fly a margin that small.","title":"Fly it in GopherForge"}],"takeaway":"State properties that must hold in every world, generate worlds from seeds that aim at trouble inside a written envelope, and when a seed fails, shrink it one change at a time while the same property still fails; what survives names the cause. Fix it, rerun every seed, keep the counterexample as a regression case, and let a fuzz target over raw parameters keep searching.","title":"Property-based testing of flight software: generated worlds, shrinking and fuzz targets","unitID":"drones-operations","wrongAnswers":["Those after which the flight passes, to locate the fix","Every simplification, as long as the program still runs"]},{"conceptTag":"drones.incident-analysis","designGuide":{"cautions":["Telemetry freezes during an outage and looks like a hover.","One root cause hides the other factors that combined."],"cost":"Event and telemetry logging at known rates, a replayable simulator scenario per incident, and time for a blameless review.","family":"drones","flow":["Preserve logs and events","Rebuild the timeline","Measure contributing factors","Change one thing, re-fly"],"ratings":[],"strengths":["Separates what the operator saw from what happened.","Every action is verified by re-flying the same fault."]},"hint":"Without a fix the drone cannot hold its position. Compare 7 m with how far a 6 m/s wind carries it before the failsafe gets it down.","id":"drones.incident-analysis","introduction":"Sooner or later a flight ends in the wrong place: against a wall, in a field, in a tree. What happens next decides whether it happens again. An incident analysis rebuilds the timeline from the logs, measures the factors that combined, and ends with a change that has been tested, not with a name. This lesson works through a GPS outage beside a tower in the simulator, where the ground station showed a drone holding still while it drifted into the wall.","nuance":"Stand-off must be measured along the wind, against the drift budget of an outage: about 44 m to touchdown here. Inspecting from the lee side turns the same drift away from the structure.","objective":"Reconstruct an incident from the autopilot's event timeline and recorded telemetry, separate what the ground station saw from what happened, compute contributing factors such as time without a fix and drift against the planned stand-off, write a blameless summary, change one thing and re-fly the same fault to verify it.","question":"A drone holding 7 m upwind of a tower loses GPS in a 6 m/s wind and touches the wall 4.3 s later. Why was the 7 m stand-off not enough?","references":["https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/common-ekf-inav-failsafe.html","https://docs.px4.io/main/en/log/flight_log_analysis.html","https://www.faa.gov/faq/when-do-i-need-report-accident"],"reviewAnswer":"It was measured around the tower, not along the wind","reviewPrompt":"Why was the stand-off not enough?","sections":[{"body":"Three kinds of evidence survive a flight. The autopilot's event messages (STATUSTEXT over MAVLink, sim.Events() here) say what it decided and when. The telemetry the ground station received says what the operator could see, at its own rate and with its own gaps. The onboard log, an ArduPilot DataFlash log or a PX4 ULog, records sensors and estimator state at much higher rates and is the nearest thing to the truth, together with where the aircraft came down. Copy all of it before anyone powers the vehicle up or flies again, and put everything on one clock. Telemetry needs the most care: during a GPS outage the position it reports is the last fix, frozen, and to a ground station a drifting drone looks like one in a perfect hover. In the simulator the true position stands in for the onboard log and the wreck, so the program records both what was sent and what happened, five times a second.","title":"Evidence: timeline, telemetry and truth"},{"body":"An inspector drone climbs to 15 m and stops at two photo points 7 m west of a 30 m tower, with a 6 m/s wind blowing from the west towards it. At the second stop the receiver loses its fix for 20 s, as it can beside a tall structure that hides half of the sky. The analysis prints every event with the distance to the wall according to the telemetry and according to the truth, derives the contributing factors from the event times and the log, flies the same flight with the tower removed to see where the drift was heading, prints a summary, and re-flies the same outage after one change.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nvar (\n\ttower = drone.Obstacle{Name: \"tower\", Y: 40, Radius: 5, Height: 30}\n\twind  = drone.Vec3{X: 6} // from the west\n)\n\n// Row is one line of the flight log at 5 Hz: what the ground station\n// received, and the true position the simulator knows (on a real aircraft,\n// the onboard log and the wreck are the nearest thing to it).\ntype Row struct {\n\tT          float64\n\tGPS, Truth drone.Vec3\n}\n\n// surface is the horizontal distance from p to the tower's wall.\nfunc surface(p drone.Vec3) float64 { return math.Hypot(p.X-tower.X, p.Y-tower.Y) - tower.Radius }\n\n// Fly inspects a face of the tower from x = side at 15 m, with photo stops\n// at two points. At the second the receiver loses its fix for 20 s, as it\n// can next to a tall structure that hides half of the sky.\nfunc Fly(side float64, obstacles []drone.Obstacle) (*drone.Sim, []Row) {\n\tsim := drone.New(drone.Config{Wind: wind, Gust: 1.5, MaxSpeed: 4, Seed: 5, Obstacles: obstacles})\n\tsim.Drone().Name = \"inspector\"\n\td, rows := sim.Drone(), []Row{}\n\trun := func(limit float64, done func() bool) {\n\t\tsim.RunUntil(limit, func(float64) bool {\n\t\t\tif tel := d.Telemetry(); len(rows) == 0 || tel.Time > rows[len(rows)-1].T {\n\t\t\t\trows = append(rows, Row{tel.Time, tel.GPS, d.State().Pos})\n\t\t\t}\n\t\t\treturn done()\n\t\t})\n\t}\n\td.Arm()\n\td.TakeOff(15)\n\trun(30, d.Arrived)\n\tfor i, y := range []float64{30, 40} {\n\t\td.GoTo(drone.Vec3{X: side, Y: y, Z: 15})\n\t\trun(60, func() bool { return d.State().Mode != drone.GoingTo })\n\t\tif i == 1 {\n\t\t\td.LoseGPS(20)\n\t\t}\n\t\trun(4, func() bool { return d.State().Mode != drone.Hold }) // photos\n\t}\n\tif d.State().Mode == drone.Hold {\n\t\td.Land()\n\t}\n\trun(60, func() bool { return d.State().Landed || d.State().Mode == drone.Crashed })\n\treturn sim, rows\n}\n\n// at returns the first log row at or after time t.\nfunc at(rows []Row, t float64) Row {\n\tfor _, r := range rows {\n\t\tif r.T >= t-1e-9 {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn rows[len(rows)-1]\n}\n\n// event finds the first note on the timeline that starts with prefix.\nfunc event(sim *drone.Sim, prefix string) (float64, bool) {\n\tfor _, e := range sim.Events() {\n\t\tif strings.HasPrefix(e.Text, prefix) {\n\t\t\treturn e.T, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc main() {\n\tincident, rows := Fly(-12, []drone.Obstacle{tower})\n\tfmt.Println(\"timeline                                      to the wall: telemetry / truth, height\")\n\tfor _, e := range incident.Events() {\n\t\tr := at(rows, e.T)\n\t\tfmt.Printf(\"%6.1f s  %-37s %5.1f / %5.1f m  %4.1f m\\n\", e.T, e.Text, surface(r.GPS), surface(r.Truth), r.Truth.Z)\n\t}\n\n\tlost, _ := event(incident, \"GPS lost\")\n\tlanding, _ := event(incident, \"no GPS\")\n\thit, crashed := event(incident, \"hit\")\n\tif !crashed {\n\t\tfmt.Println(\"no contact: the drone landed in the open, so there is no incident to analyse\")\n\t\tif err := incident.Save(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\tend := incident.Drone().State()\n\tbefore, last := at(rows, lost), at(rows, incident.Time())\n\tstandoff := surface(drone.Vec3{X: -12, Y: 40}) // the photo point\n\ttoward := drone.Vec3{X: tower.X + 12, Y: tower.Y - 40}\n\t// The same flight with the tower removed shows where the drift was going.\n\t_, free := Fly(-12, nil)\n\tgone := free[len(free)-1]\n\tbudget := gone.Truth.Sub(before.Truth).Horizontal().Len()\n\n\tfmt.Println(\"contributing factors\")\n\tfmt.Printf(\"  stand-off planned: %.1f m from the wall, upwind of it; contact at 0.3 m\\n\", standoff)\n\tfmt.Printf(\"  wind towards the tower: %.1f m/s, gusts up to 1.5 m/s\\n\", (wind.X*toward.X+wind.Y*toward.Y)/toward.Len())\n\tfmt.Printf(\"  no fix for %.1f s at contact; the failsafe landing began at +%.1f s and was %.1f m up at contact\\n\", hit-lost, landing-lost, end.Pos.Z)\n\tfmt.Printf(\"  drift from the last fix: %.1f m; telemetry showed %.1f m of movement\\n\", end.Pos.Sub(before.Truth).Horizontal().Len(), last.GPS.Sub(before.GPS).Horizontal().Len())\n\tfmt.Printf(\"  without the tower: drift %.1f m in %.1f s, until touchdown\\n\", budget, gone.T-lost)\n\n\tfmt.Println(\"summary (blameless)\")\n\tfmt.Printf(\"  At %.1f s the GPS fix was lost while the drone held a photo point %.1f m upwind of the tower.\\n\", lost, surface(before.Truth))\n\tfmt.Printf(\"  Without a fix the autopilot keeps level, so it drifted with the 6 m/s wind; the no-GPS failsafe\\n\")\n\tfmt.Printf(\"  started a landing after 3 s, which does not stop drift. Contact came %.1f s after the loss at %.1f m up,\\n\", hit-lost, end.Pos.Z)\n\tfmt.Printf(\"  while the ground station still showed the last fix. The plan's %.1f m stand-off was measured\\n\", standoff)\n\tfmt.Printf(\"  around the tower, not along the wind; the drift budget for this outage is %.0f m.\\n\", budget)\n\tfmt.Println(\"change: inspect the lee face (x = 12), so the drift carries the drone away; same outage\")\n\tsim, again := Fly(12, []drone.Obstacle{tower})\n\tclosest := math.Inf(1)\n\tfor _, r := range again {\n\t\tclosest = min(closest, surface(r.Truth))\n\t}\n\tst := sim.Drone().State()\n\tfmt.Printf(\"re-flight: %s %.1f m from the wall, never closer than %.1f m to it\\n\", strings.ToLower(st.Mode.String()), surface(st.Pos), closest)\n\tif err := incident.SaveAs(\"incident\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Reconstruct the flight, then measure","walkthrough":"Until the outage telemetry and truth agree to within about a metre of GPS error: 7.4 m and 7.0 m from the wall at the second photo point. The fix goes at 23.5 s, and from then on the telemetry says 7.4 m on every line. At 26.5 s the failsafe note 'no GPS for 3 s: landing' arrives when the truth is already 3.3 m, and at 27.8 s 'hit tower' comes at 0.3 m, 12.7 m up. The factors: a 7.0 m stand-off on the upwind side; 6.0 m/s of wind towards the tower; contact 4.3 s after the loss, 1.3 s into a landing that descends but does not stop the drift; 7.0 m of drift while the telemetry showed 0.0 m of movement; and, without the tower, 43.6 m of drift in the 14.7 s to touchdown. The same outage on the lee face ends with a landing 50.5 m from the wall, never closer than 6.9 m. incident.gfflight ends at the wall; flight.gfflight is the re-flight."},{"body":"Incidents rarely have one cause; several ordinary conditions line up. Here a GPS outage is expected near tall structures, a 6 m/s wind is unremarkable, and the failsafe did what it is designed to do. Without a position the autopilot can only hold attitude, so the drone moves with the air. PX4 documents the same choice for multicopters: with no position estimate at all its failsafe falls back to Descend. ArduPilot's EKF failsafe switches to Land by default, which descends while letting a pilot steer. Neither stops the drift by itself. What made the outage dangerous was geometry: the 7 m stand-off was measured around the tower, while the drift went along the wind, and the drift budget of this outage was about 44 m. Each factor gets a measurement, a cause and an owner, because a single root cause invites a single fix and leaves the other holes open.","title":"Contributing factors, not a root cause"},{"body":"The summary describes what happened, the timeline, the impact, the contributing factors, what worked and the actions, each with an owner and a way to verify it. Blameless means it records decisions as they looked with the information available at the time and asks why the system allowed the outcome, not who erred; aviation calls the wider principle just culture, and it is what keeps people reporting near misses. The program's summary is written from its own measurements: when the fix was lost, why the drone drifted, why the failsafe did not stop it, what the ground station showed, and which planning assumption failed. Some events must also be reported to an authority. The FAA, for example, requires the remote pilot in command of a small drone to report within 10 days an accident causing serious injury, loss of consciousness, or damage to property other than the drone above 500 dollars to repair or replace. Check what applies where you fly.","title":"A blameless summary"},{"body":"Change one thing at a time, or you cannot tell which change helped. Here the change is the plan: inspect the lee face, so that any drift carries the drone away from the structure, with the same outage injected at the same point and the same seed. The re-flight drifts about as far and lands in the open. Then ask what the change costs and what it does not cover. A real lee face has turbulence the simulator does not model, the wind can veer during the flight, and the downwind drift footprint must be clear of people and other obstacles. Turn the incident into permanent checks: a planner rule that keeps obstacles out of the downwind drift budget, and a scenario in the property tests that injects GPS outages near obstacles. Only then close the incident.","title":"Change one thing, then re-fly the fault"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists two recordings: incident.gfflight shows the grey tower, the photo stops and the drift into the wall, and flight.gfflight shows the lee-face flight drifting away and landing in the open. Change LoseGPS(20) to LoseGPS(2): the fix returns before the failsafe, the drone holds again, and the program reports that there is nothing to analyse.","title":"Fly it in GopherForge"}],"takeaway":"Rebuild the timeline from event messages and logs on one clock, treat telemetry during an outage as stale, measure each contributing factor, and write a blameless summary whose actions are tests. Here the stand-off had to be measured along the wind against the drift budget of an outage; change one thing and re-fly the same fault before closing the incident.","title":"Post-flight incident analysis: timeline, contributing factors and a verified change","unitID":"drones-operations","wrongAnswers":["GPS error put the drone 7 m closer than shown","The failsafe climbed into the tower before landing"]}],"revision":"2026-12-03.1","schemaVersion":1,"solutions":{},"units":[{"id":"drones-foundations","lessons":[{"conceptTags":["drones.architecture"],"explanation":"A drone that flies itself is several computers that trust each other only so far. A microcontroller runs the flight controller firmware and keeps the aircraft upright hundreds of times a second; a Linux computer on board may run mission logic, cameras and networking; a ground control station shows the operator what is happening; and a backend may coordinate many vehicles. Go is a strong fit for the last three and a poor fit for the first, and the reasons explain most design choices in this course.","id":"drones.architecture","objective":"Place each piece of drone software on the right computer, explain why the inner control loops stay in real-time firmware, and fly a first simulated take-off, hold and landing from Go.","task":{"reading":{}},"title":"Drone software architecture: flight controller, companion computer, ground station and fleet backend"},{"conceptTags":["drones.mavlink-frames"],"explanation":"MAVLink is the protocol PX4, ArduPilot, QGroundControl and most drone tooling speak. It is deliberately small: a 10-byte header, a payload of fixed-size little-endian fields and a 2-byte checksum, designed for slow and lossy serial radios. Building a frame by hand once is the best way to understand what every library does for you, and why one wrong byte or a mismatched message definition makes frames silently disappear.","id":"drones.mavlink-frames","objective":"Encode and decode a MAVLink v2 HEARTBEAT in pure Go with encoding/binary, compute the CRC-16/MCRF4XX checksum seeded with CRC_EXTRA, and watch corruption and mismatched definitions get rejected.","task":{"reading":{}},"title":"MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing"},{"conceptTags":["drones.telemetry-streams"],"explanation":"A vehicle does not answer questions about its position; it streams messages at configured rates and the ground station keeps the latest value of each. That design is efficient on a narrow radio link, but it means the newest value you hold may be seconds old. A ground station that shows a position without knowing its age, or calls a link healthy because heartbeats still arrive, is behind many confusing incidents.","id":"drones.telemetry-streams","objective":"Decode a recorded MAVLink stream, measure per-message rates and gaps on the ground station's clock, interpret GLOBAL_POSITION_INT's scaled integers, and flag stale streams and a lost link.","task":{"reading":{}},"title":"Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection"},{"conceptTags":["drones.coordinates"],"explanation":"GPS reports latitude, longitude and altitude on the WGS84 ellipsoid; controllers work in metres in a local frame; MAVLink and the flight stacks use NED while ROS and this simulator use ENU. Every drone codebase converts between them, and a swapped axis, a wrong sign or a missing cos(latitude) produces a vehicle that flies confidently to the wrong place. The conversions are short; knowing their error budget is the real skill.","id":"drones.coordinates","objective":"Convert mission waypoints between WGS84 latitude and longitude and local metres, compute great-circle distance and bearing, and know where the flat-plane approximation and spherical formulas stop being good enough.","task":{"reading":{}},"title":"Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes"},{"conceptTags":["drones.ground-station"],"explanation":"A ground station is a small concurrent system: bytes arrive whenever the radio delivers them, heartbeats must go out on time whether or not anything arrives, operator commands interleave with both, and the link can vanish at any moment. Goroutines, channels, select and context map onto that shape directly. The hard parts are deciding who owns what and making sure every goroutine stops when the link or the program ends.","id":"drones.ground-station","objective":"Structure a MAVLink ground station with a reader goroutine, a periodic heartbeat, a channel of decoded frames, a select loop with a resettable link-loss timer and a context that shuts everything down cleanly.","task":{"reading":{}},"title":"A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts"},{"conceptTags":["drones.telemetry-noise"],"explanation":"Every number a drone reports is an estimate built from imperfect sensors. GPS wanders by metres, a barometer measures altitude changes finely but drifts with the weather, and an IMU measures motion hundreds of times a second but drifts when integrated. Simulation gives you what real flights never do, the truth, so you can measure exactly how wrong each sensor is and in which way.","id":"drones.telemetry-noise","objective":"Compare simulated telemetry with the true state over a flight, compute bias and RMSE per sensor, and explain why smoothing one sensor fails and sensor fusion is needed.","task":{"reading":{}},"title":"Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias"}],"summary":"Flight controller, companion computer and ground station, MAVLink v2 frames and checksums, telemetry rates and stale data, WGS84, ENU and NED, a Go ground station and sensor noise.","title":"Drone software: architecture, MAVLink and telemetry","translationNote":"Programs fly gopherforge.app/drone, a deterministic simulator bundled with GopherForge, and Output replays each saved flight. Real vehicles speak MAVLink to PX4 or ArduPilot; test against their simulators before any hardware."},{"id":"drones-control","lessons":[{"conceptTags":["drones.pid-altitude"],"explanation":"SetThrust hands the program the collective thrust: about 0.5 hovers, more climbs, less sinks, and nothing else holds the altitude. Thrust sets vertical acceleration while you care about position, so the plant is a double integrator with a little drag, the simplest plant on which a naive controller rings. This lesson builds the PID found in every flight stack's inner loops, flies four variants of it through the same 10 m step on identical simulators, and measures what each term buys.","id":"drones.pid-altitude","objective":"Close an altitude loop through SetThrust with a PID controller that takes its derivative from the measurement, clamps its integral and saturates its output, and judge each variant by rise time, overshoot, settling time and steady-state error.","task":{"reading":{}},"title":"PID altitude control: P, I and D on the collective thrust"},{"conceptTags":["drones.cascaded-control"],"explanation":"No flight stack controls position with one big loop. PX4 and ArduPilot nest them: position error becomes a velocity setpoint, velocity error an acceleration and tilt, attitude error a body rate, rate error a torque for the mixer. Each loop only has to control something that already responds quickly, because the loop inside it made it so. A companion computer running Go usually sits at the top of this cascade and sends position or velocity setpoints; this lesson writes that outer loop, holds a point in a 4 m/s wind and then follows a target that moves into the wind.","id":"drones.cascaded-control","objective":"Build an outer position loop that sends velocity setpoints through SetVelocity, explain why inner loops must be faster and where the integrator belongs, and compare P, PI and velocity feedforward when holding a point in wind and following a moving target.","task":{"reading":{}},"title":"Cascaded control: a position loop on top of a velocity loop"},{"conceptTags":["drones.complementary-filter"],"explanation":"Sensors on a drone are either fast and smooth but drifting, or absolute but noisy and slow. Integrating an inertial vertical velocity gives a clean altitude that walks away over time; the barometer never walks away but jumps by tens of centimetres from sample to sample. A complementary filter takes the high frequencies from the first and the low frequencies from the second, with one parameter, the crossover time constant. It costs a few multiplications per step and is the right first estimator to write before a Kalman filter.","id":"drones.complementary-filter","objective":"Estimate altitude by integrating a biased vertical velocity at 50 Hz and correcting it with the 5 Hz barometer, choose the time constant tau and alpha = tau / (tau + dt), and measure the result as RMSE against the true altitude.","task":{"reading":{}},"title":"Complementary filter: fusing a fast drifting signal with a slow noisy one"},{"conceptTags":["drones.kalman-filter"],"explanation":"A complementary filter has a fixed blend. A Kalman filter computes the blend at every step from its own uncertainty: right after start-up it trusts the measurements almost completely, once it has converged it leans on its model, and it weighs a 1.2 m GPS altitude against a 0.3 m barometer by their variances. It also estimates states it does not measure, such as the climb rate from altitude samples alone, fuses a direct measurement of them when one exists, and says how surprising each sample is, which is the basis for rejecting glitches. PX4's EKF2 and ArduPilot's EKF3 run the same predict-update cycle with many more states.","id":"drones.kalman-filter","objective":"Write a 1-D constant-velocity Kalman filter that fuses GPS altitude, barometer and a climb-rate measurement, follow its state, covariance, predict and update steps, tune process and measurement noise, and reject outliers with an innovation gate that cannot lock out the truth.","task":{"reading":{}},"title":"A Kalman filter for altitude and climb rate"},{"conceptTags":["drones.loop-timing"],"explanation":"A control loop assumes its dt. When an iteration starts late, the integral and derivative terms are computed with the wrong time step, and a burst of catch-up iterations is worse than a skipped one. Go is a good language for the 10 to 50 Hz supervisory loops of a companion computer or ground station and the wrong one for the kilohertz rate loop inside a flight controller. This lesson runs three loop styles on a virtual clock, so the results are the same on every run, then counts the heap allocations of two versions of a loop body.","id":"drones.loop-timing","objective":"Run a supervisory control loop at a fixed rate with time.Ticker, understand dropped ticks, jitter and the monotonic clock, keep allocations out of the loop body and prove it with testing.AllocsPerRun, and decide what belongs in firmware instead.","task":{"reading":{}},"title":"Fixed-rate loops in Go: tickers, jitter, GC and allocations"},{"conceptTags":["drones.motor-mixing"],"explanation":"Below the rate controller sits the mixer, which PX4 calls control allocation. It knows where each rotor is and which way it spins, and turns four numbers, thrust and three torques, into four motor commands. That is a matrix multiplication until a motor reaches 0 or 1. Then something has to give, and what gives decides whether the vehicle keeps its attitude or rolls over. This lesson writes the mixer, the naive clip and a desaturation with explicit priorities.","id":"drones.motor-mixing","objective":"Map collective thrust and roll, pitch and yaw torque commands to four motor outputs with PX4's Quadrotor X numbering and spin directions, and handle saturation by giving up thrust and yaw before roll and pitch.","task":{"reading":{}},"title":"Motor mixing for a quad X: thrust and torques to four motors"},{"conceptTags":["drones.flight-modes"],"explanation":"Ground stations and companion computers tend to grow their flight-mode logic one if statement at a time, until nobody can say whether a go-to is allowed while the vehicle returns home. Writing it as a table of transitions with guards makes every allowed path visible, every refusal explainable and the whole logic testable without a vehicle. The autopilot keeps its own modes and checks; this machine decides what your program will ask of it.","id":"drones.flight-modes","objective":"Model flight modes as states, events and guarded transitions in a table, reject invalid requests with reasons, run pre-arm checks for battery, GPS fix and geofence, map the states onto the simulator's modes and log every transition.","task":{"reading":{}},"title":"Flight modes as an explicit state machine"}],"summary":"PID altitude control and anti-windup, cascaded position and velocity loops, complementary and Kalman filters, fixed-rate loops in Go, quad X motor mixing and flight modes as a state machine.","title":"Flight control: PID, cascades, filters and loops","translationNote":"Control code runs against the simulator's physics: tilt-limited thrust, drag on airspeed, wind and gusts and a battery. Gains that work here are a starting point, not a tune for a real airframe."},{"id":"drones-missions","lessons":[{"conceptTags":["drones.waypoint-missions"],"explanation":"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.","id":"drones.waypoint-missions","objective":"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.","task":{"reading":{}},"title":"Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern"},{"conceptTags":["drones.geofencing"],"explanation":"A geofence stands between a software bug, a gust or a confused operator and an airspace infringement. Most flight stacks act only once the vehicle is already outside, and a multicopter at 8 m/s needs several metres to stop, so where the fence acts matters as much as where it is drawn. The geometry is short; the edge cases and the physics are where fences fail.","id":"drones.geofencing","objective":"Implement point-in-polygon with an explicit boundary rule, combine inclusion zones, exclusion zones and a ceiling, predict the time to the boundary from velocity, and compare a reactive fence with a predictive guard in the simulator.","task":{"reading":{}},"title":"Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach"},{"conceptTags":["drones.failsafes"],"explanation":"Failsafes are the code paths that run when something has already gone wrong: the battery is low, the link is gone, the position estimate is bad, the vehicle left its fence. Normal flights rarely exercise them, which is exactly why they hide bugs. A fixed rule such as 'at 20 percent, return home' is a good last resort and a poor plan, because whether 20 percent is enough depends on how far away home is and which way the wind blows.","id":"drones.failsafes","objective":"Explain state of charge and voltage sag, estimate the charge needed to fly home against the wind with a reserve, compare that budget with fixed battery thresholds in the simulator, and design link-loss timeouts and failsafe priorities.","task":{"reading":{}},"title":"Failsafes: battery energy budgets, link-loss timeouts and which action wins"},{"conceptTags":["drones.path-planning"],"explanation":"A straight line from take-off to destination is the shortest path until something is in the way: a stay-out zone, a building, a temporary restriction published in the middle of a mission. Planning turns a map of allowed space into waypoints the autopilot can fly. The classic pipeline is a grid, an A* search, smoothing, and a replan whenever the map changes; each stage has a property to protect: the safety margin, optimality and flyability.","id":"drones.path-planning","objective":"Rasterize no-fly zones into an inflated grid, find the shortest path with A* and the admissible octile heuristic, prune it to a few waypoints by line of sight, fly it in the simulator and replan when a new restriction appears.","task":{"reading":{}},"title":"Path planning around no-fly zones: A*, line-of-sight pruning and replanning"},{"conceptTags":["drones.fleets"],"explanation":"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.","id":"drones.fleets","objective":"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.","task":{"reading":{}},"title":"Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation"},{"conceptTags":["drones.simulation-testing"],"explanation":"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.","id":"drones.simulation-testing","objective":"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.","task":{"reading":{}},"title":"Testing drone software: seeded scenarios, invariants, SITL, HIL and CI"}],"summary":"Waypoint missions and the MAVLink mission protocol, geofences, failsafes and energy budgets, A* around no-fly zones, fleets with goroutines, and seeded scenario tests.","title":"Missions, safety and fleets","translationNote":"Before flying anything real, follow your local rules: registration, remote ID, altitude limits and keeping the drone in sight. Simulation is where drone code should fail first."},{"id":"drones-autonomy","lessons":[{"conceptTags":["drones.rangefinders"],"explanation":"GPS tells a drone where it is; a rangefinder tells it how far away things are. Single-beam rangefinders and spinning lidars time a light pulse along a narrow beam, so every reading is a distance along one direction, valid between a minimum and a maximum range. Turning readings into obstacles is where the subtle bugs live: the maximum reading means that nothing was seen, beams leave gaps between them, a horizontal scan sees one thin slice of the world, and a few bad returns in every scan are normal.","id":"drones.rangefinders","objective":"Model a rangefinder as a ray with a maximum range and noise, turn a lidar scan into clustered obstacle points in local coordinates, reject dropouts and spurious returns with a median, pack the result as MAVLink OBSTACLE_DISTANCE, and name what a horizontal scan cannot see.","task":{"reading":{}},"title":"Rangefinders and lidar scans: rays, maximum range, noise and what a horizontal scan misses"},{"conceptTags":["drones.reactive-avoidance"],"explanation":"Reactive avoidance answers one question many times a second: given what the sensors see now, how fast may I fly in this direction? It needs no map and no plan, which makes it the last line of defence under every planner and the whole of the avoidance in many simple systems. Its failures are all about time and distance: a threshold that ignores speed, a ray that ignores the vehicle's width, a decision that comes one sensor period too late.","id":"drones.reactive-avoidance","objective":"Check the corridor a drone sweeps instead of a single ray, limit speed in proportion to the free distance with a gain that is provably safe for a measured reaction time and braking, and get past a building with stop-and-sidestep, without a map.","task":{"reading":{}},"title":"Reactive avoidance: corridors, slow-down zones and stop-and-sidestep"},{"conceptTags":["drones.potential-fields"],"explanation":"A potential field treats the goal as a valley and obstacles as hills and lets the vehicle roll downhill: the velocity command is the negative gradient of attraction plus repulsion. It takes a few dozen lines, reacts to every scan and draws smooth curves around scattered obstacles. It also has a famous flaw: wherever the pushes and the pull cancel, the vehicle stops, and a U-shaped building between it and the goal can hold it there indefinitely.","id":"drones.potential-fields","objective":"Build an artificial potential field from a goal and rangefinder readings, fly its negative gradient as a velocity command, watch it stall inside a U-shaped obstacle, detect the stall, and escape by wall following, with an honest account of what fields cannot guarantee.","task":{"reading":{}},"title":"Potential fields: attraction, repulsion from a scan, and the local-minimum trap"},{"conceptTags":["drones.gap-following"],"explanation":"Instead of adding forces, a polar histogram asks which directions are open. Borenstein and Koren's Vector Field Histogram (1991) and its successor VFH+ (Ulrich and Borenstein, 1998) reduce the surroundings to a ring of sectors, mark the ones an obstacle blocks and steer into the open sector that best serves the goal. Because it chooses among directions rather than summing pushes, an obstacle on the line to the goal cannot balance it into a standstill. It is still a local method, and the vehicle's width has to be put in explicitly.","id":"drones.gap-following","objective":"Bin a lidar scan into a polar histogram, threshold it with hysteresis into blocked and free sectors, widen every reading by the vehicle radius, choose the free direction with a VFH+ style cost, smooth heading and speed, and fly through a cluttered field.","task":{"reading":{}},"title":"Gap following with a polar histogram: VFH-style sectors, widening and heading choice"},{"conceptTags":["drones.inspection-orbit"],"explanation":"Inspection flights photograph masts, chimneys, wind turbine towers and bridge piers from a fixed distance, so that every image has the same scale and focus and the vehicle never drifts into the structure. Autopilots can orbit a point in coordinates. That works when the coordinates are right, but site plans, imagery and GPS are each good to a few metres, and a 4 m error in the centre turns an 8 m standoff into anything from 4 to 12 m.","id":"drones.inspection-orbit","objective":"Orbit a mast at a constant distance from its surface with a radial PI loop on the rangefinder and a tangential speed, count laps, and compare per-lap standoff statistics with a GPS-only orbit around a mapped position that is a few metres off.","task":{"reading":{}},"title":"Inspecting a structure: a constant-standoff orbit from rangefinder feedback"},{"conceptTags":["drones.occupancy-grid"],"explanation":"A planner needs a map, and on most sites nobody hands you a current one: a crane moved, a container arrived, a tree grew. A drone can build its own with a rangefinder. Every beam says two things: the space it crossed was empty, and something stood where it ended. An occupancy grid collects that evidence cell by cell, as a probability that the cell is occupied, and keeps apart three answers that a naive map mixes up: free, occupied, and never looked at.","id":"drones.occupancy-grid","objective":"Build a 2D occupancy grid in local metres from rangefinder scans: add log-odds evidence along each beam traced with Bresenham's line, mark nothing for readings without a return, clamp every cell so the map can change, and compare the built map with the true obstacles after a survey flight.","task":{"reading":{}},"title":"Occupancy grids from rangefinder scans: log-odds, Bresenham rays and clamping"},{"conceptTags":["drones.configuration-space"],"explanation":"The path-planning lesson searched a grid that someone else had drawn and inflated. Here the drone builds the map itself, so two decisions come before the search: how much room to leave around what it saw, and what to assume about what it never saw. Both decide whether the planned path is safe. A wrong answer to the second does not show on the map: the path looks clear because nobody looked.","id":"drones.configuration-space","objective":"Turn a self-built occupancy grid into a configuration space by growing occupied cells by the airframe radius, a margin and half a cell, decide whether unknown cells count as free or blocked, plan on the result with A*, fly the plan and check the clearance with the rangefinder.","task":{"reading":{}},"title":"Configuration space: inflating your own map, deciding about unknown cells and flying the plan"},{"conceptTags":["drones.behaviour-trees"],"explanation":"The flight-modes lesson wrote the vehicle's modes as a transition table. A table works while every state can be listed, but autonomy adds reactions that apply everywhere: whatever the drone is doing, a low battery sends it home and an obstacle ahead stops it. In a table, each such reaction is a row from every state, plus a way back to whatever it interrupted. A behaviour tree writes each reaction once, as a branch in priority order, and evaluates the tree again on every control step. Game AI made behaviour trees popular, and robotics adopted them for the same reason: reactive behaviour that stays readable as it grows.","id":"drones.behaviour-trees","objective":"Build a behaviour tree from Sequence, Fallback, Condition and Action nodes that return Success, Failure or Running, tick it at 10 Hz to fly 'inspect then return; on low battery return; on obstacle hold', trace its ticks deterministically and compare it with the flight-modes lesson's state machine.","task":{"reading":{}},"title":"Behaviour trees for autonomy: sequences, fallbacks, conditions and actions ticked every step"},{"conceptTags":["drones.precision-landing"],"explanation":"GPS puts a drone within a metre or two of a point. That is fine for a field, but not for a charging pad, a box on a ship or a dock with contacts. Precision landing adds a sensor that sees the pad itself, usually a downward camera that finds a light beacon or a printed marker, and reports where the pad is relative to the drone. The control problem is then simple. The hard part is deciding when to trust the sensor, when to keep descending and when to give up and climb.","id":"drones.precision-landing","objective":"Compare a GPS-only landing on a pad with a beacon-guided one in gusty wind: centre on the beacon's offset with a PI loop, descend only inside a gate that narrows with height, abort and climb back when the pad is out of view or the error jumps near the ground, and cap the retries.","task":{"reading":{}},"title":"Precision landing on a beacon: centring while descending, gates, aborts and retries"},{"conceptTags":["drones.gps-denied"],"explanation":"GPS fails in ordinary places: between tall buildings, under a bridge, beside large steel structures, or near radio interference. Without a position, a multicopter autopilot still holds its attitude and, with a barometer, its height. What it loses is the ability to stay over a point, and in wind that means drifting downwind while the telemetry keeps looking healthy. The ground station has to notice the outage, and the program has to decide what to ask for. Whatever the program decides, the autopilot's own failsafe will act.","id":"drones.gps-denied","objective":"Detect a GPS outage at the ground station from the fix flag and repeated positions rather than message age, measure how far a drone drifts in wind when its autopilot can only keep level, watch the 'no GPS for 3 s: landing' failsafe act, and compare hold, land and climb policies in an urban canyon with the failsafe on and off.","task":{"reading":{}},"title":"Flying without GPS: frozen telemetry, drift, the landing failsafe and your own policy"}],"summary":"Rangefinders and lidar scans, reactive avoidance and braking distance, potential fields and gap following, orbiting a structure, occupancy grids, planning in configuration space, behaviour trees, beacon landing and flying without GPS.","title":"Autonomy: rangefinders, maps, avoidance and precision landing","translationNote":"The simulator adds obstacles, a rangefinder, landing pads with a beacon and GPS outages; the replay draws them. Real perception is harder: sensors miss thin wires, glass and moving objects, so keep a human able to take over."},{"id":"drones-operations","lessons":[{"conceptTags":["drones.radio-link"],"explanation":"The failsafes lesson treated link loss as a heartbeat timeout in code, and the ground-station lesson as a timer that every frame resets. In the field the questions are different. How far does the link reach at this site today? What does the screen show when it drops? Where will the vehicle be when its failsafe fires, and where will it come back into range? What should the operator do in the meantime, and what should they not do? This lesson answers them with the simulator's limited-range link.","id":"drones.radio-link","objective":"Treat the radio link as a measured range around home, show what a ground station sees while reports stop arriving, follow the link-loss failsafe second by second, predict where the vehicle reappears, and plan and fly missions that stay inside the link with margin.","task":{"reading":{}},"title":"Radio links in operations: tested range, what the station sees, the failsafe timeline and margins"},{"conceptTags":["drones.flight-logs"],"explanation":"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.","id":"drones.flight-logs","objective":"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.","task":{"reading":{}},"title":"Flight logs: fixed-rate records, events, CSV export, per-flight metrics and anomaly rules"},{"conceptTags":["drones.energy-planning"],"explanation":"The failsafes lesson budgeted the way home in flight, every second. Before take-off the question is wider: will this whole mission, in today's wind, land with the reserve, and how sure are we? Answering it needs a consumption model of this airframe and pack, measured rather than guessed, a prediction for every leg, and an honest margin for what the model does not know. The same model then tells you after the flight where it was wrong.","id":"drones.energy-planning","objective":"Calibrate a drain model from short test legs at known airspeeds, fit it by least squares, predict a planned route leg by leg in several wind cases including the airspeed limit, decide go or no-go with a landing reserve and a model margin, then fly the mission and compare prediction with use.","task":{"reading":{}},"title":"Energy planning before take-off: calibrating consumption, predicting a mission and go/no-go"},{"conceptTags":["drones.preflight-checks"],"explanation":"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.","id":"drones.preflight-checks","objective":"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.","task":{"reading":{}},"title":"Preflight checks as code: fence legs, height limits, obstacle clearance, link and energy with errors.Join"},{"conceptTags":["drones.remote-id"],"explanation":"Remote ID is a drone's digital licence plate: while it flies it broadcasts who it is, where it is and where its control station is, so that people nearby, the authorities and other airspace users can see it. For a developer it is also a small protocol problem: a fixed message set, scaled integers in a few bytes, a strict clock, and a receiver that must decide which frames to believe. This lesson builds both ends with a teaching format, and is explicit about which parts are the regulators' requirements and which are the model's.","id":"drones.remote-id","objective":"State what standard Remote ID broadcasts and how often according to the FAA, and what EASA says the European broadcast carries; encode a simplified message set (identity, position and altitude, velocity, control station, time mark, emergency status) with encoding/binary; and build a receiver that checks freshness, plausibility and missing fields on simulator telemetry.","task":{"reading":{}},"title":"Remote ID: the broadcast message set, a binary teaching format and a validating receiver"},{"conceptTags":["drones.strategic-deconfliction"],"explanation":"The fleets lesson kept drones apart in flight: altitude layers and a monitor that reacts when two aircraft get close. That is the tactical layer, and it works with seconds of warning. The strategic layer works before take-off: every operation declares the airspace it will use and when, and a service accepts only plans whose volumes do not overlap. Done well, most conflicts are settled on the ground; done badly, two plans that each look fine on their own meet over the same field.","id":"drones.strategic-deconfliction","objective":"Describe each operation as segmented 4D volumes (footprint, altitude band, time window), detect conflicts by overlap in time, altitude and buffered footprint, reserve intents first come, first served by moving or rejecting newcomers, then fly the accepted plans with several drones and verify conformance and separation.","task":{"reading":{}},"title":"Strategic deconfliction: 4D volumes, reservations and flying the accepted plans"},{"conceptTags":["drones.fleet-backend"],"explanation":"Behind every delivery or inspection service sits a backend: clients create missions, a dispatcher hands them to vehicles, and everyone polls for progress. Mobile networks lose responses, so clients retry, and a retried POST that creates a second mission sends a second drone. The dispatcher must also tell the truth about outcomes: a mission that ended in a failsafe has failed, even if the drone landed safely at home.","id":"drones.fleet-backend","objective":"Build a mission API with Go 1.22 ServeMux method and wildcard patterns, make POST safe to retry with an Idempotency-Key, dispatch missions to drones through an explicit queued, assigned, flying, done or failed state machine driven by the autopilot, and exercise it all through httptest without opening a socket.","task":{"reading":{}},"title":"A fleet backend in Go: a mission API, idempotent POST and a dispatch state machine"},{"conceptTags":["drones.property-testing"],"explanation":"The simulation-testing lesson checked a table of hand-picked worlds, and a table holds only the cases someone thought of. Property-based testing turns the question around: state what must be true in every world, let a generator produce hundreds of worlds nobody would have written down, and when one breaks a property, shrink it until only the cause is left. Flight software suits it, because its invariants are short and its failures hide in combinations of geometry and weather.","id":"drones.property-testing","objective":"Generate scenarios from seeds, state invariants that must hold in every world, find a failing seed for a deliberately weak obstacle planner, shrink it to a minimal counterexample, verify the fixed planner across every seed, and express the same property as a Go fuzz target.","task":{"reading":{}},"title":"Property-based testing of flight software: generated worlds, shrinking and fuzz targets"},{"conceptTags":["drones.incident-analysis"],"explanation":"Sooner or later a flight ends in the wrong place: against a wall, in a field, in a tree. What happens next decides whether it happens again. An incident analysis rebuilds the timeline from the logs, measures the factors that combined, and ends with a change that has been tested, not with a name. This lesson works through a GPS outage beside a tower in the simulator, where the ground station showed a drone holding still while it drifted into the wall.","id":"drones.incident-analysis","objective":"Reconstruct an incident from the autopilot's event timeline and recorded telemetry, separate what the ground station saw from what happened, compute contributing factors such as time without a fix and drift against the planned stand-off, write a blameless summary, change one thing and re-fly the same fault to verify it.","task":{"reading":{}},"title":"Post-flight incident analysis: timeline, contributing factors and a verified change"}],"summary":"Radio range and link loss, flight logs and anomaly rules, energy planning, preflight checks as code, Remote ID, strategic deconfliction, a fleet backend, property-based flight tests and incident analysis.","title":"Operations: links, logs, rules and fleets in service","translationNote":"Rules differ by country and change: check your aviation authority before you fly. Lessons cite the FAA and EASA pages they rely on and describe the rest as principles."}]}