flypi

Official repository for flypi python library

This is a fork of kestrel-research/flypi, kept for reference and contributions. It is not an original project.

flypi

Fly ArduPilot and PX4 drones from a Raspberry Pi with a few lines of Python.

CI
PyPI
Python
License

flypi is a small, modern, high-level MAVLink library for companion computers.
It is built on pymavlink, has no other
dependencies, and installs cleanly on a Raspberry Pi.

import flypi

with flypi.connect("udp:127.0.0.1:14550") as drone:
    drone.wait_ready()  # pre-arm checks pass + 3D GPS fix
    drone.arm()
    drone.takeoff(5)  # metres above home; waits until it gets there
    print(drone.telemetry.position)
    drone.land()  # waits until landed and disarmed

Status: alpha (v0.1.1). The API may still change before 1.0.
ArduPilot Copter is the primary target. PX4 support is experimental.

Install

pip install flypi

Python 3.10 or newer. Works on Raspberry Pi OS (Bookworm and later), Linux, macOS and Windows.

Connecting

flypi.connect() takes a pymavlink connection string:

Setup Address
ArduPilot SITL via MAVProxy, or PX4 SITL "udp:127.0.0.1:14550" (default)
ArduPilot SITL directly "tcp:127.0.0.1:5760"
Pi UART (GPIO 14/15) wired to the flight controller "/dev/serial0" with baud=921600 (match your SERIALx_BAUD)
Flight controller over USB "/dev/ttyACM0"
drone = flypi.connect("/dev/serial0", baud=921600, timeout=30)

flypi waits for the autopilot's heartbeat. It ignores heartbeats from ground
stations, gimbals and cameras. If nothing is heard within timeout, you get a
flypi.ConnectionTimeout that tells you what to check.

Why flypi

What you can do in v0.2

Call What it does
drone.telemetry Immutable snapshot: armed, mode, position, velocity, attitude, battery, gps, heartbeat_age
drone.wait_ready(require_gps=True) Wait until the vehicle is ready to arm
drone.set_mode("LOITER") Change flight mode and confirm it
drone.arm() / drone.disarm() Arm or disarm and confirm it
drone.takeoff(altitude) Vertical takeoff to altitude metres above home
drone.goto(lat, lon, altitude) Fly to a position (confirmed with the autopilot), wait until there
drone.goto_relative(north=, east=, up=) Fly a distance in metres from where the vehicle is
drone.land() Land at the current position, wait for disarm
drone.return_to_launch() Switch to RTL
drone.wait_until(cond, timeout) Wait for any telemetry condition
drone.status_messages Recent messages from the autopilot (e.g. PreArm: reasons)
drone.available_modes Mode names this vehicle accepts

Every command checks the vehicle's acknowledgement. When the autopilot refuses
something, flypi raises an error that includes the autopilot's own explanation:

flypi.errors.CommandRejected: MAV_CMD_COMPONENT_ARM_DISARM was rejected by the
vehicle (MAV_RESULT_FAILED). Recent vehicle messages: PreArm: Need 3D Fix

All errors inherit from flypi.FlypiError:

Error Meaning
ConnectionTimeout No autopilot heartbeat while connecting
ConnectionLost Heartbeats stopped while flypi was waiting on the vehicle
CommandRejected The autopilot refused a command (.result, .status_messages)
CommandTimeout The autopilot never acknowledged a command, even after retries
FlightInterrupted A failsafe, the pilot or another GCS took over mid-manoeuvre (.mode)
WaitTimeout A condition was not reached in time
ModeError That mode name does not exist on this vehicle
NotArmedError The action needs the vehicle to be armed
try:
    drone.takeoff(10)
except flypi.FlightInterrupted as e:
    print(f"Something else took over (now in {e.mode}): {e}")
except flypi.ConnectionLost:
    print("Link lost; the autopilot's own failsafe is now in charge")

Telemetry example

t = drone.telemetry
print(t.mode, t.armed)
print(f"{t.position.lat:.6f}, {t.position.lon:.6f} @ {t.position.alt_rel:.1f} m")
print(f"Battery {t.battery.voltage:.1f} V ({t.battery.remaining}%)")
print(f"GPS fix {t.gps.fix_type}, {t.gps.satellites} satellites")

