Skip to content

PX4MavCtrlV4ROS Interface Documentation

Introduction

Overview: This file presents the ROS-based PX4 flight controller control interface within the RflySimSDK, built upon the MAVLink protocol. It provides fundamental encapsulation and data buffering capabilities required for PX4 drone simulation control, and supports ID-based addressing for communication management in multi-drone simulation scenarios.

This module is a ROS-compatible communication and control adapter designed by the RflySim drone simulation platform specifically for the PX4 flight controller. It adheres to the platform’s unified multi-port allocation rules, automatically generating corresponding communication ports based on the drone ID, thereby facilitating rapid configuration of multi-drone simulation networking scenarios. It implements ordered data buffering via the fifo class and manages control command encapsulation and communication address handling through the PX4MavCtrler class under the MAVLink protocol. It is suitable for simulation development scenarios on the RflySim platform—particularly those involving ROS-based autonomous missions and swarm control for PX4 drones—providing developers with a concise and unified low-level communication control interface.

Quick Start

Minimal working example; copy and modify only the minimal required configuration to run.

from RflySimSDK.ctrl import PX4MavCtrler
import time

if __name__ == "__main__":
    # Initialize the PX4 drone controller, using default local UDP connection and controlling drone ID 1
    px4_ctrl = PX4MavCtrler(CopterID=1, ip="127.0.0.1", Com="udp", port=0)

    # Start the controller message loop to receive and process data from the flight controller
    px4_ctrl.spin()

    # Keep running for 5 seconds to verify successful connection
    time.sleep(5)

    print("PX4 controller initialization and message loop execution succeeded")

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: EarthModel, ctrl.IpManager, geometry_msgs.msg, math, mavros_msgs.msg, mavros_msgs.srv, numpy, os, platform, pymavlink, pymavlink.dialects.v20, sensor_msgs.msg, socket, std_msgs.msg, struct, subprocess, sys, threading, time
  • Prerequisites: Before invoking this interface, ensure that the RflySimSDK environment has been properly configured and that the PX4 flight controller simulation environment is ready.

Core Interface Description

The module PX4MavCtrlV4ROS.py includes configuration variables, helper functions, and core business classes.

Global Constants and Enumerations

This section lists all globally accessible constants and enumerations defined in the module.

Standalone Constants

None


Global/Standalone Functions

None


fifo Class

A First-In-First-Out (FIFO) queue utility class for storing and retrieving data, adhering to the FIFO data access principle, typically used for data buffering.


__init__()

Function Description: Initializes an empty FIFO queue instance.
Parameters (Args):
None
Returns:

  • fifo instance object

Exceptions (Raises):
None


write(data)

Function Description: Appends data to the end of the FIFO queue.
Parameters (Args):

Parameter Name Type Required Default Description
data Any Yes - Data to be written into the queue

Returns:
None
Exceptions (Raises):
None

Example:

from RflySimSDK.ctrl.PX4MavCtrlV4ROS import fifo
fifo_buffer = fifo()
fifo_buffer.write(10)
fifo_buffer.write("hello")

read()

Function Description: Reads and removes the earliest-written data from the head of the FIFO queue.
Parameters (Args):
None
Returns:

  • Any: The earliest data in the queue; returns None if the queue is empty.

Exceptions (Raises):
None

Example:

from RflySimSDK.ctrl.PX4MavCtrlV4ROS import fifo
fifo_buffer = fifo()
fifo_buffer.write(10)
fifo_buffer.write("hello")
first_data = fifo_buffer.read()
# first_data will be 10

PX4MavCtrler Class

PX4 flight controller MAVLink controller, supporting two connection modes: UDP simulation communication and direct serial connection to the flight controller, enabling control and status acquisition of PX4 drones.

__init__(CopterID=1, ip='127.0.0.1', Com='udp', port=0)

Function Description: Initializes the PX4 flight controller MAVLink controller and establishes a communication connection with the flight controller based on provided parameters.
Arguments:

