Home›Blog›Larzscript
Larzscript

Building an Autonomous Drone Simulator in Larzscript

2026-08-24 · Larzscript

Most Larzscript packages so far have been utilities - a router, a state machine, a parser. This one is a real application: an autonomous drone control system with a live dashboard, a PID flight controller, a waypoint mission engine, and a geofence/battery safety layer, sitting on top of a physics-simulated drone. There's no physical hardware yet - that's deliberately Phases 6-10 of the plan - but everything from the HTTP server up is real, live, and running in production at larzos.com/drone/.

The architecture

The system splits into the same layers a real flight stack would have, each one a small Larzscript module with one job:

frontend/            static dashboard (map, telemetry, mission planner, controls)
backend/
  server.lz           entry point: tcp.serve(port, handler)
  api.lz                HTTP request parsing + routing
  state.lz               drone telemetry dict + disk persistence + flight log
  modes.lz                 flight-mode state machine (the real `fsm` package)
  commands.lz                validates + applies commands against modes.lz
  mission.lz                   waypoint list + arrival/hold logic
  guidance.lz                    PID loops -> commanded heading/speed/vspeed
  physics.lz                       pure integration + battery drain
  safety.lz                          geofence/altitude/battery failsafes
  sim.lz                                advances everything by real elapsed time

Every layer only talks to its neighbors. guidance.lz never touches position directly - it just decides what the drone should be doing and writes commanded values; physics.lz only ever ramps toward whatever's commanded. safety.lz sits outside that loop entirely and can override the flight mode on its own authority - the same way a real flight controller's failsafe does - regardless of what the mission or the frontend asked for.

No threads, no background loop - so how does it "run"?

Larzscript's interpreter has no concurrency primitive, and its tcp.serve() is genuinely one-connection-at-a-time. There's no way to spin up a background loop that keeps simulating while the process waits for the next request. So the simulation doesn't try to: every API call first measures real elapsed wall-clock time since the last request and fast-forwards the drone through however many 0.5-second physics sub-steps that represents, then answers. A dashboard polling every 1.5 seconds sees what looks like continuous flight; the simulation is really only ever advanced by a request arriving.

fn advance(st, mode_fsm) {
  let now = clock()
  let elapsed = now - st["last_tick_clock"]
  st["last_tick_clock"] = now
  let remaining = elapsed
  while remaining > 0.0 {
    let dt = remaining > MAX_SUBSTEP_S ? MAX_SUBSTEP_S : remaining
    guidance.step(st, mode_fsm, dt, st["sim_clock"])
    physics.tick(st, dt)
    safety.enforce(st, mode_fsm, state.log_event)
    remaining = remaining - dt
  }
}

A real bug: 111 meters became 17 kilometers

The first working version stored the drone's position as lat/lon and moved it every tick with a real spherical destination-point formula, built on the geo package's own trig helpers. It looked fine in isolation - moving 1000m due east landed within about 3% of the right spot. Then a real waypoint test (fly 111 meters north) sent the drone 17 kilometers off course in under a minute.

The root cause: geo's bearing()/destination-point math goes through an atan2 approximation with a documented ~0.005 rad tolerance. That's a small angle, but it translates into a roughly 50-meter position error on every single call, regardless of how far the drone is actually supposed to move. A one-off 50m fuzz on a 1000m move is nothing. Recomputed on every 0.5s physics sub-step - up to 100+ times across one API call that fast-forwards a minute of flight - that constant per-call bias compounds additively, and 50m × 120 calls is a very real 6 kilometers.

# destination(lat, lon, bearing=0, dist_m=0.0) - a ZERO-distance move -
# should return the exact same point back. It didn't:
print(destination(6.5244, 3.3792, 0, 0.0))
# [6.52485, 3.3792]   <- a real 50m jump for a distance of zero

The fix wasn't a bigger safety margin - it was realizing lat/lon was the wrong state representation for a tight simulation loop in the first place. Position now lives in a flat local meters frame (north_m/east_m relative to home), integrated with the same package's raw _sin/_cos - which round-trip to full precision (sin²+cos²==1 exactly, verified directly) because they're a real Taylor series, not an atan2 approximation. Lat/lon gets derived from that once, only when a telemetry response is built, never fed back into the simulation. Closed-loop guidance (recompute bearing toward the target fresh every tick from the real, correctly-integrated position) means any small per-tick error self-corrects instead of compounding - the bug was never the size of the error, it was letting an approximate value feed back into itself hundreds of times.

A real, generic PID controller

Altitude hold and waypoint approach both run through the same small PID implementation - anti-windup included (the integral term is clamped to the controller's own output range, not left to grow unbounded while already saturated):

fn step(p, target, current, dt) {
  let error = target - current
  p["integral"] = p["integral"] + error * dt
  # ...clamp integral to output span...
  let deriv = p["has_prev"] ? (error - p["prev_error"]) / dt : 0.0
  p["prev_error"] = error
  let output = p["kp"] * error + p["ki"] * p["integral"] + p["kd"] * deriv
  # ...clamp output to [out_min, out_max]...
  return output
}

Altitude uses one instance (target altitude → commanded vertical speed); waypoint approach uses another, fed the distance-to-target as its error so speed naturally tapers as the drone gets close, instead of overshooting and oscillating around the waypoint.

Commands can't skip the state machine

Every flight-mode transition - arm, takeoff, hold, resume, return-to-home, land - is registered as a real transition in the fsm package: idle → armed → takeoff → flying, with rth/land reachable from whichever states actually make sense mid-flight. A command handler checks fsm.can() before touching anything:

fn takeoff(st, mode_fsm, alt_m) {
  if not modes.can(mode_fsm, "takeoff") {
    return {"ok": false, "error": "cannot take off from mode '" + modes.state(mode_fsm) + "' - arm first"}
  }
  ...
}

"Invalid command rejection" isn't a comment or a TODO - it's a real 422 response with a specific reason, straight from a data-driven transition table.

Try it

The live dashboard is at larzos.com/drone/ - arm, take off, click the map to drop waypoints, watch it fly a real mission and come home on a real geofence and battery model. Full source, including the test suite that caught the drift bug, is on GitHub.

Ready to fly it?

Open the live dashboard →

Explore the apps