### Initialize and Connect MAVSDK System Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/index.md Example demonstrating how to import the System class and establish a connection to a drone using a UDP address. This process automatically manages the embedded mavsdk_server if no address is provided. ```python from mavsdk import System drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") ``` -------------------------------- ### Python Mission Upload and Execution Example Source: https://context7.com/mavlink/mavsdk-python/llms.txt This Python script demonstrates how to use the MAVSDK Mission plugin to upload and execute a waypoint mission. It requires the `mavsdk` library and `asyncio`. The script connects to a drone, defines a series of mission items (waypoints) with specific altitudes, speeds, and camera actions, uploads the mission plan, arms the drone, starts the mission, and monitors its progress until completion and landing. It also includes a function to print mission progress updates. ```python #!/usr/bin/env python3 import asyncio import logging from mavsdk import System from mavsdk.mission import MissionItem, MissionPlan logging.basicConfig(level=logging.INFO) async def print_mission_progress(drone): async for progress in drone.mission.mission_progress(): print(f"Mission progress: {progress.current}/{progress.total}") async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") # Wait for connection async for state in drone.core.connection_state(): if state.is_connected: break # Define mission waypoints # MissionItem(lat, lon, alt_m, speed_m_s, is_fly_through, # gimbal_pitch_deg, gimbal_yaw_deg, camera_action, # loiter_time_s, camera_photo_interval_s, # acceptance_radius_m, yaw_deg, camera_photo_distance_m, # vehicle_action) mission_items = [ MissionItem(47.398039859999997, 8.5455725400000002, 25, 10, True, float("nan"), float("nan"), MissionItem.CameraAction.NONE, float("nan"), float("nan"), float("nan"), float("nan"), float("nan"), MissionItem.VehicleAction.NONE), MissionItem(47.398036222362471, 8.5450146439425509, 25, 10, True, float("nan"), float("nan"), MissionItem.CameraAction.TAKE_PHOTO, float("nan"), float("nan"), float("nan"), float("nan"), float("nan"), MissionItem.VehicleAction.NONE), MissionItem(47.397825620791885, 8.5450092830163271, 25, 10, True, float("nan"), float("nan"), MissionItem.CameraAction.NONE, float("nan"), float("nan"), float("nan"), float("nan"), float("nan"), MissionItem.VehicleAction.NONE), ] mission_plan = MissionPlan(mission_items) # Configure mission settings await drone.mission.set_return_to_launch_after_mission(True) # Upload mission print("-- Uploading mission") await drone.mission.upload_mission(mission_plan) # Start progress monitoring progress_task = asyncio.create_task(print_mission_progress(drone)) # Wait for GPS async for health in drone.telemetry.health(): if health.is_global_position_ok and health.is_home_position_ok: break # Arm and start mission print("-- Arming") await drone.action.arm() print("-- Starting mission") await drone.mission.start_mission() # Monitor until mission completes async for in_air in drone.telemetry.in_air(): if not in_air: print("-- Mission complete, landed") break progress_task.cancel() if __name__ == "__main__": asyncio.run(run()) # Camera actions: NONE, TAKE_PHOTO, START_PHOTO_INTERVAL, # STOP_PHOTO_INTERVAL, START_VIDEO, STOP_VIDEO # Vehicle actions: NONE, TAKEOFF, LAND, TRANSITION_TO_FW, TRANSITION_TO_MC ``` -------------------------------- ### POST /offboard/start Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/offboard.md Starts the offboard control mode on the vehicle. ```APIDOC ## POST /offboard/start ### Description Starts offboard control. The vehicle must have a setpoint set before starting. ### Method POST ### Endpoint /offboard/start ### Response #### Success Response (200) - **result** (OffboardResult) - Success status #### Error Handling - **OffboardError**: Raised if the request fails (e.g., no setpoint set). ``` -------------------------------- ### Install Protoc Plugin for MAVSDK Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Installs the protoc-gen-mavsdk plugin required for generating MAVSDK code. This involves navigating to the proto/pb_plugins directory and installing dependencies from requirements.txt. ```shell cd proto/pb_plugins pip3 install -r requirements.txt ``` -------------------------------- ### Configure and Install MAVSDK-Python Locally Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Sets the architecture environment variable for ARM systems and installs the package in editable mode. This process triggers the download of the required mavsdk_server binary. ```bash export MAVSDK_SERVER_ARCH=armv7l python3 setup.py build pip3 install -e . ``` -------------------------------- ### Install MAVSDK-Python via pip Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/index.md Command to install or upgrade the MAVSDK-Python package using the Python package manager. ```bash python -m pip install --upgrade mavsdk ``` -------------------------------- ### Respond to Zoom In Start (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/camera_server.md Asynchronously handles responses when zoom in starts. It takes zoom in start feedback and can raise CameraServerError if the operation fails. ```python async def respond_zoom_in_start(zoom_in_start_feedback): """Respond to zoom in start. Parameters: zoom_in_start_feedback (CameraFeedback): the feedback Raises: CameraServerError: If the request fails. """ pass ``` -------------------------------- ### Respond to Zoom Out Start (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/camera_server.md Asynchronously handles responses when zoom out starts. It accepts zoom out start feedback and raises CameraServerError on failure. ```python async def respond_zoom_out_start(zoom_out_start_feedback): """Respond to zoom out start. Parameters: zoom_out_start_feedback (CameraFeedback): the feedback Raises: CameraServerError: If the request fails. """ pass ``` -------------------------------- ### GET /follow_me/config Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/follow_me.md Retrieves the current configuration settings for the FollowMe mode. ```APIDOC ## GET /follow_me/config ### Description Retrieves the current configuration for the FollowMe plugin, including height, distance, and responsiveness settings. ### Method GET ### Endpoint /follow_me/config ### Response #### Success Response (200) - **config** (Config) - The current configuration object containing follow_height_m, follow_distance_m, responsiveness, altitude_mode, max_tangential_vel_m_s, and follow_angle_deg. #### Response Example { "follow_height_m": 8.0, "follow_distance_m": 4.0, "responsiveness": 0.5, "altitude_mode": "CONSTANT" } ``` -------------------------------- ### Install MAVSDK-Python using pip Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Installs the MAVSDK-Python package from PyPi using pip. This is the standard method for acquiring the library. Note that for specific architectures like Raspberry Pi 1/2 and Zero, grpcio might need to be installed via the system package manager. ```shell pip3 install mavsdk ``` -------------------------------- ### GET /info/product Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/info.md Retrieves product information including vendor and product IDs and names. ```APIDOC ## GET /info/product ### Description Get product information of the system. ### Method GET ### Endpoint /info/product ### Response #### Success Response (200) - **vendor_id** (int32_t) - ID of the board vendor - **vendor_name** (string) - Name of the vendor - **product_id** (int32_t) - ID of the product - **product_name** (string) - Name of the product #### Response Example { "vendor_id": 1, "vendor_name": "ExampleVendor", "product_id": 100, "product_name": "FlightControllerX" } ``` -------------------------------- ### Run mavsdk_server Manually Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/index.md Instructions for executing the mavsdk_server binary directly from the terminal to isolate connection issues. This bypasses the automatic management by the Python library and provides raw output for debugging. ```python drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") ``` ```bash ~/.local/lib/python3.10/site-packages/mavsdk/bin/mavsdk_server udpin://0.0.0.0:14540 ``` ```python drone = System() await drone.connect() ``` -------------------------------- ### Generate API Documentation Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Installs documentation dependencies and uses the Makefile to build the HTML documentation for the project. ```bash pip3 install -r requirements-docs.txt make -C mavsdk html ``` -------------------------------- ### Install MAVSDK-Python Development Dependencies Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Installs the necessary dependencies for developing MAVSDK-Python. This includes both the standard requirements and development-specific requirements. ```shell cd ../.. pip3 install -r requirements.txt -r requirements-dev.txt ``` -------------------------------- ### FTP Plugin File Transfer Example in Python Source: https://context7.com/mavlink/mavsdk-python/llms.txt Demonstrates how to use the MAVSDK-Python FTP plugin to connect to a drone, list directory contents, and download files. Requires an external mavsdk_server and a serial connection. Outputs directory listings and handles potential errors during log listing. ```python #!/usr/bin/env python3 import asyncio from mavsdk import System async def run(): # For FTP, often need external mavsdk_server with serial connection drone = System(mavsdk_server_address="localhost", port=50051) await drone.connect(system_address="serial:///dev/ttyACM0:57600") # Wait for connection print("Waiting for drone to connect...") async for state in drone.core.connection_state(): if state.is_connected: print("-- Connected!") break # List root directory print("\n-- Listing root directory:") dir_contents = await drone.ftp.list_directory("/") for item in dir_contents: print(f" {item}") # List log directory (common paths) try: print("\n-- Listing /fs/microsd/log:") log_contents = await drone.ftp.list_directory("/fs/microsd/log") for item in log_contents: print(f" {item}") except Exception as e: print(f"Could not list logs: {e}") # Download a file # await drone.ftp.download("/fs/microsd/log/session001/log001.ulg", # "downloaded_log.ulg") if __name__ == "__main__": asyncio.run(run()) # Common autopilot paths: # / - Root directory # /fs/microsd/ - SD card root # /fs/microsd/log - Flight logs # /fs/microsd/etc - Configuration files ``` -------------------------------- ### GET /info/identification Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/info.md Retrieves the hardware identification details for the connected system. ```APIDOC ## GET /info/identification ### Description Get the identification of the system, including hardware UID and legacy UID. ### Method GET ### Endpoint /info/identification ### Response #### Success Response (200) - **hardware_uid** (string) - UID of the hardware - **legacy_uid** (uint64_t) - Legacy UID of the hardware #### Response Example { "hardware_uid": "0000000000000000", "legacy_uid": 987654321 } ``` -------------------------------- ### Connect to a Drone System using MAVSDK-Python Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Demonstrates how to connect to a drone system using the MAVSDK-Python library. It initializes a System object and establishes a connection, optionally starting the embedded mavsdk_server. The system_address parameter specifies the connection endpoint. ```python from mavsdk import System ... drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") ``` -------------------------------- ### GET /gimbal/list Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/gimbal.md Retrieves a list of all gimbals currently connected to the system. ```APIDOC ## GET /gimbal/list ### Description Returns a list of all gimbals detected on the system, allowing the user to identify valid gimbal IDs for further operations. ### Method GET ### Endpoint /gimbal/gimbal_list ### Response #### Success Response (200) - **gimbal_list** (Array) - A list of connected gimbal objects. #### Response Example { "gimbals": [ { "gimbal_id": 0 }, { "gimbal_id": 1 } ] } ``` -------------------------------- ### GET /info/flight_information Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/info.md Retrieves the current flight information of the system, including boot time, flight UID, and durations since arming and takeoff. ```APIDOC ## GET /info/flight_information ### Description Retrieves the current flight information of the system. ### Method GET ### Endpoint /info/flight_information ### Response #### Success Response (200) - **time_boot_ms** (uint32_t) - Time since system boot - **flight_uid** (uint64_t) - Flight counter - **duration_since_arming_ms** (uint32_t) - Duration since arming in ms - **duration_since_takeoff_ms** (uint32_t) - Duration since takeoff in ms #### Response Example { "time_boot_ms": 123456, "flight_uid": 1, "duration_since_arming_ms": 5000, "duration_since_takeoff_ms": 2000 } ``` -------------------------------- ### GET /log_streaming/raw Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/log_streaming.md Subscribe to raw logging messages streamed from the system. ```APIDOC ## GET /log_streaming/raw ### Description Subscribe to logging messages streamed from the connected system. ### Method GET ### Endpoint /log_streaming/raw ### Response #### Success Response (200) - **logging_raw** (LogStreamingRaw) - A message containing logged data encoded as base64. #### Response Example { "data_base64": "U29tZVVsb2dEYXRhQmFzZTY0" } ``` -------------------------------- ### CameraServer: Respond to Start Video Streaming (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/camera_server.md Responds to a start video streaming request received from SubscribeStartVideoStreaming. Requires a CameraFeedback object. Raises CameraServerError on failure. ```python async def respond_start_video_streaming(self, start_video_streaming_feedback): """Respond to start video streaming from SubscribeStartVideoStreaming. Parameters: start_video_streaming_feedback (CameraFeedback): the feedback Raises: CameraServerError: If the request fails. The error contains the reason for the failure. """ # Implementation details omitted for brevity pass ``` -------------------------------- ### Start Position Control (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/manual_control.md Initiates position control mode, typically used with joystick input. This requires regular manual control inputs and a valid position estimate (e.g., from GPS, external vision, or optical flow). Raises ManualControlError if the request fails. ```python await manual_control.start_position_control() ``` -------------------------------- ### CameraServer: Respond to Start Video (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/camera_server.md Responds to a stop video request received from SubscribeStopVideo. Requires a CameraFeedback object. Raises CameraServerError on failure. ```python async def respond_start_video(self, start_video_feedback): """Subscribe to stop video requests. Each request received should respond using StopVideoResponse Parameters: start_video_feedback (CameraFeedback): the feedback Raises: CameraServerError: If the request fails. The error contains the reason for the failure. """ # Implementation details omitted for brevity pass ``` -------------------------------- ### GET /arm_authorizer/subscribe Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/arm_authorizer_server.md Subscribes to incoming arm authorization request messages. ```APIDOC ## GET /arm_authorizer/subscribe ### Description Subscribe to arm authorization request messages. Each request received should be responded to using the RespondArmAuthorization method. ### Method GET ### Endpoint /arm_authorizer/subscribe ### Response #### Success Response (200) - **system_id** (uint32_t) - The vehicle system ID requesting authorization #### Response Example { "system_id": 1 } ``` -------------------------------- ### POST /follow_me/start Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/follow_me.md Activates the FollowMe mode. ```APIDOC ## POST /follow_me/start ### Description Starts the FollowMe mode, causing the vehicle to begin tracking the set target. ### Method POST ### Response #### Success Response (200) - **result** (Result) - Success status of the start command. ``` -------------------------------- ### Initialize MAVSDK System and Connect to Drone Source: https://context7.com/mavlink/mavsdk-python/llms.txt Demonstrates how to instantiate the System class and establish a connection to a drone using UDP. It includes logic to wait for a successful connection and verify GPS health before proceeding. ```python #!/usr/bin/env python3 import asyncio import logging from mavsdk import System logging.basicConfig(level=logging.INFO) async def run(): # Default: starts embedded mavsdk_server on port 50051 drone = System() # Connect to drone via UDP (common for simulators) await drone.connect(system_address="udpin://0.0.0.0:14540") # Wait for connection print("Waiting for drone to connect...") async for state in drone.core.connection_state(): if state.is_connected: print(f"-- Connected to drone!") break # Wait for GPS lock before flying print("Waiting for global position estimate...") async for health in drone.telemetry.health(): if health.is_global_position_ok and health.is_home_position_ok: print("-- Global position estimate OK") break if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Initialize and Connect System in MAVSDK-Python Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/system.md Demonstrates how to instantiate the System class and establish a connection to a remote drone system using a specified connection URL. ```python import asyncio from mavsdk import System async def run(): # Instantiate the system drone = System() # Connect to the drone via UDP await drone.connect(system_address="udpin://0.0.0.0:14540") # Access a plugin, e.g., telemetry async for position in drone.telemetry.position(): print(f"Position: {position}") break if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Configure MAVSDK Logging Levels Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/index.md Adjust the Python logging configuration to control the verbosity of MAVSDK-Python and mavsdk_server output. This allows developers to toggle between basic connection info, detailed debug logs, or suppressing server messages entirely. ```python import logging logging.basicConfig(level=logging.INFO) ``` ```python import logging logging.basicConfig(level=logging.DEBUG) ``` ```python import logging logging.basicConfig(level=logging.WARNING) logging.getLogger('mavsdk_server').setLevel(logging.INFO) ``` ```python import logging logging.getLogger('mavsdk_server').setLevel(logging.CRITICAL) ``` -------------------------------- ### POST /log_streaming/start Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/log_streaming.md Initiates the streaming of logging data from the system. ```APIDOC ## POST /log_streaming/start ### Description Starts the streaming of logging data. If the request fails, a LogStreamingError is raised. ### Method POST ### Endpoint /log_streaming/start ### Response #### Success Response (200) - **result** (LogStreamingResult) - Indicates success or failure of the start command. #### Error Response (500) - **error** (LogStreamingError) - Raised if the request fails (e.g., NO_SYSTEM, BUSY, TIMEOUT). ``` -------------------------------- ### Initialize and Use ActionServer in Python Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/action_server.md Demonstrates how to instantiate the ActionServer and utilize its asynchronous methods to subscribe to vehicle commands or update vehicle states. ```python from mavsdk import System from mavsdk.action_server import ActionServer async def run_server(): drone = System() await drone.connect() action_server = ActionServer(drone._async_plugin_manager) # Subscribe to arming commands async for arm_command in action_server.arm_disarm(): print(f"Arm command received: {arm_command}") # Set vehicle takeoff permission await action_server.set_allow_takeoff(True) ``` -------------------------------- ### Implement Follow Me Target Tracking in Python Source: https://context7.com/mavlink/mavsdk-python/llms.txt Demonstrates how to configure and execute the Follow Me plugin to track moving GPS coordinates. It requires an active drone connection and valid GPS telemetry, outputting movement commands to the drone. ```python #!/usr/bin/env python3 import asyncio from mavsdk import System from mavsdk.follow_me import Config, TargetLocation async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") async for state in drone.core.connection_state(): if state.is_connected: break async for health in drone.telemetry.health(): if health.is_global_position_ok and health.is_home_position_ok: break config = Config( follow_height_m=8.0, follow_distance_m=5.0, responsiveness=0.05, altitude_mode=Config.FollowAltitudeMode.TARGET_GPS, max_tangential_vel_m_s=10.0, follow_angle_deg=180.0, ) await drone.follow_me.set_config(config) await drone.action.arm() await drone.action.takeoff() await asyncio.sleep(8) await drone.follow_me.start() target_locations = [ (47.398039859999997, 8.5455725400000002), (47.398036222362471, 8.5450146439425509), (47.397825620791885, 8.5450092830163271), ] target = TargetLocation(0, 0, 0, 0, 0, 0) for lat, lon in target_locations: target.latitude_deg = lat target.longitude_deg = lon target.absolute_altitude_m = 480.0 await drone.follow_me.set_target_location(target) await asyncio.sleep(3) await drone.follow_me.stop() await drone.action.land() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### GET /transponder/subscribe Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/transponder.md Subscribes to real-time ADS-B vehicle updates. ```APIDOC ## GET /transponder/subscribe ### Description Subscribes to a stream of AdsbVehicle objects representing detected aircraft. ### Method GET ### Endpoint /transponder/subscribe ### Response #### Success Response (200) - **transponder** (AdsbVehicle) - The latest ADS-B vehicle data including ICAO address, position, altitude, and velocity. #### Response Example { "icao_address": 123456, "latitude_deg": 45.0, "longitude_deg": 10.0, "altitude_type": "PRESSURE_QNH", "absolute_altitude_m": 1500.0, "heading_deg": 90.0, "horizontal_velocity_m_s": 50.0, "vertical_velocity_m_s": 0.0, "callsign": "N123AB", "emitter_type": "UAV", "squawk": 1200, "tslc_s": 1 } ``` -------------------------------- ### Transition to Multicopter Mode (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/action.md Sends a command to transition the drone to multicopter mode. This action is specifically for VTOL vehicles and will succeed if the vehicle is already in multicopter mode. It raises an ActionError if the request fails. ```python async def transition_to_multicopter(): """ Send command to transition the drone to multicopter. The associated action will only be executed for VTOL vehicles (on other vehicle types the command will fail). The command will succeed if called when the vehicle is already in multicopter mode. * **Raises:** [**ActionError**](#mavsdk.action.ActionError) – If the request fails. The error contains the reason for the failure. """ pass ``` -------------------------------- ### Execute Basic Flight Commands with Action Plugin Source: https://context7.com/mavlink/mavsdk-python/llms.txt Shows how to use the Action plugin to perform common flight operations such as arming, takeoff, navigation to coordinates, holding position, and landing. These methods are asynchronous and handle drone state transitions. ```python #!/usr/bin/env python3 import asyncio import logging from mavsdk import System from mavsdk.action import ActionError logging.basicConfig(level=logging.INFO) async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") # Wait for connection and GPS async for state in drone.core.connection_state(): if state.is_connected: break async for health in drone.telemetry.health(): if health.is_global_position_ok and health.is_home_position_ok: break # Set takeoff altitude (default is usually 2.5m) await drone.action.set_takeoff_altitude(10.0) altitude = await drone.action.get_takeoff_altitude() print(f"Takeoff altitude set to: {altitude}m") # Arm the drone (motors will spin at idle) print("-- Arming") await drone.action.arm() # Take off to configured altitude print("-- Taking off") await drone.action.takeoff() await asyncio.sleep(10) # Fly to specific GPS coordinates # goto_location(latitude_deg, longitude_deg, altitude_amsl_m, yaw_deg) print("-- Flying to location") await drone.action.goto_location(47.397606, 8.543060, 500.0, 0) await asyncio.sleep(20) # Hold position (loiter) print("-- Holding position") await drone.action.hold() await asyncio.sleep(5) # Return to launch point print("-- Returning to launch") await drone.action.return_to_launch() await asyncio.sleep(30) # Land at current position print("-- Landing") await drone.action.land() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Manage Autopilot Parameters with MAVSDK-Python Source: https://context7.com/mavlink/mavsdk-python/llms.txt Demonstrates how to fetch all parameters, retrieve specific float parameters by name, and set parameter values. Requires a connection to a MAVSDK-compatible drone system. ```python #!/usr/bin/env python3 import asyncio from mavsdk import System async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") async for state in drone.core.connection_state(): if state.is_connected: break print("-- Fetching all parameters...") all_params = await drone.param.get_all_params() print("\nInteger parameters:") for param in all_params.int_params[:10]: print(f" {param.name}: {param.value}") print("\nFloat parameters:") for param in all_params.float_params[:10]: print(f" {param.name}: {param.value}") try: nav_acc_rad = await drone.param.get_param_float("NAV_ACC_RAD") print(f"\nNAV_ACC_RAD (waypoint acceptance radius): {nav_acc_rad}m") except Exception as e: print(f"Could not get NAV_ACC_RAD: {e}") print("\n-- Parameter operations complete") if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### GET /gimbal/attitude Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/gimbal.md Retrieves the current attitude and angular rate of a specific gimbal. ```APIDOC ## GET /gimbal/attitude ### Description Fetches the current orientation (Euler angles/quaternions) and angular velocity of the gimbal identified by the provided ID. ### Method GET ### Endpoint /gimbal/get_attitude ### Parameters #### Query Parameters - **gimbal_id** (int32_t) - Required - The unique identifier of the gimbal. ### Response #### Success Response (200) - **attitude** (Attitude) - The current attitude data including euler angles, quaternions, and angular velocity. #### Response Example { "gimbal_id": 0, "euler_angle_forward": { "roll_deg": 0.0, "pitch_deg": 0.0, "yaw_deg": 0.0 }, "angular_velocity": { "roll_rad_s": 0.0, "pitch_rad_s": 0.0, "yaw_rad_s": 0.0 }, "timestamp_us": 1625097600000 } ``` -------------------------------- ### POST /follow_me/config Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/follow_me.md Updates the FollowMe configuration parameters. ```APIDOC ## POST /follow_me/config ### Description Applies new configuration settings to the FollowMe plugin. ### Method POST ### Request Body - **config** (Config) - Required - The new configuration object. ### Request Example { "config": { "follow_height_m": 10.0, "follow_distance_m": 5.0, "responsiveness": 0.2, "altitude_mode": "TARGET_GPS" } } ``` -------------------------------- ### Mission Control Endpoints Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/mission_raw.md Endpoints to start, pause, and manage the current state of a mission. ```APIDOC ## POST /start_mission ### Description Starts the mission. A mission must be uploaded to the vehicle before this can be called. ### Method POST --- ## POST /pause_mission ### Description Pauses the mission, putting the vehicle into HOLD mode. ### Method POST --- ## POST /set_current_mission_item ### Description Sets the raw mission item index to go to. Setting to 0 restarts the mission. ### Method POST ### Parameters #### Request Body - **index** (int32_t) - Required - Index of the mission item (0-based) ``` -------------------------------- ### GET /gimbal/control_status Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/gimbal.md Retrieves the current control status of the gimbal to determine which component has primary or secondary control. ```APIDOC ## GET /gimbal/control_status ### Description Checks which system or component currently holds primary or secondary control over the gimbal. ### Method GET ### Endpoint /gimbal/get_control_status ### Parameters #### Query Parameters - **gimbal_id** (int32_t) - Required - The unique identifier of the gimbal. ### Response #### Success Response (200) - **control_status** (ControlStatus) - Object containing control mode and IDs of controlling components. #### Response Example { "gimbal_id": 0, "control_mode": "PRIMARY", "sysid_primary_control": 1, "compid_primary_control": 190 } ``` -------------------------------- ### POST /tune/play_tune Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/tune.md Sends a structured tune description to the system to be played. The tune consists of a list of song elements and a specified tempo. ```APIDOC ## POST /tune/play_tune ### Description Sends a tune to be played by the system. The tune is defined by a list of song elements and a tempo. ### Method POST ### Endpoint /tune/play_tune ### Parameters #### Request Body - **tune_description** (TuneDescription) - Required - The object containing the list of song elements and the tempo (32-255). - **song_elements** (List[SongElement]) - Required - A list of musical notes, pauses, and style modifiers. - **tempo** (int32_t) - Required - The speed of the tune. ### Request Example { "tune_description": { "song_elements": ["NOTE_C", "NOTE_E", "NOTE_G"], "tempo": 120 } } ### Response #### Success Response (200) - **result** (TuneResult) - Indicates if the tune was successfully queued for playback. #### Error Response (TuneError) - **result** (Result) - Enum value representing the failure (e.g., INVALID_TEMPO, TUNE_TOO_LONG, NO_SYSTEM). #### Response Example { "result": "SUCCESS" } ``` -------------------------------- ### Control Drone with Offboard Plugin Source: https://context7.com/mavlink/mavsdk-python/llms.txt Demonstrates how to arm a drone, enter offboard mode, and send position and velocity setpoints. It requires a connection to a MAVSDK-compatible system and handles errors during mode transitions. ```python #!/usr/bin/env python3 import asyncio import logging from mavsdk import System from mavsdk.offboard import OffboardError, PositionNedYaw, VelocityNedYaw logging.basicConfig(level=logging.INFO) async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") async for state in drone.core.connection_state(): if state.is_connected: break async for health in drone.telemetry.health(): if health.is_global_position_ok and health.is_home_position_ok: break print("-- Arming") await drone.action.arm() print("-- Setting initial setpoint") await drone.offboard.set_position_ned(PositionNedYaw(0.0, 0.0, 0.0, 0.0)) print("-- Starting offboard mode") try: await drone.offboard.start() except OffboardError as error: print(f"Offboard start failed: {error._result.result}") await drone.action.disarm() return print("-- Go 5m up") await drone.offboard.set_position_ned(PositionNedYaw(0.0, 0.0, -5.0, 0.0)) await asyncio.sleep(10) print("-- Flying forward at 2 m/s") await drone.offboard.set_velocity_ned(VelocityNedYaw(2.0, 0.0, 0.0, 0.0)) await asyncio.sleep(5) await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 0.0, 0.0, 0.0)) await drone.offboard.stop() await drone.action.land() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Manage Mission Lifecycle and Execution in MAVSDK Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/mission.md Demonstrates how to interact with the Mission class to upload, start, pause, and clear missions. These methods are asynchronous and require a connection to a vehicle. ```python from mavsdk import System import asyncio async def run_mission_control(drone): mission = drone.mission # Upload a mission plan await mission.upload_mission(mission_plan) # Start the mission await mission.start_mission() # Pause the mission await mission.pause_mission() # Clear the mission await mission.clear_mission() ``` -------------------------------- ### Start Altitude Control (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/manual_control.md Initiates altitude control mode. This requires that manual control inputs are being sent regularly. It does not depend on a valid position fix like GPS. Raises ManualControlError if the request fails. ```python await manual_control.start_altitude_control() ``` -------------------------------- ### Interact with ParamServer API Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/param_server.md Demonstrates how to use the ParamServer class to provide parameters and retrieve them asynchronously. Note that parameters must be provided before the client requests the parameter list. ```python async def manage_params(param_server): # Provide parameters await param_server.provide_param_int("SYS_ID", 1) await param_server.provide_param_float("BAT_LOW", 3.5) # Retrieve parameters val = await param_server.retrieve_param_float("BAT_LOW") print(f"Retrieved float param: {val}") # Subscribe to changes async for param in param_server.changed_param_int(): print(f"Int param changed: {param.name} = {param.value}") ``` -------------------------------- ### POST /arm_authorizer/accept Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/arm_authorizer_server.md Authorizes an arm request for a specified duration. ```APIDOC ## POST /arm_authorizer/accept ### Description Authorize arm for the specific time duration provided. ### Method POST ### Endpoint /arm_authorizer/accept ### Parameters #### Request Body - **valid_time_s** (int32_t) - Required - Time in seconds for which this authorization is valid ### Request Example { "valid_time_s": 60 } ### Response #### Success Response (200) - **result** (string) - Success confirmation #### Response Example { "result": "SUCCESS" } ``` -------------------------------- ### Request Specific Component Metadata (Python) Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/component_metadata.md This Python code demonstrates how to request metadata from a particular component identified by its component ID using the MAVSDK library. This action precedes accessing the metadata through subscriptions or the get_metadata function. Ensure the 'mavsdk' library is installed. ```python import asyncio from mavsdk import ComponentMetadata async def request_specific_component(compid): """Requests metadata from a specific component.""" try: await component_metadata.request_component(compid) print(f"Requested metadata from component {compid}.") except Exception as e: print(f"Error requesting metadata from component {compid}: {e}") # Example usage: # asyncio.run(request_specific_component(1)) ``` -------------------------------- ### Access Autopilot Shell with MAVSDK-Python Source: https://context7.com/mavlink/mavsdk-python/llms.txt Shows how to establish a shell connection to the autopilot, send commands, and asynchronously receive output. Useful for debugging and system status monitoring. ```python #!/usr/bin/env python3 import asyncio from mavsdk import System async def receive_shell_output(drone): async for output in drone.shell.receive(): print(output, end="", flush=True) async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") async for state in drone.core.connection_state(): if state.is_connected: print("Connected to drone!") break receive_task = asyncio.create_task(receive_shell_output(drone)) print("Sending shell commands...") await drone.shell.send("top once\n") await asyncio.sleep(1) await drone.shell.send("commander status\n") await asyncio.sleep(1) receive_task.cancel() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Manage Camera Operations with Camera Plugin Source: https://context7.com/mavlink/mavsdk-python/llms.txt Shows how to switch between photo and video modes, trigger photo capture, and control video recording. It includes status monitoring tasks to track camera state changes. ```python #!/usr/bin/env python3 import asyncio import logging from mavsdk import System from mavsdk.camera import CameraError, Mode async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") async for state in drone.core.connection_state(): if state.is_connected: break print("-- Setting camera to PHOTO mode") await drone.camera.set_mode(Mode.PHOTO) await asyncio.sleep(2) print("-- Taking photo") await drone.camera.take_photo() await asyncio.sleep(2) print("-- Setting camera to VIDEO mode") await drone.camera.set_mode(Mode.VIDEO) await drone.camera.start_video() await asyncio.sleep(10) await drone.camera.stop_video() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Manage Camera Focus via MAVSDK Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/camera.md Functions to control camera focus, including starting focus in/out, setting a specific range, and stopping the focus operation. These methods require a component_id and may raise a CameraError upon failure. ```python async def focus_operations(camera, component_id): await camera.focus_in_start(component_id) await camera.focus_out_start(component_id) await camera.focus_range(component_id, 50.0) await camera.focus_stop(component_id) ``` -------------------------------- ### Accessing and Modifying Parameters in MAVSDK-Python Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/param.md Demonstrates how to initialize the Param plugin and perform asynchronous operations to retrieve or update vehicle parameters. These methods require an active connection to a MAVSDK system. ```python from mavsdk import System import asyncio async def run(): drone = System() await drone.connect(system_address="udp://:14540") # Get all parameters all_params = await drone.param.get_all_params() # Set an integer parameter try: await drone.param.set_param_int("SYS_ID", 1) except Exception as e: print(f"Failed to set parameter: {e}") # Get a float parameter val = await drone.param.get_param_float("BAT_LOW_THR") print(f"Battery threshold: {val}") asyncio.run(run()) ``` -------------------------------- ### Create Git Release Tag Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Commands to switch to the main branch, pull the latest changes, and push a new version tag to the repository. ```bash git switch main git pull git tag X.Y.Z git push --tags ``` -------------------------------- ### POST /action/land Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/action.md Switches the drone to 'Land' flight mode to descend at the current position. ```APIDOC ## POST /action/land ### Description Send command to land at the current position. ### Method POST ### Endpoint /action/land ### Response #### Success Response (200) - **status** (string) - Landing sequence initiated ``` -------------------------------- ### POST /action/arm Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/action.md Sends a command to arm the drone, causing motors to spin at idle. Safety precautions are required before execution. ```APIDOC ## POST /action/arm ### Description Sends a command to arm the drone. Arming a drone normally causes motors to spin at idle. ### Method POST ### Endpoint /action/arm ### Response #### Success Response (200) - **status** (string) - Success confirmation #### Error Response - **ActionError** - If the request fails due to safety checks or system state. ``` -------------------------------- ### Mission Import Endpoints Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/mission_raw.md Endpoints for importing mission plans from strings or files in QGC or Mission Planner formats. ```APIDOC ## POST /import_mission_planner_mission_from_string ### Description Imports a Mission Planner mission in QGC WPL 110 format from a string. ### Method POST ### Parameters #### Request Body - **mission_planner_mission** (string) - Required - Mission Planner mission as string ### Response #### Success Response (200) - **mission_import_data** (MissionImportData) - The imported mission data --- ## POST /import_qgroundcontrol_mission ### Description Imports a QGroundControl mission in JSON .plan format from a file path. ### Method POST ### Parameters #### Request Body - **qgc_plan_path** (string) - Required - File path of the QGC plan ### Response #### Success Response (200) - **mission_import_data** (MissionImportData) - The imported mission data ``` -------------------------------- ### Connect and Run Multiple Telemetry Streams with Python Source: https://context7.com/mavlink/mavsdk-python/llms.txt This snippet demonstrates connecting to a drone via UDP and concurrently running multiple telemetry data streams (battery, position, GPS, flight mode, in air status) using asyncio tasks. The script runs indefinitely, continuously updating the telemetry information. Requires MAVSDK-Python and a running drone simulator or physical drone. ```python import asyncio import logging from mavsdk import System logging.basicConfig(level=logging.INFO) async def print_battery(drone): async for battery in drone.telemetry.battery(): print(f"Battery: {battery.remaining_percent:.1f}% " f"({battery.voltage_v:.2f}V)") async def print_position(drone): async for position in drone.telemetry.position(): print(f"Position: lat={position.latitude_deg:.6f}, " f"lon={position.longitude_deg:.6f}, " f"alt={position.relative_altitude_m:.2f}m") async def print_gps_info(drone): async for gps_info in drone.telemetry.gps_info(): print(f"GPS: {gps_info.num_satellites} satellites, " f"fix type: {gps_info.fix_type}") async def print_flight_mode(drone): async for flight_mode in drone.telemetry.flight_mode(): print(f"Flight mode: {flight_mode}") async def print_in_air(drone): async for in_air in drone.telemetry.in_air(): print(f"In air: {in_air}") async def run(): drone = System() await drone.connect(system_address="udpin://0.0.0.0:14540") tasks = [ asyncio.create_task(print_battery(drone)), asyncio.create_task(print_position(drone)), asyncio.create_task(print_gps_info(drone)), asyncio.create_task(print_flight_mode(drone)), asyncio.create_task(print_in_air(drone)), ] await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Generate MAVSDK-Python Code from Proto Definitions Source: https://github.com/mavlink/mavsdk-python/blob/main/README.md Executes a helper script to generate Python wrappers for MAVSDK plugins. This script utilizes the proto definitions to create the necessary code for the Python wrapper. ```shell ./other/tools/run_protoc.sh ``` -------------------------------- ### POST /mavsdk/mission_raw/upload_rally_points Source: https://github.com/mavlink/mavsdk-python/blob/main/mavsdk/source/plugins/mission_raw.md Uploads a list of rally point mission items to the connected system. This operation is asynchronous. ```APIDOC ## POST /mavsdk/mission_raw/upload_rally_points ### Description Uploads a list of rally point mission items to the connected system. This operation is asynchronous and may raise a MissionRawError if the upload fails. ### Method POST ### Endpoint /mavsdk/mission_raw/upload_rally_points ### Parameters #### Request Body - **mission_items** (array[MissionItem]) - Required - A list of MissionItem objects representing the rally points to be uploaded. ### Request Example ```json { "mission_items": [ { "latitude_deg": 47.397742, "longitude_deg": 8.545592, "altitude_m": 100.0, "speed_m_s": 10.0, "delay_s": 2.0, "is_fly_through": true, "gimbal_pitch_deg": 0.0, "camera_action": "NONE", "loiter_radius_m": 0.0, "loiter_time_s": 0.0, "camera_photo_interval_s": 0.0, "camera_photo_distance_m": 0.0, "taxi_waypoint_type": "NONE" } ] } ``` ### Response #### Success Response (200) - **None** - The operation is asynchronous and does not return a value upon success. Errors are indicated by exceptions. #### Response Example ```json null ``` ### Errors - **MissionRawError** - Raised if the upload fails. The error object contains details about the failure reason. ```