Parameter Name Type Default Value Description
CopterID int 1 Drone ID number. By default, the communication port is automatically calculated according to platform rules: port = 20100 + CopterID * 2 - 2.
ip str 127.0.0.1 Target IP address for sending MAVLink data. By default, data is sent to localhost; for distributed simulation, a LAN IP or broadcast address 255.255.255.255 can be specified.
Com str udp Connection mode to the Pixhawk flight controller: 'udp' indicates UDP mode for receiving MAVLink messages forwarded by CopterSim; alternatively, specify serial port names such as 'COM3' on Windows or '/dev/ttyUSB0' on Linux to enable direct serial connection mode.
port int 0 In UDP mode, if set to 0, the port is automatically calculated based on CopterID; if set to a value greater than 0, the specified port is used forcibly. In serial mode, this parameter represents the baud rate, defaulting to 57600 when set to 0.

Returns: None
Raises: None

spin()

Function Description: ROS node spinning mechanism to keep the node running and process callbacks.
Arguments: None
Returns: None
Raises: None


convert_to_payload64(payload_bytes)

Function Description: Converts input byte data into a 64-byte payload format compliant with MAVLink requirements.
Arguments:

Parameter Name Type Required Default Value Description
payload_bytes bytes Yes None Raw byte data to be converted.

Returns: 64-byte formatted payload.
Raises: None


convert_to_rosmsg(mavmsg, header)

Function Description: Converts a pymavlink-format message into the ROS standard MAVLink message format. Currently supports only MAVLink v1.0.
Arguments:

Parameter Name Type Required Default Value Description
mavmsg pymavlink.message Yes None Input pymavlink-format message.
header std_msgs/Header Yes None ROS message header used to populate the header information of the output ROS message.

Returns: Converted ROS standard MAVLink message.
Raises: None


setGPSOriLLA(LonLatAlt)

Function Description: Sets the initial GPS longitude, latitude, and altitude of the drone.
Arguments:

Parameter Name Type Required Default Value Description
LonLatAlt list[float] No [40.1540302, 116.2593683, 50] Initial GPS information in the format [longitude, latitude, altitude].

Returns: None
Raises: None


arm_px4(isArm)

Function Description: Arms or disarms the PX4 drone.
Arguments:

Parameter Name Type Required Default Value Description
isArm bool Yes None True to arm the drone; False to disarm it.

Returns: None
Raises: None


fillList(data, inLen, fill)

Function Description: Pads or truncates the input list to a specified length.
Arguments:

Parameter Name Type Required Default Value Description
data list Yes None Original input data list.
inLen int Yes None Desired length of the output list.
fill any No 0 Element used for padding when the original list length is insufficient.

Returns: A new list with length inLen, after padding or truncation.
Raises: None


InitMavLoop()

Function Description: Initializes the MAVLink communication loop, starting communication-related threads and processing logic.
Arguments: None
Returns: None
Raises: None


sendStartMsg(copterID)

Function Description: Sends a startup message to the drone with the specified ID to complete the initial handshake.
Arguments:

Parameter Name Type Required Default Value Description
copterID int No -1 Target drone ID; -1 indicates broadcasting to all drones.

Returns: None
Raises: None


waitForStartMsg()

Function Description: Waits for the drone to return a startup confirmation message, completing the initial handshake procedure.
Arguments: None
Returns: None
Raises: None


SendMavArm(isArm)

Function Description: Sends an arm/disarm command to the drone via MAVLink.
Arguments:

Parameter Name Type Required Default Value Description
isArm bool Yes None True sends the unlock command; False sends the lock command

Returns: No return value
Raises: None


initOffboard()

Function Description: Initializes PX4 Offboard mode, entering the ready state for offboard control
Args: None
Returns: No return value
Raises: None


OffboardLoop()

Function Description: Offboard control loop, continuously sending offboard control commands to the PX4 flight controller
Args: None
Returns: No return value
Raises: None


endOffboard()

Function Description: Exits PX4 Offboard mode and stops sending offboard control commands
Args: None
Returns: No return value
Raises: None


stopRun()