Values the vehicle has not reported yet are None.

Going somewhere

drone.takeoff(10)
drone.goto(-35.36290, 149.16550, 15)  # lat, lon, metres above home
drone.goto_relative(north=20, east=-10)  # 20 m north, 10 m west
drone.goto(-35.36326, 149.16523, groundspeed=3)  # slower; altitude unchanged

goto() blocks until the vehicle is within tolerance metres (default 1 m) of
the target. Pass wait=False to return straight away.

MAVLink has no acknowledgement for position targets, so most libraries just
send one and hope. flypi confirms it:

If a failsafe, the RC pilot or another ground station changes mode on the way,
goto() raises FlightInterrupted.

Coming from DroneKit

DroneKit-Python fails to import on Python 3.10 and newer (it uses
collections.MutableMapping, which Python 3.10 removed), and current Raspberry Pi
OS releases ship newer Pythons than that. flypi is a small, typed replacement for
the most common DroneKit flight scripts:

DroneKit flypi
connect(addr, wait_ready=True) flypi.connect(addr), then drone.wait_ready()
vehicle.mode = VehicleMode("GUIDED") + polling drone.set_mode("GUIDED") (confirmed)
vehicle.armed = True + while not vehicle.armed drone.arm() (confirmed, with PreArm: reasons on failure)
vehicle.is_armable drone.is_armable
vehicle.simple_takeoff(alt) + altitude loop drone.takeoff(alt) (waits until it gets there)
vehicle.simple_goto(LocationGlobalRelative(lat, lon, alt)) + distance loop drone.goto(lat, lon, alt) (confirmed, waits until it gets there)
simple_goto(..., groundspeed=5) drone.goto(..., groundspeed=5)
get_distance_metres(a, b) helper drone.telemetry.position.distance_to(lat, lon)
get_location_metres(...) helper + simple_goto drone.goto_relative(north=..., east=...)
vehicle.location.global_relative_frame.alt drone.telemetry.position.alt_rel
vehicle.battery, vehicle.gps_0 drone.telemetry.battery, drone.telemetry.gps
vehicle.attitude (radians) drone.telemetry.attitude (degrees)
add_attribute_listener / polling loops drone.wait_until(condition, timeout)
vehicle.close() drone.close() or with flypi.connect(...) as drone:

Not in flypi yet: velocity control, missions and parameters (see the roadmap).

Try it in simulation first

Always test in software-in-the-loop (SITL) simulation before flying real hardware.

ArduPilot SITL (see the ArduPilot SITL docs):

sim_vehicle.py -v ArduCopter --console --map
# in another terminal
python examples/first_flight.py

PX4 SITL (see the PX4 simulation docs):

make px4_sitl gz_x500
python examples/first_flight.py

How it works

Each connection runs one background thread. The thread reads every MAVLink
message from the vehicle to keep telemetry current, and sends a 1 Hz
ground-station heartbeat so the autopilot knows a controller is attached. Your
code calls ordinary blocking methods. No asyncio is needed.

flypi asks the vehicle for the telemetry streams it needs and confirms each
request. Streams the vehicle refused or did not confirm are listed in
drone.unconfirmed_streams (and logged); flypi keeps working with whatever the
vehicle sends by default.

Because flypi heartbeats as a ground station, an autopilot with a GCS failsafe
enabled (FS_GCS_ENABLE on ArduPilot) will treat your script stopping
mid-flight as a lost ground station and run its failsafe action. That is
usually what you want on a companion computer.

Safety

Drones can seriously injure people and damage property. Test in SITL first, then
with propellers removed. Fly only where it is safe and legal, follow your local
aviation rules, and always keep a manual RC override ready. flypi is provided
"as is", without warranty. See the LICENSE.

Development

git clone https://github.com/kestrel-research/flypi
cd flypi
pip install -e ".[dev]"
pytest
ruff check .
mypy

The test suite runs flypi end to end over real UDP sockets against a small
MAVLink vehicle emulator (tests/fake_vehicle.py), so it needs no simulator.

Roadmap

License

Apache-2.0 © Kestrel Research contributors. Part of
Kestrel Research.