The high-level Python API for reliable, autonomous drone control, advanced telemetry, and MAVLink mission management.
- β¨ Overview
- π Key Features
- π οΈ Tech Stack & Architecture
- π Project Structure
- βοΈ Getting Started
- π― Usage
- π€ Contributing
- π License
pyMAVLinCS is a powerful, professional-grade Python library designed to simplify the development of autonomous systems by providing a high-level, stable, and feature-rich interface for MAVLink-based flight controllers (like ArduPilot and PX4).
β οΈ The Problem: Developing complex drone missions or ground control stations (GCS) often requires deep, low-level integration with the MAVLink protocol. This involves handling command acknowledgments, managing asynchronous message streams (likeSTATUSTEXTorTIMESYNC), performing complex geographic calculations, and ensuring thread safety, leading to verbose and error-prone code.
pyMAVLinCS eliminates this complexity by wrapping the core pymavlink functionality into an intuitive, object-oriented API (MAVLinCS class). It enables developers and engineers to execute mission-critical commands, retrieve comprehensive telemetry, manage gimbal payloads, and handle inter-system communication using simple, Pythonic method calls. This allows users to focus entirely on mission logic and operational safety, drastically reducing development time and enhancing code reliability.
The library is built around core Python features, geographic computations (geopy), and a thread-safe MAVLink message handler (pymavlink). Internal handler classes ensure seamless management of complex MAVLink processes like STATUSTEXT chunk reconstruction, TIMESYNC latency calculation, automatic .tlog flight recording, and structured console/file logging.
pyMAVLinCS provides comprehensive capabilities spanning control, data retrieval, mission management, and advanced system configuration through the core MAVLinCS class.
Gain instant access to crucial flight and system data using simple method calls that handle message retrieval and parsing automatically:
- π°οΈ Global & Local Position: Retrieve current GPS coordinates (
position_gps: latitude, longitude, relative altitude, MSL altitude) and local NED coordinates (position_local). - π§ Attitude and Velocity: Get precise attitude Euler angles (
angles) and angular rates (angular_rates). Retrieve linear velocities in three dimensions (speed) and absolute speed norm (speed_module). - β‘ Power Monitoring: Check remaining battery percentage (
battery_percentage) and current voltage in Volts (battery_voltage). - βοΈ Flight Status: Instantly check arming status (
motors_armed,motors_disarmed), autopilot type (autopilot_int,autopilot_str), current flight mode (mode,custom_mode), and PX4 mode details (base_mode,custom_main_mode,custom_sub_mode). - π Fix Status: Confirm the status of the GPS system, including 3D fix availability (
gps_3d_fix). - π Timing Data: Access system boot time in seconds (
time_boot) and milliseconds (time_boot_ms), and Unix timestamp in microseconds (time_usec).
Execute mission-critical commands with built-in acknowledgment handling to ensure reliable action completion:
- π System State Management: Safely arm (
arm) or disarm (disarm) the drone, with automatic pre-arm mode checks on ArduPilot, optional forced execution, and configurable timeouts. - π Takeoff & Landing: Initiate automated takeoff (
takeoff) to a specified altitude (including in-air vertical repositioning) or perform an automated landing (land). - π Flight Mode Control: Change the flight mode using human-readable mode names, ArduPilot mode IDs, or PX4 mode tuples (
set_mode). - πΊοΈ Targeted Movement: Set precise GPS position targets (
set_gps_pos_target) or local NED position targets (set_local_pos_target) with optional yaw control. - π¨ Velocity Control: Directly command the drone's velocity components (
set_speed: North, East, Down in m/s) and heading. - π Return to Launch (RTL): Send a Return-To-Launch request (
return_to_launch) for safe mission abort. - π― Dynamic Vehicle Following: Autonomously take off and follow another moving MAVLink vehicle in real time (
do_follow,do_follow_with_takeoff). - π¬ Precision Landing Target: Stream visual/IR landing target offsets in the drone's body frame (
send_landing_target). - π§ System Configuration & Reboot: Modify flight controller parameters on the fly (
write_parameter), adjust telemetry message streaming rates (set_msg_rate), or trigger an autopilot reboot (reboot). - π‘οΈ Built-in Safety Switches: Instantly inhibit physical flight commands (
allow_actions = False) or abort all blocking waits across threads (mission_ended = True).
Utilize powerful built-in mathematical functions for complex navigation and coordinate system management:
- π Home Position Management: Request and retrieve the designated HOME position (
request_home_position,home_position) and set a new HOME location (set_home,set_home_current_pos). - π EKF Origin: Get or set the EKF origin location (
ekf_origin,set_ekf_origin) for accurate local navigation initialization. - π Distance Calculation: Calculate 2D/3D distances between the flight controller and a specified GPS point (
get_distance_with_gps_pos) or local coordinate point (get_distance_with_local_pos). - π Coordinate Conversion Utilities: Perform geometric transformations, including Quaternion to Euler conversion (
quaternion_to_euler), 2D/3D distances between arbitrary points (distance_between_two_gps_points,distance_between_two_local_points), Cartesian/polar projections to GPS coordinates (cartesian_to_geographic_point,polar_to_geographic_point), and GPS-to-Cartesian displacements (geographic_to_cartesian_point).
Simplify the workflow for designing and executing automated AUTO missions:
- π’ Waypoint Management: Clear stored missions (
clear_waypoints), announce waypoint counts (send_waypoint_count), and upload individual mission items (send_waypoint). βΆοΈ Mission Execution: Start the loaded mission from the ground or in flight (start_mission).- β
Mission Status: Check the active waypoint sequence number (
current_waypoint_seq) and verify if the waypoint mission is completed (is_waypoint_mission_completed).
Integrated support for controlling camera gimbals and servo peripherals:
- πΌοΈ Angle & Rate Control: Orient the gimbal precisely by setting pitch/yaw angles, rotation speeds, and reference frames (
set_gimbal_angles), or read current gimbal orientation (gimbal_angles). - π ROI Position Targeting: Command the gimbal to track a specific GPS coordinate (
set_gimbal_target). - π Gimbal Modes: Set the gimbal to retract mode (
set_gimbal_retract) or neutral position (set_gimbal_neutral). - π Servo Control: Actuate any servo channel (
set_servo) and read live PWM outputs (servo_pwm).
Dedicated handler classes simplify listening for and sending custom messages:
- πΌ Automatic
.tlogFlight Logging: Automatically records all incoming and outgoing MAVLink packets into a standard.tlogbinary file (MavLogger), ready for replay in Mission Planner or QGroundControl. - π¬ Status Text Handling: Automatically reassemble multi-chunk
STATUSTEXTmessages (StatustextReceiver,last_statustext_from_sysidcompid) and send chunked status texts (send_statustext). - π°οΈ Latency Monitoring: Broadcast
TIMESYNCrequests (send_timesync) and monitor one-way link latency (get_latence_ms_with_sysidcompid). - π’ Mission Control Codes (MCC): Define, send, check, and delete custom named integer codes (
MCC,send_mcc,check_mcc,delete_mcc,send_named_value_int) for multi-agent or GCS-to-companion synchronization. - β‘ Event Callbacks: Register custom callbacks for incoming messages (
set_additional_recv_msg_callback), outgoing messages (set_additional_send_callback), complete status texts (set_statustext_callback), or MCC events (set_mcc_callback).
Implement robust, blocking operations with timeout and abort support:
- π Arming Synchronization: Wait until motors are confirmed armed or disarmed (
wait_motors_armed,wait_motors_disarmed). βοΈ Mode Synchronization: Wait for a flight mode transition to complete (wait_mode_changed).- π Navigation Synchronization: Wait for a 3D GPS fix (
wait_gps_3d_fix), HOME position reception (wait_for_home), or target proximity in GPS/local coordinates (wait_proximity_with_gps_pos,wait_proximity_with_local_pos). - π Command & Mission Acknowledgments: Block execution until a specific
COMMAND_ACKorMISSION_ACKis received and validated (wait_command_ack,wait_mission_ack).
pyMAVLinCS is designed as a focused Python library, utilizing proven components for reliable aerospace communication and data processing.
| Technology | Purpose | Why it was Chosen |
|---|---|---|
| Python (>=3.10) | Primary development language for the API. | Provides clean type-annotated syntax ideal for robotics and embedded companion computers. |
| pymavlink | Core dependency for MAVLink protocol communication. | Standard library for parsing, packing, and transmitting MAVLink 2 messages. |
| geopy | Dependency for geographic calculations. | Provides accurate geodesics for distance, bearing, and coordinate projection. |
| colorama | Terminal output formatting. | Enables color-coded severity levels in the built-in console logger. |
| pytest | Testing framework for unit and SITL integration tests. | Powers automated continuous integration against ArduPilot SITL. |
The project structure separates the core MAVLink interface, supporting utility classes, usage examples, and automated SITL tests.
π pyMAVLinCS/
βββ π pyMAVLinCS/ # Core Library Package
β βββ π __init__.py # Main entry point (MAVLinCS class definition)
β βββ π mavecstra.py # Threading, TimesyncHandler, StatustextReceiver, MavLogger
β βββ π mavtypes.py # Typed data models (GPSPosition, Angles, Speed, etc.)
β βββ π mission_control_code.py # Class definition for MCC (Missio Control Code)
β βββ π setup_logger.py # Logging setup utility and custom console/file formatters
βββ π examples/ # Demonstrative usage scripts
β βββ π 01_basic_takeoff_and_land.py # Pre-flight telemetry, arming, takeoff, and landing
β βββ π 02_guided_navigation_and_velocity.py # Local NED, GPS polar projection, velocity circle, RTL
β βββ π 03_autonomous_waypoint_mission.py # Building, uploading, and monitoring AUTO missions
β βββ π 04_custom_mcc_and_callbacks.py # Custom MCCs, asynchronous callbacks, and TIMESYNC
βββ π tests/ # Automated test suite (Unit & ArduPilot SITL)
β βββ π conftest.py # Pytest configuration and automated SITL fixtures
β βββ π test_01_unit_offline.py # Offline geometry, math, MCC, and safety guard tests
β βββ π test_02_telemetry_comms.py # Telemetry getters, HOME, TIMESYNC, callbacks, and params
β βββ π test_03_flight_guided.py # Full GUIDED flight test (takeoff, NED, GPS, speed, servo)
β βββ π test_04_missions_auto.py # In-air and ground-start AUTO waypoint mission tests
βββ π .github/ # GitHub configuration
β βββ π workflows/ # Continuous Integration & Delivery workflows
β βββ π test.yml # CI workflow (pytest against ArduPilot SITL master)
β βββ π publish.yml # CD workflow for PyPI package publication
βββ π pytest.ini # Pytest configuration file
βββ π pyproject.toml # Project metadata, dependencies, and build requirements
βββ π LICENSE # Project License (MPL 2.0)
βββ π README.md # Project documentation (this file)
βββ π .gitignore # Git ignore rules
Ensure you have the following installed:
- Python: Version 3.10 or higher (
>=3.10is required). - A MAVLink-compatible flight controller or simulator (e.g., ArduPilot SITL, PX4, Pixhawk, Cube).
- A communication link (e.g., UDP, TCP, USB/Serial telemetry radio).
- Install the library using pip:
pip install pyMAVLinCS- Verify installation:
from pyMAVLinCS import MAVLinCSpyMAVLinCS is used by instantiating the MAVLinCS class with your connection address. The instance automatically opens the link, waits for a valid HEARTBEAT, configures telemetry rates, starts the background MavThread, and begins recording a .tlog file.
from pyMAVLinCS import MAVLinCS
# Example 1: Connect via UDP to an ArduPilot SITL / GCS endpoint
drone = MAVLinCS(
address="udpin:127.0.0.1:14550",
mavlogfile="flight.tlog",
timeout_heartbeat=10,
pos_rate=4
)
# Example 2: Connect via Serial (replace /dev/ttyACM0 with your serial port)
# drone = MAVLinCS(address="/dev/ttyACM0", baud=57600)Execute flight commands with built-in acknowledgment and state verification:
try:
# Wait for the drone to achieve a 3D GPS fix before proceeding
drone.logger.info("Waiting for 3D GPS Fix...")
if not drone.wait_gps_3d_fix(timeout=30):
raise RuntimeError("GPS 3D Fix timeout.")
# Arm the drone (automatically switches to GUIDED mode if needed on ArduPilot)
if not drone.arm(timeout_arming=10):
raise RuntimeError("Drone failed to arm.")
# Execute a takeoff to 10 meters (waits until target altitude is reached)
if not drone.takeoff(altitude=10.0, precision=0.5, timeout_takeoff=30):
raise RuntimeError("Drone takeoff failed.")
# Land safely and wait for motors to disarm
drone.land(timeout_land=60)
except KeyboardInterrupt:
drone.mission_ended = True
finally:
drone.close()Access structured NamedTuple data models defining the vehicle's state:
# Get current GPS position and local NED position
gps_pos = drone.position_gps()
local_pos = drone.position_local()
print("\n--- Telemetry Snapshot ---")
print(f"Lat: {gps_pos.lat:.6f}Β°, Lon: {gps_pos.lon:.6f}Β°")
print(f"Relative Alt: {gps_pos.relative_alt:.2f}m | Alt (MSL): {gps_pos.alt:.2f}m")
print(f"Local NED -> North: {local_pos.x:.2f}m, East: {local_pos.y:.2f}m, Down: {local_pos.z:.2f}m")
# Get attitude angles (roll, pitch, yaw in radians)
angles = drone.angles()
print(f"Roll: {angles.roll:.2f} rad, Pitch: {angles.pitch:.2f} rad, Yaw: {angles.yaw:.2f} rad")
# Check battery status
print(f"Battery: {drone.battery_percentage()}% ({drone.battery_voltage():.2f}V)")pyMAVLinCS provides Mission Control Codes (MCC) to simplify event synchronization between ground stations and companion computers over MAVLink (NAMED_VALUE_INT):
from pyMAVLinCS import MAVLinCS, MCC
# Define a custom Mission Control Code
DRONE_READY = MCC(
value=1,
name="DRONE_READY",
level="SUCCESS",
description="Drone initialized and ready for mission."
)
drone = MAVLinCS(address="udpin:127.0.0.1:14550")
# Register a callback triggered whenever an MCC is received
drone.set_mcc_callback(lambda mcc: print(f"Received MCC: {mcc}"))
# Send, check, and delete an MCC
drone.send_mcc(DRONE_READY)
if drone.check_mcc(DRONE_READY):
drone.delete_mcc(DRONE_READY)Always close the connection when finished to cleanly stop the background MavThread, close the serial/UDP link, and flush the .tlog file:
drone.close()We welcome contributions to improve pyMAVLinCS! Your input helps make this project a more robust and reliable tool for autonomous vehicle development.
- Fork the repository: Click the 'Fork' button at the top right of this page.
- Create a feature branch:
git checkout -b feature/new-telemetry-endpoint
- Make your changes: Improve code, documentation, or features within the
pyMAVLinCS/directory. - Test thoroughly: Ensure all existing and new functionality works as expected. Automated tests run on push and PR via GitHub Actions using ArduPilot SITL. You can run the test suite locally with
pytest:# Run the automated test suite: pytest tests/ -v -s # Or execute an example script: python examples/01_basic_takeoff_and_land.py
- Commit your changes: Write clear, descriptive commit messages.
git commit -m "Fix: Corrected latency calculation in TimesyncHandler" - Push to your branch:
git push origin feature/new-telemetry-endpoint
- Open a Pull Request: Submit your changes for review by the maintainers.
- β
Follow the existing Python code style and type-hinting conventions (
PEP 8). - π Add comprehensive docstrings and comments for complex logic, especially within
MAVLinCSandmavecstra.py. - π§ͺ Whenever possible, ensure changes are verified against ArduPilot/PX4 SITL or real hardware.
- π Update documentation, including the
README.md, for any changed functionality or new public methods. - π Ensure backward compatibility when modifying existing API calls.
- π― Keep commits focused and atomic, addressing a single feature or bug fix per commit.
This project is licensed under the Mozilla Public License 2.0 (MPL-2.0) - see the LICENSE file for complete details.
- β Commercial & Private Use: You can freely use this software in commercial, private, and proprietary closed-source applications.
- β
Integration: You can import and use
pyMAVLinCSin your proprietary project without being forced to open-source your entire project. - β Patent Grant: You are explicitly granted rights to use patents related to this software.
β οΈ File-Level Copyleft: If you modify the original source files ofpyMAVLinCSitself (e.g., fixing a bug or adding a feature to the library's core), you must make the source code of those specific modified files available under the MPL 2.0. New distinct files you create for your application remain yours.β οΈ Warranty: The software is provided "as is," without warranty of any kind.