Function Description: Stops all running threads and loops of PX4MavCtrler, safely closing communication
Args: None
Returns: No return value
Raises: None


calcTypeMask(EnList)

Function Description: Computes the type mask for MAVLink offboard control commands based on the enabled field list
Args:

Parameter Name Type Required Default Value Description
EnList list[bool] Yes None List of enabled control fields; True at a given index indicates that the corresponding field is enabled

Returns: Computed type mask as an integer
Raises: None


SendVelNED(vx=math.nan, vy=math.nan, vz=math.nan, yawrate=math.nan)

Function Description: Sends velocity control commands in the North-East-Down (NED) coordinate frame. If a parameter is nan, the corresponding channel retains its previous control value
Args:

Parameter Name Type Required Default Value Description
vx float No math.nan Northward velocity, in m/s
vy float No math.nan Eastward velocity, in m/s
vz float No math.nan Downward velocity, in m/s
yawrate float No math.nan Yaw angular rate, in rad/s
Returns: No return value

Raises: None


SendVelFRD(vx=math.nan, vy=math.nan, vz=math.nan, yawrate=math.nan)

Function Description: Sends velocity control commands in the Forward-Right-Down (FRD) body-fixed coordinate frame. If a parameter is nan, the corresponding channel retains its previous control value
Args:

Parameter Name Type Required Default Value Description
vx float No math.nan Forward velocity, in m/s
vy float No math.nan Rightward velocity, in m/s
vz float No math.nan Downward velocity, in m/s
yawrate float No math.nan Yaw angular rate, in rad/s
Returns: No return value

Raises: None


SendPosNED(x=math.nan, y=math.nan, z=math.nan, yaw=math.nan)

Function Description: Sends position control commands in the North-East-Down (NED) coordinate frame. If a parameter is nan, the corresponding channel retains its previous control value
Args:

Parameter Name Type Required Default Value Description
x float No math.nan Northward position, in meters
y float No math.nan Eastward position, in meters
z float No math.nan Downward position, in meters
yaw float No math.nan Yaw angle, in radians
Returns: No return value

Raises: None


SendPosVelNED(PosE=[math.nan] * 3, VelE=[math.nan] * 3, yaw=math.nan, yawrate=math.nan)

Function Description: Simultaneously sends position and velocity control commands in the North-East-Down (NED) coordinate frame. If a parameter is nan, the corresponding channel retains its previous control value
Args:

Parameter Name Type Required Default Value Description
PosE list[float] No [math.nan] * 3 NED position, in order [x, y, z], in meters
VelE list[float] No [math.nan] * 3 NED velocity, in order [vx, vy, vz], in m/s
yaw float No math.nan Yaw angle, in radians
yawrate float No math.nan Yaw angular rate, in rad/s
Returns: No return value

Raises: None


local_pose_callback(msg)

Function Description: ROS local pose topic callback function, used to update stored local pose information of the UAV
Args:

Parameter Name Type Required Default Value Description
msg geometry_msgs/PoseStamped Yes None ROS local position topic message
Returns: None

Raises: None


local_vel_callback(msg)

Function Description: ROS local velocity topic callback function, used to update stored local velocity information of the drone. Arguments:

Parameter Name Type Required Default Value Description
msg geometry_msgs/TwistStamped Yes None ROS local velocity topic message
Returns: None

Raises: None


mavros_state_callback(msg)

Function Description: MAVROS state topic callback function, used to update PX4 connection status, arming status, and flight mode information. Arguments:

Parameter Name Type Required Default Value Description
msg mavros_msgs/State Yes None MAVROS state topic message
Returns: None

Raises: None


imu_callback(msg)

Function Description: IMU data topic callback function, used to update stored IMU acceleration and angular velocity information. Arguments:

Parameter Name Type Required Default Value Description
msg sensor_msgs/Imu Yes None ROS IMU topic message
Returns: None

Raises: None


gps_callback(msg)

Function Description: GPS data topic callback function, used to update stored GPS information. Arguments:

Parameter Name Type Required Default Value Description
msg sensor_msgs/NavSatFix Yes None ROS GPS topic message
Returns: None

