MavlinkDirect ​
The MavlinkDirect plugin enables direct MAVLink communication with runtime message parsing and JSON field representation.
TIP
MavlinkDirect is the recommended replacement for MavlinkPassthrough. Since MAVSDK v4, MavlinkPassthrough is deprecated and only available if MAVSDK_ENABLE_MAVLINK_C_API is defined, see API changes.
INFO
The MavlinkDirect plugin is built on top of the work by Thomas Debrunner in libmav.
Overview ​
MavlinkDirect allows you to:
- Send and receive any MAVLink message
- Load custom MAVLink message definitions from XML
Quickstart ​
A complete program that connects to a vehicle and prints every GLOBAL_POSITION_INT it receives:
#include <mavsdk/mavsdk.hpp>
#include <mavsdk/plugins/mavlink_direct/mavlink_direct.hpp>
#include <chrono>
#include <iostream>
#include <thread>
using namespace mavsdk;
int main()
{
Mavsdk mavsdk{Mavsdk::Configuration{ComponentType::GroundStation}};
if (mavsdk.add_any_connection("udpin://0.0.0.0:14540") != ConnectionResult::Success) {
std::cerr << "Connection failed\n";
return 1;
}
auto system = mavsdk.first_autopilot(3.0);
if (!system) {
std::cerr << "No autopilot found\n";
return 1;
}
auto mavlink_direct = MavlinkDirect{system.value()};
auto handle = mavlink_direct.subscribe_message(
"GLOBAL_POSITION_INT", [](MavlinkDirect::MavlinkMessage message) {
std::cout << "Got " << message.message_name << ": " << message.fields_json << '\n';
});
std::this_thread::sleep_for(std::chrono::seconds(3));
mavlink_direct.unsubscribe_message(handle);
return 0;
}Against a vehicle or simulator on udpin://0.0.0.0:14540, this prints lines like:
Got GLOBAL_POSITION_INT: {"message_id":33,"message_name":"GLOBAL_POSITION_INT","alt":500000,"hdg":9000,"lat":473977420,"lon":85455940,"relative_alt":100000,"time_boot_ms":1234,"vx":0,"vy":0,"vz":0}See Building C++ Apps for how to build it, and the C++ QuickStart for setting up a simulator.
Getting at the fields ​
fields_json is just a JSON string, so you can pick it apart with the JSON library of your choice. Using nlohmann/json, the subscription above becomes:
#include <nlohmann/json.hpp>
// ...
auto handle = mavlink_direct.subscribe_message(
"GLOBAL_POSITION_INT", [](MavlinkDirect::MavlinkMessage message) {
const auto fields = nlohmann::json::parse(message.fields_json);
// The units are the ones from the MAVLink message definition:
// degrees * 1e7, and millimeters above the home position.
const double latitude_deg = fields["lat"].get<int32_t>() / 1e7;
const double longitude_deg = fields["lon"].get<int32_t>() / 1e7;
const double altitude_m = fields["relative_alt"].get<int32_t>() / 1e3;
std::cout << "Position: " << latitude_deg << ", " << longitude_deg << " at "
<< altitude_m << " m\n";
});which prints:
Position: 47.3977, 8.54559 at 100 mMAVSDK does not expose a JSON library in its headers, so add the one you want to your own build, e.g.:
find_package(nlohmann_json REQUIRED)
target_link_libraries(your_executable_name
PRIVATE
MAVSDK::mavsdk
nlohmann_json::nlohmann_json
)The sections below go through this in more detail. The complete examples are in the repository:
| Example | Shows |
|---|---|
| mavlink_direct | Subscribing to a message (GPS_RAW_INT), and stats about all arriving messages |
| mavlink_direct_sender | Sending a message (OBSTACLE_DISTANCE) |
| mavlink_direct_sender_custom | Sending a custom message (GAS_SENSOR), by loading its XML definition |
| mavlink_direct_receiver_custom | Receiving the custom message (GAS_SENSOR), by loading the same XML definition |
For Python, see MavlinkDirect in Python.
Runtime vs compile-time considerations ​
MavlinkDirect works at runtime instead of compile-time, so instead of having the C types and functions to rely on, everything has to be done using string methods. There are trade-offs with that:
Runtime pros:
- Allows extension with custom messages/dialects without re-compiling MAVSDK.
- Allows usage in language wrappers such as Python.
- MAVSDK no longer needs to carry and install the MAVLink C headers.
Runtime cons:
- API users need to look up MAVLink message definitions and don't get auto-complete.
- Enum values or flags/bits need to be assembled manually.
- The API is likely slower although that's likely negligible in C++ as long as messages are not sent/received at very high rates (benchmarks outstanding).
Load custom MAVLink XML/ MAVLink dialects ​
By default all messages from the common.xml MAVLink dialect are available, loaded in.
MavlinkDirect allows to load your own/custom MAVLink messages or other dialects.
In the example below we define and load our own message for a gas sensor. The message ID 44000 is not used by any of the public MAVLink dialects:
std::string custom_xml = R"(
<mavlink>
<messages>
<message id="44000" name="GAS_SENSOR">
<description>Gas concentration measured by a sensor.</description>
<field type="uint64_t" name="time_usec" units="us">Timestamp (time since system boot).</field>
<field type="uint8_t" name="id" instance="true">Sensor ID.</field>
<field type="float" name="co2" units="ppm">CO2 concentration.</field>
<field type="float" name="ch4" units="ppm">Methane concentration.</field>
<field type="int16_t" name="temperature" units="cdegC">Sensor temperature.</field>
</message>
</messages>
</mavlink>)";
// Load custom XML
auto xml_result = mavlink_direct.load_custom_xml(custom_xml);
if (xml_result != MavlinkDirect::Result::Success) {
std::cerr << "Failed to load custom XML: " << xml_result << std::endl;
return 1;
}Once loaded, the message can be sent by name like any other, with the fields assembled using nlohmann/json:
using json = nlohmann::json;
// ...
const json fields = {
{"time_usec", 1000000},
{"id", 0},
{"co2", 420.0},
{"ch4", 1.9},
{"temperature", 2150},
};
MavlinkDirect::MavlinkMessage message{};
message.message_name = "GAS_SENSOR";
message.system_id = config.get_system_id();
message.component_id = config.get_component_id();
message.target_system_id = 0; // Does not apply for this message
message.target_component_id = 0; // Does not apply for this message
message.fields_json = fields.dump();
auto result = mavlink_direct.send_message(message);The receiving side needs to know about the message as well. If it uses MAVSDK, it has to load the same XML, and can then subscribe to it by name and parse its fields:
void on_gas_sensor(const MavlinkDirect::MavlinkMessage& message)
{
const auto fields = json::parse(message.fields_json);
// The temperature is in cdegC, as given by the message definition.
std::cout << std::fixed << std::setprecision(1) << "GAS_SENSOR " << fields["id"].get<int>()
<< " received: " << fields["co2"].get<double>() << " ppm CO2, "
<< fields["ch4"].get<double>() << " ppm CH4, "
<< fields["temperature"].get<int>() / 100.0 << " degC" << std::endl;
}
// ...
mavlink_direct.subscribe_message("GAS_SENSOR", on_gas_sensor);INFO
Forwarding MAVSDK instances in between do not need to know about the message.
Check out the full examples on GitHub for sending and receiving.
Sending messages ​
Let's assume we are a companion computer that detects obstacles and therefore needs to send the message OBSTACLE_DISTANCE to the autopilot.
// Set up as companion computer
auto config = Mavsdk::Configuration{ComponentType::CompanionComputer};
// Connect ...
// Create MavlinkDirect plugin instance
auto mavlink_direct = MavlinkDirect{system.value()};
// Create an OBSTACLE_DISTANCE message
MavlinkDirect::MavlinkMessage obstacle_distance{};
obstacle_distance.message_name = "OBSTACLE_DISTANCE";
obstacle_distance.system_id = config.get_system_id(); // Your component's system ID
obstacle_distance.component_id = config.get_component_id(); // Your component's component ID
obstacle_distance.target_system_id = 0; // Does not apply for this message
obstacle_distance.target_component_id = 0; // Does not apply for this message
// For now we just hard-code values for demonstration purposes.
// We assume the sensor has is looking forward and has 8 segments with 10 degrees per segment,
// so 80 degrees field of view.
// On 3 segments we see an obstacle, the closest is at 7m.
//
// In a real application this JSON message content would of course be
// assembled manually, or using a json library like nlohmann/json.
obstacle_distance.fields_json = R"({
"time_usec": 12345678,
"sensor_type": 3,
"distances": [
2000, 2000, 2000, 1000, 800, 700, 2000, 2000,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535
],
"increment": 0,
"min_distance": 20,
"max_distance": 2000,
"increment_f": 10.0,
"angle_offset": -40.0,
"frame": 12
})";
while (true) {
// Send the message
auto result = mavlink_direct.send_message(obstacle_distance);
if (result == MavlinkDirect::Result::Success) {
std::cout << "OBSTACLE_DISTANCE message sent successfully" << std::endl;
} else {
std::cerr << "OBSTACLE_DISTANCE message could not be sent: " << result << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}Check the full example on GitHub.
Receiving messages ​
You can subscribe to specific message types:
// Subscribe to GLOBAL_POSITION_INT messages
auto handle = mavlink_direct.subscribe_message(
"GLOBAL_POSITION_INT",
[](MavlinkDirect::MavlinkMessage message) {
std::cout << "Received position: " << message.fields_json << std::endl;
}
);See Getting at the fields for how to parse fields_json.
Or all messages using the empty string "":
// Subscribe to all incoming messages
auto handle = mavlink_direct.subscribe_message(
"", // Empty string = all messages
[](MavlinkDirect::MavlinkMessage message) {
std::cout << "Received " << message.message_name
<< " from system " << message.system_id
<< " component " << message.component_id << std::endl;
}
);And to unsubscribe again, just use the handle from the subscription, as usual.
// Clean up subscription
mavlink_direct.unsubscribe_message(handle);Sniffing all messages ​
There is also an example that demonstrates a generic MAVLink message sniffer.
INFO
: This example uses the mavsdk.h intercept API rather than the MavlinkDirect plugin API, however, they are very similar.
JSON field format ​
MavlinkDirect represents MAVLink message fields as JSON objects:
{
"time_boot_ms": 12345,
"lat": 473977418,
"lon": -1223974560,
"alt": 100500,
"relative_alt": 50250,
"vx": 100,
"vy": -50,
"vz": 25,
"hdg": 18000
}Key points:
- All field names match the MAVLink message definition
- Numeric values preserve original MAVLink types and scaling
- Arrays are represented as JSON arrays:
[1, 2, 3, 0, 0] - NaN and infinity values are represented as
null - Extended fields are automatically included
API reference ​
See API Reference for full details.
Troubleshooting ​
Can I get more debug information? ​
Yes, set the environment variable MAVSDK_MAVLINK_DIRECT_DEBUGGING=1 before running your binary.

