From 2816766c008b07027125571b60dc483c349082ce Mon Sep 17 00:00:00 2001 From: Julian Oes Date: Wed, 17 Sep 2025 10:08:36 +1200 Subject: [PATCH] examples: add two MavlinkDirect examples This is to demonstrate the new MavlinkDirect functionality. --- examples/mavlink_direct_receive.py | 31 ++++++++++++++++ examples/mavlink_direct_send.py | 57 ++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100755 examples/mavlink_direct_receive.py create mode 100755 examples/mavlink_direct_send.py diff --git a/examples/mavlink_direct_receive.py b/examples/mavlink_direct_receive.py new file mode 100755 index 00000000..55ecf147 --- /dev/null +++ b/examples/mavlink_direct_receive.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +import asyncio +from mavsdk import System +import json + + +async def print_messages(): + drone = System() + print("Waiting for drone to connect...") + 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 + + async for message in drone.mavlink_direct.message("ATTITUDE"): + fields = json.loads(message.fields_json) + + # Format as JSON again for the reader but this time with indenting. + fields_formatted = json.dumps(fields, indent=4) + + print(f"{message.message_name} from {message.system_id}/{message.component_id}:") + print("----") + print(f"{fields_formatted}") + print("----") + + +if __name__ == "__main__": + asyncio.run(print_messages()) diff --git a/examples/mavlink_direct_send.py b/examples/mavlink_direct_send.py new file mode 100755 index 00000000..0fc6e997 --- /dev/null +++ b/examples/mavlink_direct_send.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +import asyncio +from mavsdk import System, mavlink_direct +import json +import random + + +async def send_airspeed(): + drone = System() + print("Waiting for drone to connect...") + 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 + + await drone.mavlink_direct.load_custom_xml(""" + + + + Airspeed information from a sensor. + Sensor ID. + Calibrated airspeed (CAS). + Temperature. INT16_MAX for value unknown/not supplied. + Raw differential pressure. NaN for value unknown/not supplied. + Airspeed sensor flags. + + + + """) # noqa: E501 + + for i in range(20): + print(f"Sending airspeed {i}...") + fields = { + "id": 0, + "airspeed": random.random() * 10, + "temperature": 20 * 100, + "raw_press": 1010, + "flags": 0, + } + + message = mavlink_direct.MavlinkMessage( + message_name="AIRSPEED", + system_id=245, + component_id=25, + target_system_id=0, + target_component_id=0, + fields_json=json.dumps(fields), + ) + await drone.mavlink_direct.send_message(message) + await asyncio.sleep(0.1) + + +if __name__ == "__main__": + asyncio.run(send_airspeed())