Raises: None


q2yaw(q)

Function Description: Converts a quaternion to yaw angle. Arguments:

Parameter Name Type Required Default Value Description
q list[float]/geometry_msgs/Quaternion Yes None Input quaternion, in format [w, x, y, z] or as a quaternion message
Returns: float Yaw angle computed, in radians

Raises: None


q2Euler(q)

Function Description: Converts a quaternion to Euler angles: roll, pitch, and yaw. Arguments:

Parameter Name Type Required Default Value Description
q list[float]/geometry_msgs/Quaternion Yes None Input quaternion, in format [w, x, y, z] or as a quaternion message
Returns: tuple[float, float, float] Returns (roll, pitch, yaw) in radians

Raises: None


SendMavArm(isArm=1)

Function Description: Sends drone arm/disarm command. Arguments:

Parameter Name Type Required Default Value Description
isArm int No 1 1 indicates sending arm command; 0 indicates sending disarm command
Returns: None

Raises: None


arm()

Function Description: Executes drone arming operation. Arguments: None
Returns: None
Raises: None


disarm()

Function Description: Executes drone disarming operation. Arguments: None
Returns: None
Raises: None


offboard()

Function Description: Switches PX4 to Offboard flight mode, enabling external control command transmission. Arguments: None
Returns: None
Raises: None

land()

Function Description: Sends automatic landing command to PX4, causing the drone to enter landing mode and perform automatic landing. Arguments: None
Returns: None
Raises: None


yawSat(yaw)

Function Description: Limits the yaw angle command of the drone, constraining the maximum change rate of yaw angle. Arguments:

Parameter Name Type Required Default Value Description
yaw float Yes None Target yaw angle command to be limited, in radians

Returns: float Limited target yaw angle command
Raises: None


sendMavSetParam(param_id_str, param_value, param_type)

Function Description: Sends a parameter setting request via MAVLink to the PX4 flight controller to modify the value of a specified parameter. Arguments:

Parameter Name Type Required Default Value Description
param_id_str str Yes None Parameter name string to be set, corresponding to the PX4 flight controller’s parameter ID
param_value float/int Yes None Target parameter value to be set
param_type int Yes None MAVLink parameter type identifier, corresponding to the MAV_PARAM_TYPE enum value

Return Value (Returns): No return value
Exceptions (Raises): None


SendMavCmdLong(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0)

Function Description: Sends a MAVLink long command (COMMAND_LONG message) to the PX4 flight controller to execute various flight control commands.
Parameter List (Args):

Parameter Name Type Required Default Value Description
command int Yes None MAVLink command ID, corresponding to the MAV_CMD enum definitions
param1 float No 0 MAVLink command parameter 1; specific meaning is determined by the command ID
param2 float No 0 MAVLink command parameter 2; specific meaning is determined by the command ID
param3 float No 0 MAVLink command parameter 3; specific meaning is determined by the command ID
param4 float No 0 MAVLink command parameter 4; specific meaning is determined by the command ID
param5 float No 0 MAVLink command parameter 5; specific meaning is determined by the command ID
param6 float No 0 MAVLink command parameter 6; specific meaning is determined by the command ID
param7 float No 0 MAVLink command parameter 7; specific meaning is determined by the command ID

Return Value (Returns): No return value
Exceptions (Raises): None


SendHILCtrlMsg(ctrls=[0] * 16, idx=0)

Function Description: Sends the HIL_ACTUATOR_CONTROLS control message to PX4. This message is internally converted by PX4 into the uORB rfly_ctrl message, used for sending actuator control commands in Hardware-in-the-Loop (HIL) simulation. Corresponding MAVLink message definition: https://mavlink.io/en/messages/common.html#HIL_ACTUATOR_CONTROLS
Parameter List (Args):

Parameter Name Type Required Default Value Description
ctrls list[float] No [0] * 16 16-channel actuator/control output values, typically normalized to the flight controller’s control output range
idx int No 0 Control message group index, identifying the group to which the current control values belong

Return Value (Returns): No return value
Exceptions (Raises): None

Advanced Usage Example

Demonstrates complex collaborative scenarios (e.g., multi-agent coordination, asynchronous control, batch operations)

This example implements batch initialization, asynchronous arming, and asynchronous position control for multiple PX4 drones. It utilizes a FIFO queue to buffer multi-drone control commands, enabling asynchronous task scheduling in multi-drone collaborative scenarios:

```python import RflySimSDK.ctrl as rfly_ctrl from threading import Thread

Initialize a list of 10 drone controllers and a FIFO command buffer queue

drone_list = [] cmd_fifo = rfly_ctrl.fifo() for i in range(10): ctrl = rfly_ctrl.PX4MavCtrler(id=i+1) ctrl.InitMavLoop() ctrl.fillList(drone_list) drone_list.append(ctrl)

Asynchronous processing thread: reads commands from FIFO and broadcasts them in batches

def async_cmd_publish(): while True: cmd = cmd_fifo.read() if cmd is None: break for ctrl in drone_list[cmd['drone_range']]: ctrl.setGPSOriLLA(cmd['lat'], cmd['lon'], cmd['alt'])

Start the asynchronous processing thread

pub_thread = Thread(target=async_cmd_publish, daemon=True) pub_thread.start()

Batch complete pre-takeoff preparation and arming

start_success = True for ctrl in drone_list: if not ctrl.waitForStartMsg(): start_success = False break ctrl.sendStartMsg() ctrl.SendMavArm() if start_success: # Batch write takeoff position commands to FIFO cmd_fifo.write({'drone_range': slice(0,10), 'lat': 30.5, 'lon': 104.0, 'alt': 100})

Start message loops to process flight controller acknowledgments

for ctrl in drone_list: Thread(target=ctrl.spin, daemon=True).start()

Notes and Pitfall Avoidance Guide

  • FIFO Read/Write Thread Safety: The FIFO class itself does not include built-in multi-threading locks. Concurrent read/write operations by multiple threads may lead to issues such as duplicate instruction reads and data corruption. Users must implement their own locking mechanisms to ensure safe operations.
  • Initialization Message Interaction Sequence Requirement: The InitMavLoop function must be called first to complete communication loop initialization, followed sequentially by waitForStartMsg and sendStartMsg to complete the handshake. Incorrect ordering will cause flight controller connection failure and prevent reception of subsequent control commands.
  • Connection Validation for Batch Operations: After using fillList to add controllers in bulk, each controller’s waitForStartMsg return value must be individually validated. A single drone connection failure can affect the entire fleet mission; skipping validation and proceeding directly to subsequent operations is not allowed.
  • Differences in Arming Interface Usage: arm_px4 is a directly wrapped arming command interface, whereas SendMavArm is the standard arming interface adapted to the PX4 message protocol. For the v4 ROS communication link, SendMavArm must be used; otherwise, command parsing errors will occur.

Changelog

  • 2026-03-03: feat: SDK adds IP handling mechanism for compatibility with cloud deployment from local version
  • 2025-09-11: fix: Adds support for Linux port reuse
  • 2025-09-01: Adds a blocking spin function; external usage of this interface will suspend the daemon process
  • 2025-08-27: fix: Updates velocity subscription interface
  • 2025-03-31: fix: Resolves issue where Offboard mode cannot take off in versions after 1.13
  • 2025-01-17: fix: Resolves QoS configuration error when calling in ROS1 environment
  • 2025-01-07: fix: Sensor-related data should use SENSOR_QOS
  • 2024-11-22: fix
  • 2024-06-13: fix: Updates comments in PX4MavCtrlV4ROS.py
  • 2024-06-05: fix: Updates ROS interfaces
  • 2024-06-04: fix: Resolves ROS2 compatibility issues
  • 2024-06-04: fix: Adapts to more scenarios
  • 2024-06-04: fix: Updates library files
  • 2024-03-11: fix: Invalid interfaces need to be disabled
  • 2024-03-03: fix: Adds multicast exception handling to prevent initialization errors during network disconnection