PX4MavCtrlV4 Interface Documentation¶
Introduction¶
Overview: Provides various enumerations, utility classes, and core control classes required for offline control of PX4 flight controllers, enabling MAVLink communication integration with PX4 flight controllers under the RflySim platform.
This module serves as the core component of RflySimSDK responsible for PX4 drone communication and control. It adapts to the custom modes and offline control message formats of the PX4 flight controller based on the MAVLink protocol, supporting ID-based addressing and port-based identification for multi-drone scenarios. It conforms to the communication rules of the RflySim simulation platform, allowing target drones to be identified either by aircraft ID or via custom ports. This module is applicable to diverse scenarios such as offline trajectory planning, control algorithm development, and multi-drone cooperative mission simulation, providing a unified communication interface and parameter definition support for upper-layer control algorithms.
The module includes built-in mask generation classes for standard MAVLink offline messages, enumerations for flight controller custom modes, and key type definitions adapted to the platform's Redis communication mechanism, facilitating rapid alignment with PX4 flight controller control logic and eliminating the need for developers to manually handle low-level communication protocol details.
Quick Start¶
Minimal runnable example; copy and modify only the minimal required configuration to run.
from RflySimSDK.ctrl.PX4MavCtrlV4 import PX4MavCtrler
import time
# 1. Initialize the PX4 flight controller controller, using default local simulation environment settings with drone ID 1
mav_ctrl = PX4MavCtrler(ID=1, ip="127.0.0.1", Com="udp", port=0)
# 2. Send a global start signal to awaken all simulated drones
mav_ctrl.sendStartMsg(copterID=-1)
# 3. Wait for the start signal confirmation, blocking the program until preparation is complete
mav_ctrl.waitForStartMsg()
# 4. Example: take off, hover for 10 seconds, then exit
print("Drone started, beginning task execution")
# Add your control logic here, e.g., sending position control commands
time.sleep(10)
print("Task execution completed")
Environment and Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
copy,ctrl.DllSimCtrlAPI,ctrl.IpManager,math,numpy,os,platform,pymavlink,pymavlink.dialects.v20,socket,struct,sys,threading,time - Prerequisites: Before invoking this interface, ensure RflySimSDK environment configuration is completed and the corresponding modules are imported.
Core Interface Description¶
The module PX4MavCtrlV4.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
Enumerations¶
PX4_CUSTOM_MAIN_MODE¶
| Name | Type | Value | Description |
|---|---|---|---|
PX4_CUSTOM_MAIN_MODE_MANUAL |
int |
1 |
- |
PX4_CUSTOM_MAIN_MODE_ALTCTL |
int |
2 |
- |
PX4_CUSTOM_MAIN_MODE_POSCTL |
int |
3 |
- |
PX4_CUSTOM_MAIN_MODE_AUTO |
int |
4 |
- |
PX4_CUSTOM_MAIN_MODE_ACRO |
int |
5 |
- |
PX4_CUSTOM_MAIN_MODE_OFFBOARD |
int |
6 |
- |
PX4_CUSTOM_MAIN_MODE_STABILIZED |
int |
7 |
- |
PX4_CUSTOM_MAIN_MODE_RATTITUDE |
int |
8 |
- |
PX4_CUSTOM_MAIN_MODE_SIMPLE |
int |
9 |
- |
PX4_CUSTOM_SUB_MODE_AUTO¶
| Name | Type | Value | Description |
|---|---|---|---|
PX4_CUSTOM_SUB_MODE_AUTO_READY |
int |
1 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF |
int |
2 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_LOITER |
int |
3 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_MISSION |
int |
4 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_RTL |
int |
5 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_LAND |
int |
6 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_RTGS |
int |
7 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET |
int |
8 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND |
int |
9 |
- |
APM_COPTER_MODE¶
ArduCopter flight mode numbers, can be used with SendSetModeAPM() to switch APM multi-rotor modes.
| Name | Type | Value | Description |
|---|---|---|---|
STABILIZE |
int |
0 |
Stabilize mode |
ACRO |
int |
1 |
Acro mode |
ALT_HOLD |
int |
2 |
Altitude hold mode |
AUTO |
int |
3 |
Auto mission mode |
GUIDED |
int |
4 |
Guided mode |
LOITER |
int |
5 |
Loiter mode |
RTL |
int |
6 |
Return to launch mode |
LAND |
int |
9 |
Land mode |
APM_PLANE_MODE¶
ArduPlane flight mode numbers, can be used with SendSetModeAPM() to switch APM fixed-wing modes.
| Name | Type | Value | Description |
|---|---|---|---|
MANUAL |
int |
0 |
Manual mode |
STABILIZE |
int |
2 |
Stabilize mode |
FBWA |
int |
5 |
Fly-by-wire A mode |
FBWB |
int |
6 |
Fly-by-wire B mode |
AUTO |
int |
10 |
Auto mission mode |
RTL |
int |
11 |
Return to launch mode |
LOITER |
int |
12 |
Loiter mode |
GUIDED |
int |
15 |
Guided mode |
QLOITER |
int |
19 |
VTOL loiter mode |
APM_ROVER_MODE¶
ArduRover flight mode numbers, can be used with SendSetModeAPM() to switch APM rover/boat modes.
| Name | Type | Value | Description |
|---|---|---|---|
MANUAL |
int |
0 |
Manual mode |
STEERING |
int |
3 |
Steering assist mode |
HOLD |
int |
4 |
Hold mode |
AUTO |
int |
10 |
Auto mission mode |
RTL |
int |
11 |
Return to launch mode |
GUIDED |
int |
15 |
Guided mode |
Global/Standalone Functions¶
None
RedisKey Class¶
Key type for Redis channels; using a type ID, the corresponding channel string name can be retrieved from RedisKey.
GetRedisKey(port)¶
Function Description: Retrieves the Redis channel key name corresponding to a given port number.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
port |
Any type | Yes | - | Port number |
Return Value (Returns):
str: The Redis channel key name corresponding to the port
Exceptions (Raises):
- None
Example:
Class Variables¶
| Variable Name | Type | Value | Description |
|---|---|---|---|
SIL |
str |
SIL |
Redis channel key for Software-in-the-Loop (SIL) simulation |
SIL_TRUE |
str |
SIL_TRUE |
Redis channel key for SIL mode of real UAV |
R3D |
str |
RFLYSIM_3D |
Redis channel key for RflySim 3D visualization |
SIL_RECV |
str |
SIL_RECV |
Redis channel key for SIL receive channel |
SIL_TRUE_RECV |
str |
SIL_TRUE_RECV |
Redis channel key for SIL receive channel of real UAV |
fifo Class¶
First-In-First-Out (FIFO) queue for storing and accessing data elements in the order they were added.
__init__()¶
Function Description: Initializes an empty FIFO queue.
Parameters (Args):
None
Returns:
- An instance of the fifo class
Exceptions (Raises):
None
write(data)¶
Function Description: Appends a new data element to the end of the queue.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
data |
Any |
Yes | - | Data element to be added to the queue |
Returns:
- None
Exceptions (Raises):
None
read()¶
Function Description: Removes and returns the earliest-added data element from the front of the queue, following the FIFO principle.
Parameters (Args):
None
Returns:
- The earliest-added data element at the front of the queue; its type matches the original input type
Exceptions (Raises):
None
Example:
# Create a FIFO queue
queue = fifo()
# Write data
queue.write(10)
queue.write("test_data")
# Read data in the order it was written
first_data = queue.read()
second_data = queue.read()
PosTypeMask Class¶
Generates a type mask bitmap for PX4 offboard control messages, corresponding to the POSITION_TARGET_TYPEMASK definition in the MAVLink protocol. It specifies which control inputs should be ignored by the flight controller.
__init__(ignore_all=False)¶
Function Description: Initializes the mask object. By default, it configures the mask for velocity + yaw rate control mode. If ignore_all is set to True, all offboard control inputs will be ignored.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
ignore_all |
bool |
No | False |
If True, all offboard control inputs are ignored; if False, the default velocity + yaw rate control mode is used |
Returns:
- An instance of the PosTypeMask class
Exceptions (Raises):
None
mask()¶
Function Description: Retrieves the computed final type mask value.
Parameters (Args):
None
Returns:
- int: The final offboard control type mask bitmap, ready to be used directly in generating MAVLink position control messages
Exceptions (Raises):
None
Example:
from RflySimSDK.ctrl import PosTypeMask
# Create a default mask object for velocity + yaw rate mode
mask_obj = PosTypeMask()
# Get the mask value
type_mask = mask_obj.mask()
# Create a mask object that ignores all control inputs
ignore_all_mask = PosTypeMask(ignore_all=True).mask()
AttTypeMask Class¶
【Reference: Previous English Translation】
PX4MavCtrlV4 Interface Documentation¶
Introduction¶
Overview: Provides various enumerations, utility classes, and core control classes required for offline control of PX4 flight controllers, enabling MAVLink communication integration with PX4 flight controllers under the RflySim platform.
This module serves as the core component of RflySimSDK responsible for PX4 drone communication and control. It adapts to the custom modes and offline control message formats of the PX4 flight controller based on the MAVLink protocol, supporting ID-based addressing and port-based identification for multi-drone scenarios. It conforms to the communication rules of the RflySim simulation platform, allowing target drones to be identified either by aircraft ID or via custom ports. This module is applicable to diverse scenarios such as offline trajectory planning, control algorithm development, and multi-drone cooperative mission simulation, providing a unified communication interface and parameter definition support for upper-layer control algorithms.
The module includes built-in mask generation classes for standard MAVLink offline messages, enumerations for flight controller custom modes, and key type definitions adapted to the platform’s Redis communication mechanism, facilitating rapid alignment with PX4 flight controller control logic and eliminating the need for developers to manually handle low-level communication protocol details.
Quick Start¶
Minimal runnable example; copy and modify only the minimal required configuration to run.
from RflySimSDK.ctrl.PX4MavCtrlV4 import PX4MavCtrler
import time
# 1. Initialize the PX4 flight controller controller, using default local simulation environment settings with drone ID 1
mav_ctrl = PX4MavCtrler(ID=1, ip="127.0.0.1", Com="udp", port=0)
# 2. Send a global start signal to awaken all simulated drones
mav_ctrl.sendStartMsg(copterID=-1)
# 3. Wait for the start signal confirmation, blocking the program until preparation is complete
mav_ctrl.waitForStartMsg()
# 4. Example: take off, hover for 10 seconds, then exit
print("Drone started, beginning task execution")
# Add your control logic here, e.g., sending position control commands
time.sleep(10)
print("Task execution completed")
Environment and Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
copy,ctrl.DllSimCtrlAPI,ctrl.IpManager,math,numpy,os,platform,pymavlink,pymavlink.dialects.v20,socket,struct,sys,threading,time - Prerequisites: Before invoking this interface, ensure RflySimSDK environment configuration is completed and the corresponding modules are imported.
Core Interface Description¶
The module PX4MavCtrlV4.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
Enumerations¶
PX4_CUSTOM_MAIN_MODE¶
| Name | Type | Value | Description |
|---|---|---|---|
PX4_CUSTOM_MAIN_MODE_MANUAL |
int |
1 |
- |
PX4_CUSTOM_MAIN_MODE_ALTCTL |
int |
2 |
- |
PX4_CUSTOM_MAIN_MODE_POSCTL |
int |
3 |
- |
PX4_CUSTOM_MAIN_MODE_AUTO |
int |
4 |
- |
PX4_CUSTOM_MAIN_MODE_ACRO |
int |
5 |
- |
PX4_CUSTOM_MAIN_MODE_OFFBOARD |
int |
6 |
- |
PX4_CUSTOM_MAIN_MODE_STABILIZED |
int |
7 |
- |
PX4_CUSTOM_MAIN_MODE_RATTITUDE |
int |
8 |
- |
PX4_CUSTOM_MAIN_MODE_SIMPLE |
int |
9 |
- |
PX4_CUSTOM_SUB_MODE_AUTO¶
| Name | Type | Value | Description |
|---|---|---|---|
PX4_CUSTOM_SUB_MODE_AUTO_READY |
int |
1 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF |
int |
2 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_LOITER |
int |
3 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_MISSION |
int |
4 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_RTL |
int |
5 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_LAND |
int |
6 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_RTGS |
int |
7 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET |
int |
8 |
- |
PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND |
int |
9 |
- |
Global/Standalone Functions¶
None
RedisKey Class¶
Key type for Redis channels; using a type ID, the corresponding channel string name can be retrieved from RedisKey.
GetRedisKey(port)¶
Function Description: Retrieves the Redis channel key name corresponding to a given port number.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
port |
Any type | Yes | - | Port number |
Return Value (Returns):
str: The Redis channel key name corresponding to the port
Exceptions (Raises):
- None
Example:
Class Variables¶
| Variable Name | Type | Value | Description |
|---|---|---|---|
SIL |
str |
SIL |
Redis channel key for Software-in-the-Loop (SIL) simulation |
SIL_TRUE |
str |
SIL_TRUE |
Redis channel key for SIL mode of real UAV |
R3D |
str |
RFLYSIM_3D |
Redis channel key for RflySim 3D visualization |
SIL_RECV |
str |
SIL_RECV |
Redis channel key for SIL receive channel |
SIL_TRUE_RECV |
str |
SIL_TRUE_RECV |
Redis channel key for SIL receive channel of real UAV |
fifo Class¶
First-In-First-Out (FIFO) queue for storing and accessing data elements in the order they were added.
__init__()¶
Function Description: Initializes an empty FIFO queue.
Parameters (Args):
None
Returns:
- An instance of the fifo class
Exceptions (Raises):
None
write(data)¶
Function Description: Appends a new data element to the end of the queue.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
data |
Any |
Yes | - | Data element to be added to the queue |
Returns:
- None
Exceptions (Raises):
None
read()¶
Function Description: Removes and returns the earliest-added data element from the front of the queue, following the FIFO principle.
Parameters (Args):
None
Returns:
- The earliest-added data element at the front of the queue; its type matches the original input type
Exceptions (Raises):
None
Example:
# Create a FIFO queue
queue = fifo()
# Write data
queue.write(10)
queue.write("test_data")
# Read data in the order it was written
first_data = queue.read()
second_data = queue.read()
PosTypeMask Class¶
Generates a type mask bitmap for PX4 offboard control messages, corresponding to the POSITION_TARGET_TYPEMASK definition in the MAVLink protocol. It specifies which control inputs should be ignored by the flight controller.
__init__(ignore_all=False)¶
Function Description: Initializes the mask object. By default, it configures the mask for velocity + yaw rate control mode. If ignore_all is set to True, all offboard control inputs will be ignored.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
ignore_all |
bool |
No | False |
If True, all offboard control inputs are ignored; if False, the default velocity + yaw rate control mode is used |
Returns:
- An instance of the PosTypeMask class
Exceptions (Raises):
None
mask()¶
Function Description: Retrieves the computed final type mask value.
Parameters (Args):
None
Returns:
- int: The final offboard control type mask bitmap, ready to be used directly in generating MAVLink position control messages
Exceptions (Raises):
None
AttTypeMask Class¶
Generates a type mask bitmap for offboard control messages, corresponding to the ATTITUDE_TARGET_TYPEMASK definition in the MAVLink protocol. It is commonly used in PX4 drone offboard control scenarios to mark control quantities that should be ignored.
__init__(ignore_all=False)¶
Function Description: Initializes the mask object. By default, it configures the mask for attitude + throttle control mode. When ignore_all is set to True, all offboard control quantities will be ignored.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
ignore_all |
bool |
No | False |
Whether to ignore all offboard control quantities; when set to True, all control bits are marked as ignored |
Return Value (Returns):
AttTypeMaskinstance object
Exceptions (Raises): None
mask()¶
Function Description: Retrieves the computed final mask value, used for sending offboard control messages to the flight controller.
Parameters (Args):
None
Return Value (Returns):
int: The computed control mask value
Exceptions (Raises): None
Example:
from RflySimSDK.ctrl import AttTypeMask
# Create a default attitude throttle mode mask
att_mask = AttTypeMask()
mask_val = att_mask.mask()
# Mask that ignores all control quantities
ignore_mask = AttTypeMask(ignore_all=True)
ignore_val = ignore_mask.mask()
PX4ExtMsg Class¶
This class is used to represent PX4 flight controller extension messages, serving as the base container class for PX4 extension message-related data in RflySimSDK.
__init__()¶
Function Description: Initializes a PX4ExtMsg class instance
Parameters (Args):
No parameters
Return Value (Returns):
PX4ExtMsginstance object
Exceptions (Raises): None
PX4MavCtrler Class¶
Creates a MAVLink communication control instance for the PX4 flight controller, supporting multiple communication modes such as simulation, direct connection to real hardware, and serial connection.
__init__(ID=1, ip='127.0.0.1', Com='udp', port=0)¶
Function Description: Initializes a PX4 flight controller MAVLink communication instance, configuring the corresponding communication mode and connection parameters based on the input parameters.
Parameters (Args):
| Parameter Name | Type | Default Value | Description |
|---|---|---|---|
| ID | - | 1 | Aircraft ID or port number: ID ≤ 10000 indicates the CopterID of the aircraft; ID > 10000 indicates the communication port number port (a transitional definition for backward compatibility); in COM and Direct modes, it only represents the aircraft ID. |
| ip | str | 127.0.0.1 | Target IP address for data transmission: defaults to localhost 127.0.0.1; for distributed simulation, specify a LAN IP or broadcast address 255.255.255.255; in Redis mode, this is the server address. |
| Com | str | udp | Connection mode with the flight controller:udp: Default UDP mode; receives MAVLink messages forwarded by CopterSim, uses port for sending and port+1 for receiving;COMx//dev/ttyxxx: Serial port connection mode; on Windows, specifies COM port names; on Linux, specifies device paths, connecting to the flight controller via USB or telemetry module;Direct: UDP direct connection mode (real-machine mode); uses the same port for both sending and receiving;redis: Redis communication mode; exchanges data via a Redis server. |
| port | int | 0 | Port/baudrate configuration: UDP mode: 0 means automatically computing the port as port = 20100 + CopterID * 2 - 2; values greater than 0 force usage of the specified port;Serial mode: specifies the baud rate; 0 defaults to 57600;Direct mode: specifies the shared port number for sending and receiving; Redis mode: specifies the Redis server port; 0 defaults to the standard port 6379. |
Return Value (Returns): None
Exceptions (Raises): None
fillList(data, inLen, fill="0")¶
Function Description: Pads the input list to a specified length; if shorter, fills with the specified value.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| data | Any | Yes | None | Input list to be processed |
| inLen | Any | Yes | None | Target length of the list |
| fill | Any | No | "0" | Value used for padding; defaults to "0" |
Return Value (Returns): A list padded to length inLen
Exceptions (Raises): None
sendStartMsg(copterID=-1)¶
Function Description: Sends a start signal over the network for drones that have called waitForStartMsg() to receive and begin execution. When copterID = -1, all drones will start; when copterID > 0, only the drone with the specified ID will start.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| copterID | Any | No | -1 | ID of the drone(s) to start; default -1 means starting all drones |
Return Value (Returns): None
Exceptions (Raises): None
waitForStartMsg()¶
Function Description: Blocks program execution until a start signal from sendStartMsg() is received, after which execution continues.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
initPointMassModel(intAlt=0, intState=[0, 0, 0])¶
Function Description: Initializes and starts the drone point-mass model for drone control. intAlt is the initial altitude (in meters) of the aircraft in the UE4 map, which can be obtained from CopterSim or UE4; intState contains the initial X position (meters), Y position (meters), and yaw angle (degrees) of the aircraft, consistent with the values displayed on the CopterSim interface.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| intAlt | Any | No | 0 | Initial altitude in meters; default is 0 |
| intState | Any | No | [0, 0, 0] | Initial state [X position, Y position, yaw angle]; default is [0, 0, 0] |
Return Value (Returns): None
Exceptions (Raises): None
EndPointMassModel()¶
Function Description: Stops the point-mass model execution.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
yawSat(yaw)¶
Function Description: Saturates the input yaw angle to the range [-π, π].
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| yaw | Any | Yes | None | Input yaw angle in radians |
Return Value (Returns): Yaw angle saturated within [-π, π]
Exceptions (Raises): None
PointMassModelLoop()¶
Function Description: Infinite loop function for the point-mass model, continuously updating the model state.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
sendUE4PosNew(copterID=1, vehicleType=3, PosE=[0, 0, 0], AngEuler=[0, 0, 0], VelE=[0, 0, 0], PWMs=[0] * 8, runnedTime=-1, windowID=-1)¶
Function Description: Sends position and attitude information to RflySim3D to create a new 3D model or update the state of an existing model. The data is encapsulated and transmitted according to the RflySim3D-defined structure format.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| copterID | Any | No | 1 | Drone ID; default value is 1 |
| vehicleType | Any | No | 3 | Vehicle type; default value is 3 |
| PosE | Any | No | [0, 0, 0] | Vehicle position in Earth-fixed NED frame, in meters; default value is [0, 0, 0] |
| AngEuler | Any | No | [0, 0, 0] | Vehicle roll, pitch, and yaw Euler angles, in radians; default value is [0, 0, 0] |
| VelE | Any | No | [0, 0, 0] | Vehicle velocity in Earth-fixed frame; default value is [0, 0, 0] |
| PWMs | Any | No | [0] * 8 | PWM/speed information for 8 motors; default is all zeros |
| runnedTime | Any | No | -1 | Current timestamp, in seconds; default value -1 indicates automatic use of the current time |
| windowID | Any | No | -1 | Target RflySim3D window ID; default -1 indicates sending to all windows |
Return Value (Returns): None
Exceptions (Raises): None
InitTrueDataLoop()¶
Function Description: Initializes the UDP real-data listening loop from CopterSim, receiving data via port series 30100.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
EndTrueDataLoop()¶
Function Description: Ends the real-data reception mode and stops the real-data listening loop.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
SendOffAll(type_mask=PosTypeMask(), coordinate_frame=1, pos=[0, 0, 0], vel=[0, 0, 0], acc=[0, 0, 0], yaw=0, yawrate=0)¶
Function Description: Sends position control commands to the PX4 flight controller via the MAVLink protocol.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| type_mask | Any | No | PosTypeMask() | Position control type mask, used to enable/disable specific control inputs |
| coordinate_frame | Any | No | 1 | Coordinate frame ID; default value 1 indicates global frame |
| pos | Any | No | [0, 0, 0] | Desired position; default value is [0, 0, 0] |
| vel | Any | No | [0, 0, 0] | Desired velocity; default value is [0, 0, 0] |
| acc | Any | No | [0, 0, 0] | Desired acceleration; default value is [0, 0, 0] |
| yaw | Any | No | 0 | Desired yaw angle; default value is 0 |
| yawrate | Any | No | 0 | Desired yaw rate; default value is 0 |
Return Value (Returns): None
Exceptions (Raises): None
SendAttAll(type_mask=AttTypeMask(), q=[1, 0, 0, 0], body_rate=[0, 0, 0], thrust=0)¶
Function Description: Sends attitude control commands to the PX4 flight controller via the MAVLink protocol.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| type_mask | Any | No | AttTypeMask() | Attitude control type mask, used to enable/disable specific control inputs |
| q | Any | No | [1, 0, 0, 0] | Desired attitude quaternion; default is unit quaternion |
| body_rate | Any | No | [0, 0, 0] | Desired body angular rate; default value is [0, 0, 0] |
| thrust | Any | No | 0 | Desired thrust; default value is 0 |
Return Value (Returns): None
Exceptions (Raises): None
InitMavLoop(UDPMode=2)¶
Function Description: Initializes the MAVLink listening loop from CopterSim, supporting multiple working modes: 0 and 1 correspond to UDP_Full and UDP_Simple modes respectively, 2 and 3 correspond to MAVLink_Full and MAVLink_Simple modes respectively, 4 is MAVLink_NoSend mode, 5 is MAVLink_NoGPS mode, 6 is MAVLink_NoVision mode, with the default mode being 2 (MAVLink_Full mode). Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| UDPMode | Any | No | 2 | Working mode number, default value is 2 (MAVLink_Full mode) |
Return Value (Returns): None Exceptions (Raises): None
endMavLoop()¶
Function Description: Functionally identical to stopRun(), stops message listening from port 20100 or serial port.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
SendVisionPosition(x, y, z, yaw)¶
Function Description: Sends the UAV position and yaw angle obtained from motion capture or visual measurement to the PX4 flight controller, used for visual odometry/motion capture positioning. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | Any | Yes | None | X-direction position from motion capture/visual measurement |
| y | Any | Yes | None | Y-direction position from motion capture/visual measurement |
| z | Any | Yes | None | Z-direction position from motion capture/visual measurement |
| yaw | Any | Yes | None | Yaw angle from motion capture/visual measurement |
Return Value (Returns): None Exceptions (Raises): None
SendHILGps(lat=40.1540302, lon=116.2593683, alt=50, vel=0, vn=0, ve=0, vd=0, cog=0, time_usec=-1, eph=0.3, epv=0.4, fix_type=3, satellites_visible=15)¶
Function Description: Sends GPS information in Hardware-in-the-Loop (HIL) mode to PX4. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| lat | None | No | 40.1540302 | GPS latitude, in degrees |
| lon | None | No | 116.2593683 | GPS longitude, in degrees |
| alt | None | No | 50 | GPS altitude, in meters |
| vel | None | No | 0 | GPS ground speed, in m/s |
| vn | None | No | 0 | Northward velocity, in m/s |
| ve | None | No | 0 | Eastward velocity, in m/s |
| vd | None | No | 0 | Downward velocity, in m/s |
| cog | None | No | 0 | Course over ground, in degrees |
| time_usec | None | No | -1 | Timestamp in microseconds; if -1, uses the current synchronized time |
| eph | None | No | 0.3 | Horizontal dilution of precision (HDOP) |
| epv | None | No | 0.4 | Vertical dilution of precision (VDOP) |
| fix_type | None | No | 3 | GPS fix type; 3 indicates 3D positioning |
| satellites_visible | None | No | 15 | Number of visible satellites |
Return Value (Returns): None Exceptions (Raises): None
SendRedisData(key, buf)¶
Function Description: Sends specified data via Redis. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| key | None | Yes | None | Redis key name for the data |
| buf | None | Yes | None | Data buffer to be sent |
Return Value (Returns): None Exceptions (Raises): None
SendBuf(buf)¶
Function Description: Sends a data buffer to PX4. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| buf | None | Yes | None | Byte data buffer to be sent |
Return Value (Returns): None Exceptions (Raises): None
SendBufTrue(buf, port=None)¶
Function Description: Sends a complete data buffer via a specified port. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| buf | None | Yes | None | Byte data buffer to be sent |
| port | None | No | None | Target port number; if None, uses the default port |
Return Value (Returns): None Exceptions (Raises): None
sat(inPwm=0, thres=1)¶
Function Description: Applies saturation limiting to the input value; if the input exceeds the threshold range, it is clamped within the threshold bounds. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| inPwm | None | No | 0 | Input value to be saturated |
| thres | None | No | 1 | Saturation threshold; maximum absolute value allowed |
Return Value (Returns): Saturated input value Exceptions (Raises): None
SendMavCmdLong(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0)¶
Function Description: Sends a COMMAND_LONG type MAVLink command to PX4. For MAVLink command definitions, refer to the official documentation: https://mavlink.io/en/messages/common.html#COMMAND_LONG and https://mavlink.io/en/messages/common.html#MAV_CMD Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| command | None | Yes | None | MAVLink command ID, corresponding to a MAV_CMD enum value |
| param1 | None | No | 0 | Command parameter 1 |
| param2 | None | No | 0 | Command parameter 2 |
| param3 | None | No | 0 | Command parameter 3 |
| param4 | None | No | 0 | Command parameter 4 |
| param5 | None | No | 0 | Command parameter 5 |
| param6 | None | No | 0 | Command parameter 6 |
| param7 | None | No | 0 | Command parameter 7 |
Return Value (Returns): None Exceptions (Raises): None
SendMavCmdLongNEW(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0, target_system=None, target_component=1, confirmation=0, force_send=False)¶
Function Description: Sends a MAVLink COMMAND_LONG command to PX4. PX4 converts the COMMAND_LONG into a uORB vehicle_command and logs it to ULog. For MAVLink command definitions, refer to the official documentation: COMMAND_LONG and MAV_CMD.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| command | None | Yes | None | MAVLink command ID, corresponding to a MAV_CMD enum value |
| param1 | None | No | 0 | Command parameter 1 |
| param2 | None | No | 0 | Command parameter 2 |
| param3 | None | No | 0 | Command parameter 3 |
| param4 | None | No | 0 | Command parameter 4 |
| param5 | None | No | 0 | Command parameter 5 |
| param6 | None | No | 0 | Command parameter 6 |
| param7 | None | No | 0 | Command parameter 7 |
| target_system | None | No | None | Target system ID; uses the default target system if None |
| target_component | None | No | 1 | Target component ID |
| confirmation | None | No | 0 | Confirmation sequence number, used for command acknowledgment |
| force_send | bool | No | False | Whether to force sending the command even if not connected |
Return Value (Returns): None Exceptions (Raises): None
SendFaultEvent(fault_id, params=None, action=1, seq=0, vehicle_id=None, sim_id=0, command=MAV_CMD_USER_1)¶
Function Description: Sends fault event information for recording fault injection in simulations. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| fault_id | int | Yes | None | Fault ID, identifying the fault type |
| params | None | No | None | Fault parameter information |
| action | int | No | 1 | Fault action: 1 for injecting a fault, 0 for clearing a fault |
| seq | int | No | 0 | Fault event sequence number |
| vehicle_id | int | No | None | Target UAV ID; uses the current UAV ID if None |
| sim_id | int | No | 0 | Simulation ID, used to distinguish between multi-vehicle simulations |
| command | int | No | MAV_CMD_USER_1 | MAVLink command ID used; defaults to MAV_CMD_USER_1 |
Return Value (Returns): None Exceptions (Raises): None
ClearFault(fault_id, seq=0, vehicle_id=None, sim_id=0, command=MAV_CMD_USER_1)¶
Function Description: Clears/ends a specified fault. Writes a record with action=0, facilitating post-processing to define the fault time window.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| fault_id | int | Yes | None | Fault ID to be cleared |
| seq | int | No | 0 | Fault event sequence number |
| vehicle_id | int | No | None | Target UAV ID; uses the current UAV ID if None |
| sim_id | int | No | 0 | Simulation ID, used to distinguish between multi-vehicle simulations |
| command | int | No | MAV_CMD_USER_1 | MAVLink command ID used; defaults to MAV_CMD_USER_1 |
Return Value (Returns): None Exceptions (Raises): None
SendQgcCmdLong(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0)¶
Function Description: Sends a COMMAND_LONG command to the QGroundControl ground station.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| command | None | Yes | None | MAVLink command ID, corresponding to a MAV_CMD enum value |
| param1 | None | No | 0 | Command parameter 1 |
| param2 | None | No | 0 | Command parameter 2 |
| param3 | None | No | 0 | Command parameter 3 |
| param4 | None | No | 0 | Command parameter 4 |
| param5 | None | No | 0 | Command parameter 5 |
| param6 | None | No | 0 | Command parameter 6 |
| param7 | None | No | 0 | Command parameter 7 |
Return Value (Returns): None
Exceptions (Raises): None
sendMavOffboardCmd(type_mask, coordinate_frame, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate)¶
Function Description: Sends an offboard control command to PX4, corresponding to the MAVLink SET_POSITION_TARGET_LOCAL_NED message. For message definitions, refer to: https://mavlink.io/en/messages/common.html#SET_POSITION_TARGET_LOCAL_NED
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| type_mask | None | Yes | None | Offboard control type mask, indicating which control inputs are active |
| coordinate_frame | None | Yes | None | Coordinate frame, typically LOCAL_NED |
| x | None | Yes | None | X-direction position/velocity/acceleration command, determined by type_mask |
| y | None | Yes | None | Y-direction position/velocity/acceleration command, determined by type_mask |
| z | None | Yes | None | Z-direction position/velocity/acceleration command, determined by type_mask |
| vx | None | Yes | None | X-direction velocity command, determined by type_mask |
| vy | None | Yes | None | Y-direction velocity command, determined by type_mask |
| vz | None | Yes | None | Z-direction velocity command, determined by type_mask |
| afx | None | Yes | None | X-direction acceleration command, determined by type_mask |
| afy | None | Yes | None | Y-direction acceleration command, determined by type_mask |
| afz | None | Yes | None | Z-direction acceleration command, determined by type_mask |
| yaw | None | Yes | None | Yaw angle command |
| yaw_rate | None | Yes | None | Yaw rate command |
Return Value (Returns): None
Exceptions (Raises): None
TypeMask(EnList)¶
Function Description: Generates the type_mask bitmap for offboard control messages based on the required active control inputs. For bitmap definitions, refer to: https://mavlink.io/en/messages/common.html#POSITION_TARGET_TYPEMASK
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| EnList | None | Yes | None | List of control inputs to be enabled; contains the names of the active control quantities |
Return Value (Returns): The computed type_mask bitmap
Exceptions (Raises): None
sendMavOffboardAPI(type_mask=0, coordinate_frame=0, pos=[0, 0, 0], vel=[0, 0, 0], acc=[0, 0, 0], yaw=0, yawrate=0)¶
Function Description: Encapsulated offboard control API that sends offboard control commands to PX4, corresponding to the MAVLink SET_POSITION_TARGET_LOCAL_NED message. For message definitions, refer to: https://mavlink.io/en/messages/common.html#SET_POSITION_TARGET_LOCAL_NED
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| type_mask | None | No | 0 | Offboard control type mask, indicating which control inputs are active |
| coordinate_frame | None | No | 0 | Coordinate frame, defaults to LOCAL_NED |
| pos | None | No | [0, 0, 0] | Position command, formatted as [x, y, z] |
| vel | None | No | [0, 0, 0] | Velocity command, formatted as [vx, vy, vz] |
| acc | None | No | [0, 0, 0] | Acceleration command, formatted as [afx, afy, afz] |
| yaw | None | No | 0 | Yaw angle command |
| yawrate | None | No | 0 | Yaw rate command |
Return Value (Returns): None
Exceptions (Raises): None
sendUDPSimpData(ctrlMode, ctrls)¶
Function Description: Sends simplified control data via UDP
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| ctrlMode | None | Yes | None | Control mode |
| ctrls | None | Yes | None | Array of control inputs |
Return Value (Returns): None
Exceptions (Raises): None
sendPX4UorbRflyCtrl(data=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], modes=1, flags=1)¶
Function Description: Sends Rfly-customized PX4 uORB control messages
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| data | None | No | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] | 16-dimensional control data array |
| modes | None | No | 1 | Control mode identifier |
| flags | None | No | 1 | Control flags |
Return Value (Returns): None
Exceptions (Raises): None
SendVelNED(vx, vy, vz, yawrate=math.nan)¶
Function Description: Sends target drone velocity (m/s) and yaw rate (rad/s) in the geographic North-East-Down (NED) coordinate frame to PX4. Note: when the drone ascends, vz < 0.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| vx | float | Yes | math.nan | North-direction velocity in NED frame; NaN indicates this axis is not controlled |
| vy | float | Yes | math.nan | East-direction velocity in NED frame; NaN indicates this axis is not controlled |
| vz | float | Yes | math.nan | Down-direction velocity in NED frame; NaN indicates this axis is not controlled |
| yawrate | float | No | math.nan | Target yaw rate; NaN indicates yaw rate is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendVelNEDNoYaw(vx, vy, vz)¶
Function Description: Sends the target drone velocity in the geographic North-East-Down (NED) coordinate system (unit: m/s) to PX4, without controlling yaw. When the drone flies upward, vz < 0.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| vx | float | Yes | None | Northward velocity in NED frame; NaN indicates no control for this axis |
| vy | float | Yes | None | Eastward velocity in NED frame; NaN indicates no control for this axis |
| vz | float | Yes | None | Downward velocity in NED frame; NaN indicates no control for this axis |
Return Value (Returns): None
Exceptions (Raises): None
SendVelFRD(vx, vy, vz, yawrate=math.nan)¶
Function Description: Sends the target drone velocity in the body Front-Right-Down (FRD) coordinate system (unit: m/s) to PX4, and controls yaw angular rate (unit: rad/s). When the drone flies upward, vz < 0.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| vx | float | Yes | math.nan | Forward velocity in FRD frame; NaN indicates no control for this axis |
| vy | float | Yes | math.nan | Rightward velocity in FRD frame; NaN indicates no control for this axis |
| vz | float | Yes | math.nan | Downward velocity in FRD frame; NaN indicates no control for this axis |
| yawrate | float | No | math.nan | Target yaw angular rate; NaN indicates no yaw rate control |
Return Value (Returns): None
Exceptions (Raises): None
SendAttPX4(att=[0, 0, 0, 0], thrust=0.5, CtrlFlag=0, AltFlg=0)¶
Function Description: Sends the target drone attitude in the body Front-Right-Down (FRD) coordinate system to PX4.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| att | list/array | No | [0, 0, 0, 0] | Target attitude quaternion, format: [w, x, y, z] |
| thrust | float | No | 0.5 | Thrust value, typically in range [0, 1] |
| CtrlFlag | int | No | 0 | Control flag; 0 indicates default control mode |
| AltFlg | int | No | 0 | Altitude control flag; 0 indicates default altitude control |
Return Value (Returns): None
Exceptions (Raises): None
EulerToQuat(Euler)¶
Function Description: Converts Euler angles to a quaternion.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Euler | list/array | Yes | None | Input Euler angles, format: [roll, pitch, yaw] (unit: rad) |
Return Value (Returns): Quaternion array, format: [w, x, y, z]
Exceptions (Raises): None
SendAccPX4(afx=math.nan, afy=math.nan, afz=math.nan, yawValue=math.nan, yawType=0, frameType=0)¶
Function Description: Sends target acceleration (unit: m/s²) to PX4.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| afx | float | No | math.nan | X-axis target acceleration; NaN indicates this axis is not controlled |
| afy | float | No | math.nan | Y-axis target acceleration; NaN indicates this axis is not controlled |
| afz | float | No | math.nan | Z-axis target acceleration; NaN indicates this axis is not controlled |
| yawValue | float | No | math.nan | Target yaw value; determined by yawType whether it is yaw angle or yaw rate |
| yawType | int | No | 0 | Yaw control type: 0 means yawValue is yaw angle; 1 means yawValue is yaw rate |
| frameType | int | No | 0 | Coordinate frame type: 0 means NED geographic frame; 1 means FRD body frame |
Return Value (Returns): None
Exceptions (Raises): None
SendVelNoYaw(vx=math.nan, vy=math.nan, vz=math.nan)¶
Function Description: Sends the target drone velocity in the body Front-Right-Down (FRD) coordinate system (unit: m/s) to PX4, without controlling yaw rate. When the drone flies upward, vz < 0.
Arguments (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| vx | float | No | math.nan | Forward velocity in FRD frame; NaN indicates this axis is not controlled |
| vy | float | No | math.nan | Rightward velocity in FRD frame; NaN indicates this axis is not controlled |
| vz | float | No | math.nan | Downward velocity in FRD frame; NaN indicates this axis is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendPosNED(x=math.nan, y=math.nan, z=math.nan, yaw=math.nan)¶
Function Description: Sends target drone position (unit: m) in the geographic North-East-Down (NED) coordinate system to PX4, and controls yaw angle (unit: rad). When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | float | No | math.nan | Northward position in NED frame; NaN indicates this axis is not controlled |
| y | float | No | math.nan | Eastward position in NED frame; NaN indicates this axis is not controlled |
| z | float | No | math.nan | Downward position in NED frame; NaN indicates this axis is not controlled |
| yaw | float | No | math.nan | Target yaw angle; NaN indicates yaw is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendVelYawAlt(vel=10, yaw=6.28, alt=-100)¶
Function Description: Sends velocity, yaw angle, and altitude setpoints to PX4. When the drone is flying above ground, the altitude corresponds to the NED z-coordinate satisfying z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| vel | float | No | 10 | Target forward speed magnitude |
| yaw | float | No | 6.28 | Target yaw angle (unit: rad) |
| alt | float | No | -100 | Target altitude (NED z-coordinate, unit: m) |
Return Value (Returns): None
Exceptions (Raises): None
SendPosGlobal(lat=0, lon=0, alt=0, yawValue=0, yawType=0)¶
Function Description: Sends target drone position in the global latitude, longitude, and altitude coordinate system to PX4, and controls yaw. When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| lat | float | No | 0 | Target latitude (unit: degrees) |
| lon | float | No | 0 | Target longitude (unit: degrees) |
| alt | float | No | 0 | Target altitude (unit: m) |
| yawValue | float | No | 0 | Target yaw value, in rad; determined by yawType as yaw angle or yaw rate |
| yawType | int | No | 0 | Yaw control type: 0 means yawValue is yaw angle; 1 means yawValue is yaw rate |
Return Value (Returns): None
Exceptions (Raises): None
SendPosNEDNoYaw(x=math.nan, y=math.nan, z=math.nan)¶
Function Description: Sends target drone position (unit: m) in the geographic North-East-Down (NED) coordinate system to PX4, without yaw control. When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | float | No | math.nan | Northward position in NED frame; NaN indicates this axis is not controlled |
| y | float | No | math.nan | Eastward position in NED frame; NaN indicates this axis is not controlled |
| z | float | No | math.nan | Downward position in NED frame; NaN indicates this axis is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendPosFRD(x=math.nan, y=math.nan, z=math.nan, yaw=math.nan)¶
Function Description: Sends target drone position (unit: m) in the body Front-Right-Down (FRD) coordinate system to PX4, and controls yaw angle (unit: rad). When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | float | No | math.nan | Forward position in FRD frame; NaN indicates this axis is not controlled |
| y | float | No | math.nan | Rightward position in FRD frame; NaN indicates this axis is not controlled |
| z | float | No | math.nan | Downward position in FRD frame; NaN indicates this axis is not controlled |
| yaw | float | No | math.nan | Target yaw angle; NaN indicates yaw is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendPosFRDNoYaw(x=math.nan, y=math.nan, z=math.nan)¶
Function Description: Sends target drone position (unit: m) in the body Front-Right-Down (FRD) coordinate system to PX4, without yaw control. When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | float | No | math.nan | Forward position in FRD frame; NaN indicates this axis is not controlled |
| y | float | No | math.nan | Rightward position in FRD frame; NaN indicates this axis is not controlled |
| z | float | No | math.nan | Downward position in FRD frame; NaN indicates this axis is not controlled |
Return Value (Returns): None
Exceptions (Raises): None
SendPosNEDExt(x=math.nan, y=math.nan, z=math.nan, mode=3, isNED=True)¶
Function Description: Sends extended-format target drone position (unit: m) to PX4. When the drone is flying above ground, z < 0.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | float | No | math.nan | Target x-axis position; NaN indicates this axis is not controlled |
| y | float | No | math.nan | Target y-axis position; NaN indicates this axis is not controlled |
| z | float | No | math.nan | Target z-axis position; NaN indicates this axis is not controlled |
| mode | int | No | 3 | Control mode, corresponding to PX4 position control mask |
| isNED | bool | No | True | True indicates input is in NED geographic frame; False indicates FRD body frame |
Return Value (Returns): None
Exceptions (Raises): None
enFixedWRWTO()¶
Function Description: Sends a command to enable fixed-wing aircraft runway takeoff mode.
Parameters (Args): No parameters
Return Value (Returns): None
Exceptions (Raises): None
SendCruiseSpeed(Speed=0)¶
Function Description: Sends a command to modify the aircraft's cruise speed, in m/s.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Speed | None | No | 0 | Target cruise speed to be set |
Return Value (Returns): None
Exceptions (Raises): None
SendCopterSpeed(Speed=0)¶
Function Description: Sends a command to set the maximum speed for a multi-rotor aircraft.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Speed | None | No | 0 | Maximum speed to be set for the multi-rotor |
Return Value (Returns): None
Exceptions (Raises): None
SendGroundSpeed(Speed=0)¶
Function Description: Sends a command to modify the aircraft's ground speed, in m/s.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Speed | None | No | 0 | Target ground speed to be set |
Return Value (Returns): None
Exceptions (Raises): None
SendCruiseRadius(rad=0)¶
Function Description: Sends a command to modify the aircraft's cruise turning radius, in meters.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| rad | None | No | 0 | Target cruise turning radius to be set |
Return Value (Returns): None
Exceptions (Raises): None
sendTakeoffMode(alt=0)¶
Function Description: Sends a command to control the aircraft's takeoff.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| alt | None | No | 0 | Target takeoff altitude |
Return Value (Returns): None
Exceptions (Raises): None
initOffboard()¶
Function Description: Sends a command to put the PX4 flight controller into Offboard mode and starts sending Offboard messages at 30 Hz.
Parameters (Args): No parameters
Return Value (Returns): None
Exceptions (Raises): None
initOffboardAcc()¶
Function Description: Sends a command to put the PX4 flight controller into Offboard mode and starts sending Offboard messages at 30 Hz (acceleration control type).
Parameters (Args): No parameters
Return Value (Returns): None
Exceptions (Raises): None
initOffboardAtt()¶
Function Description: Sends a command to put the PX4 flight controller into Offboard mode and starts sending Offboard messages at 30 Hz (attitude control type).
Parameters (Args): No parameters
Return Value (Returns): None
Exceptions (Raises): None
initOffboard2()¶
Function Description: Sends a command to put the PX4 flight controller into Offboard mode and starts sending Offboard messages at 30 Hz (extended version).
Parameters (Args): No parameters
Return Value (Returns): None
Exceptions (Raises): None
sendMavTakeOff(xM=0, yM=0, zM=0, YawRad=0, PitchRad=0)¶
Function Description: Sends a command to control the aircraft to take off to a specified target position in the local coordinate system, in meters.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| xM | None | No | 0 | Target X-coordinate |
| yM | None | No | 0 | Target Y-coordinate |
| zM | None | No | 0 | Target Z-coordinate |
| YawRad | None | No | 0 | Target yaw angle, in radians |
| PitchRad | None | No | 0 | Target pitch angle, in radians |
Return Value (Returns): None
Exceptions (Raises): None
sendMavTakeOffLocal(xM=0, yM=0, zM=0, YawRad=0, PitchRad=0, AscendRate=2)¶
Function Description: Sends a command to control the aircraft to take off to a specified target position in the local coordinate system, in meters.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| xM | None | No | 0 | Target X-coordinate |
| yM | None | No | 0 | Target Y-coordinate |
| zM | None | No | 0 | Target Z-coordinate |
| YawRad | None | No | 0 | Target yaw angle, in radians |
| PitchRad | None | No | 0 | Target pitch angle, in radians |
| AscendRate | None | No | 2 | Takeoff climb rate |
Return Value (Returns): None
Exceptions (Raises): None
sendMavTakeOffGPS(lat=None, lon=None, alt=None, yawDeg=0, pitchDeg=15)¶
Function Description: Sends a command to control the aircraft to take off to a specified target position in the global coordinate system, with coordinates in degrees.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| lat | None | No | None | Target latitude, in degrees |
| lon | None | No | None | Target longitude, in degrees |
| alt | None | No | None | Target altitude above sea level, in meters |
| yawDeg | None | No | 0 | Target yaw angle, in degrees |
| pitchDeg | None | No | 15 | Target pitch angle, in degrees |
Return Value (Returns): None
Exceptions (Raises): None
sendMavLand(xM=None, yM=None, zM=None)¶
Function Description: Sends a command to control the aircraft to land at a specified target position in the local coordinate system, with units in meters (m).
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| xM | None | No | None | Target X-coordinate |
| yM | None | No | None | Target Y-coordinate |
| zM | None | No | None | Target Z-coordinate |
Return Value (Returns): None
Exceptions (Raises): None
sendMavLandGPS(lat=None, lon=None, alt=None)¶
Function Description: Sends a command to control the aircraft to land at a specified target position in the global coordinate system, with coordinates in degrees.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| lat | None | No | None | Target latitude, in degrees |
| lon | None | No | None | Target longitude, in degrees |
| alt | None | No | None | Target altitude above sea level, in meters |
Return Value (Returns): None
Exceptions (Raises): None
endOffboard()¶
Function Description: Sends a command to instruct the PX4 flight controller to exit Offboard mode and stops the Offboard message transmission loop.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
sendMavSetParam(param_id, param_value, param_type)¶
Function Description: Sends a command to PX4 to modify a specified parameter using the MAVLink PARAM_SET message. Parameter lists can be viewed in QGroundControl.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| param_id | Any | Yes | None | Identifier/name of the target parameter |
| param_value | Any | Yes | None | Target value for the parameter |
| param_type | Any | Yes | None | MAVLink type of the parameter |
Return Value (Returns): None
Exceptions (Raises): None
SendHILCtrlMsg(ctrls=[0] * 16, idx=0, flags=1)¶
Function Description: Sends the HIL_ACTUATOR_CONTROLS command to PX4; this message is converted into the uORB message rfly_ctrl.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| ctrls | Any | No | [0] * 16 | 16-dimensional control input array |
| idx | Any | No | 0 | Control group index |
| flags | Any | No | 1 | Message flags |
Return Value (Returns): None
Exceptions (Raises): None
SendHILCtrlMsg1()¶
Function Description: Sends a DEBUG_VECT debug vector message to PX4; this message is converted into the uORB message rfly_ctrl.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
SendMavArm(isArm=1)¶
Function Description: Sends a command to PX4 to arm or disarm the UAV.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| isArm | Any | No | 1 | 1 indicates arming, 0 indicates disarming |
Return Value (Returns): None
Exceptions (Raises): None
initRCSendLoop(Hz=30)¶
Function Description: Initializes the RC PWM transmission loop and sets the transmission frequency.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Hz | Any | No | 30 | RC signal transmission frequency, in Hz |
Return Value (Returns): None
Exceptions (Raises): None
endRCSendLoop()¶
Function Description: Terminates the RC PWM transmission loop.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
RcSendLoop()¶
Function Description: Execution function for the RC PWM transmission loop; continuously transmits the configured PWM values.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
SendRCPwms(Pwms)¶
Function Description: Sets the PWM values to be transmitted for the RC channels.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| Pwms | Any | Yes | None | Array of PWM values for each channel |
Return Value (Returns): None
Exceptions (Raises): None
SendRcOverride(ch1=1500, ch2=1500, ch3=1100, ch4=1500, ch5=1100, ch6=1100, ch7=1500, ch8=1500)¶
Function Description: Sends a MAVLink command to PX4 to override the original RC channel signals using the RC_CHANNELS_OVERRIDE message.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| ch1 | Any | No | 1500 | PWM value for channel 1, range: 1000–2000 |
| ch2 | Any | No | 1500 | PWM value for channel 2, range: 1000–2000 |
| ch3 | Any | No | 1100 | PWM value for channel 3, range: 1000–2000 |
| ch4 | Any | No | 1500 | PWM value for channel 4, range: 1000–2000 |
| ch5 | Any | No | 1100 | PWM value for channel 5, range: 1000–2000 |
| ch6 | Any | No | 1100 | PWM value for channel 6, range: 1000–2000 |
| ch7 | Any | No | 1500 | PWM value for channel 7, range: 1000–2000 |
| ch8 | Any | No | 1500 | PWM value for channel 8, range: 1000–2000 |
Return Value (Returns): None
Exceptions (Raises): None
sendMavManualCtrl(x=0, y=0, z=0, r=0)¶
Function Description: Sends a MAVLink command to PX4 to override manual control signals using the MANUAL_CONTROL message.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| x | Any | No | 0 | Control input along the X-axis, range: -1000–1000 |
| y | Any | No | 0 | Control input along the Y-axis, range: -1000–1000 |
| z | Any | No | 0 | Control input along the Z-axis, range: -1000–1000 |
| r | Any | No | 0 | Yaw-axis control input, range: -1000–1000 |
Return Value (Returns): None
Exceptions (Raises): None
SendSetMode(mainmode, cusmode=0)¶
Function Description: Sends a MAVLink command to PX4 to change the flight mode using the MAV_CMD_DO_SET_MODE message.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| mainmode | Any | Yes | None | Main mode identifier |
| cusmode | Any | No | 0 | Custom sub-mode identifier; defaults to 0 |
Return Value (Returns): None
Exceptions (Raises): None
stopRun()¶
Function Description: Stops the MAVLink listening loop started by InitMavLoop(), equivalent to endMavLoop().
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
getTrueDataMsg()¶
Function Description: Starts a loop to continuously listen for real simulation data from port 30100.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
getPX4DataMsg()¶
Function Description: Starts a loop to continuously listen for PX4 data from port 40100.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
setMsgDict(stName)¶
Function Description: Sets the message dictionary-related identifier.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| stName | Any | Yes | None | Message dictionary name identifier |
Return Value (Returns): None
Exceptions (Raises): None
netForwardData()¶
Function Description: Forwards data over the network.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
GetUDPRedisBuf(sock)¶
Function Description: Retrieves UDP forwarding buffer data.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| sock | None | Yes | None | UDP socket object |
Return Value (Returns): None
Exceptions (Raises): None
getMavMsg()¶
Function Description: Starts a loop to listen for MAVLink data from the 20100 series ports or serial port.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
OffboardSendMode()¶
Function Description: Sets the offboard mode transmission.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
sendRebootPix(copterID, delay=-1)¶
Function Description: Sends a restart simulation message to the PX4 flight controller of the specified drone ID. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| copterID | None | Yes | None | Target drone ID |
| delay | None | No | -1 | Restart delay in seconds |
Return Value (Returns): None Exceptions (Raises): None
sendCustomData(CopterID, data=[0] * 16, checksum=123456, port=50000, IP=127.0.0.1)¶
Function Description: Sends a 16-dimensional custom message to the specified IP and port. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| CopterID | None | Yes | None | Target drone ID |
| data | None | No | [0] * 16 | Data array of 16 elements to be sent |
| checksum | None | No | 123456 | Data checksum |
| port | None | No | 50000 | Target port number |
| IP | None | No | 127.0.0.1 | Target IP address |
Return Value (Returns): None Exceptions (Raises): None
setGPSOriLLA(LonLatAlt)¶
Function Description: Sets the initial GPS latitude, longitude, and altitude. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| LonLatAlt | None | Yes | None | Initial latitude, longitude, and altitude array, formatted as [longitude, latitude, altitude] |
Return Value (Returns): None Exceptions (Raises): None
sendSILIntFloat(inSILInts=[0] * 8, inSILFLoats=[0] * 20, copterID=-1)¶
Function Description: Sends SIL integer and floating-point data to the PX4 flight controller. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| inSILInts | None | No | [0] * 8 | Array of 8 integers to be sent |
| inSILFLoats | None | No | [0] * 20 | Array of 20 floating-point numbers to be sent |
| copterID | None | No | -1 | Target drone ID; -1 indicates broadcasting to all drones |
Return Value (Returns): None Exceptions (Raises): None
InitDllLogLoop(copterID=-1)¶
Function Description: Initializes a DLL log data receiving thread, listening for the DLL model output data outCopterStruct of the specified aircraft. This interface is used to read 32-dimensional double log data exported by the integrated model or custom DLL.
The listening port rule is 30100 + CopterID * 2 - 1, i.e., when CopterID=1, it listens on 30101; when CopterID=2, it listens on 30103.
Data Protocol:
struct outCopterStruct {
int checksum; // 1234567890
int CopterID;
double data[32];
}; // Total 264 bytes, corresponding to Python unpack format "ii32d"
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
copterID |
int |
No | -1 |
Target aircraft ID. When -1, uses the aircraft ID of the current controller object |
Return Value (Returns): None
Exceptions (Raises): None
Port Occupancy
InitDllLogLoop() uses the 30101/30103/... truth data output series ports and cannot be used simultaneously with InitTrueDataLoop() to listen to the same port for the same aircraft. If a truth data return thread has already been started, first confirm the data source and port allocation.
EndDllLogLoop()¶
Function Description: Stops the DLL log receiving thread started by InitDllLogLoop() and closes the corresponding UDP socket.
Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None
getDllLogData()¶
Function Description: Thread-safely retrieves a copy of the latest DLL model output data outCopterStruct.data.
Parameters (Args): None
Return Value (Returns):
list[float]: A copy of the 32-element double data array. Returns a list of all zeros if no data has been received yet.
Exceptions (Raises): None
Example:
from RflySimSDK.ctrl.PX4MavCtrlV4 import PX4MavCtrler
import time
mav = PX4MavCtrler(1)
mav.InitDllLogLoop()
time.sleep(1)
data = mav.getDllLogData()
print(data)
mav.EndDllLogLoop()
SendSetModeAPM(apm_mode_number)¶
Function Description: Directly switches the flight mode according to the ArduPilot mode number, used for APM real hardware or ArduPilot simulation control. Mode numbers can be selected from APM_COPTER_MODE, APM_PLANE_MODE, APM_ROVER_MODE.
The internal implementation sends the command via MAVLink MAV_CMD_DO_SET_MODE, with base_mode using MAV_MODE_FLAG_CUSTOM_MODE_ENABLED.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
apm_mode_number |
int |
Yes | - | ArduPilot flight mode number |
Return Value (Returns): None
Exceptions (Raises): None
Example:
from RflySimSDK.ctrl.PX4MavCtrlV4 import PX4MavCtrler, APM_COPTER_MODE
mav = PX4MavCtrler(1)
mav.SendSetModeAPM(APM_COPTER_MODE.GUIDED)
Advanced Usage Example¶
Demonstrates complex composite scenarios (e.g., multi-agent collaboration, asynchronous control, batch operations)
This example implements a composite scenario combining point-mass model collaborative simulation for multi-drone swarms with asynchronous real-time pose and frequency data feedback. FIFO queues are used to enable inter-thread communication of control commands and state data, while PX4 custom flight modes support multi-drone collaborative missions.
import RflySimSDK.ctrl as rfc
import threading
import time
# Initialize a list of controller objects for 5 drones
px4_ctrl_list = [rfc.PX4MavCtrler() for _ in range(5)]
# Initialize an asynchronous communication FIFO queue
data_fifo = rfc.fifo()
# Start true data feedback threads for all drones
for ctrl in px4_ctrl_list:
ctrl.InitTrueDataLoop()
# Batch-initialize point-mass simulation models
for ctrl in px4_ctrl_list:
ctrl.initPointMassModel()
# Define thread function for asynchronous pose data reading
def async_read_true_data():
while True:
# Read latest multi-drone pose data from FIFO
all_pos_data = data_fifo.read()
if all_pos_data:
# Batch-send pose data to simulation visualization endpoint
for idx, pos_data in enumerate(all_pos_data):
px4_ctrl_list[idx].sendUE4PosNew(pos_data, rfc.PosTypeMask.mask(), rfc.AttTypeMask.mask())
time.sleep(0.01)
# Start asynchronous thread for data feedback processing
read_thread = threading.Thread(target=async_read_true_data, daemon=True)
read_thread.start()
# Main loop runs point-mass model control to achieve swarm cooperative path following
try:
while True:
for ctrl in px4_ctrl_list:
ctrl.PointMassModelLoop(rfc.PX4_CUSTOM_MAIN_MODE, rfc.PX4_CUSTOM_SUB_MODE_AUTO)
# Apply yaw rate saturation constraint
ctrl.yawSat(max_yaw_rate=30.0)
time.sleep(0.01)
finally:
# Upon termination, batch-stop all threads and models
for ctrl in px4_ctrl_list:
ctrl.EndPointMassModel()
ctrl.EndTrueDataLoop()
Notes and Pitfall Avoidance Guide¶
- Point Mass Model Start/Stop Pairing:
initPointMassModelandEndPointMassModelmust be called in pairs. If only initialization is performed without termination, the background simulation thread will continue to occupy resources, leading to abnormal model states during subsequent simulation startups. Similarly,InitTrueDataLoopandEndTrueDataLoopmust also be managed in pairs for proper lifecycle control. - FIFO Queue Read/Write Permission Matching: In multi-threaded collaboration scenarios, FIFO queue read and write operations must be performed by different threads. Avoid performing consecutive read and write operations within the same thread, as this may cause data blocking or erroneous empty reads, thereby affecting the real-time performance of the control chain.
- Custom Flight Mode Parameter Matching: When calling
PointMassModelLoopor similar functions that require custom flight mode parameters, you must use thePX4_CUSTOM_MAIN_MODEandPX4_CUSTOM_SUB_MODE_AUTOtype parameters provided by this module. Passing arbitrary integer values will cause the PX4 flight controller to fail to recognize the control commands, triggering mode-switching failures. - Redis Key Retrieval Must Match Aircraft ID: When calling
RedisKey.GetRedisKeyto obtain the state storage key, the correct ID corresponding to the drone number must be provided. An incorrect ID will result in reading state data from another drone, causing crosstalk issues in cluster control.
Changelog¶
2026-03-03: feat: SDK adds IP handling mechanism for compatibility with local-to-cloud migration2025-09-19: Compatibility with WSL22025-09-19: Recovery mechanism for multicast failure scenarios2025-09-11: fix: Added support for port reuse on Linux2025-08-20: fix: Added timestamp retrieval for fault injection2025-08-07: fix: Resolved bug where themavlinkport variable was ineffective indirectmode when connecting to real hardware2024-12-18: fix: Added a custom message sending interface2024-11-22: fix2024-11-22: fix: Updated API documentation page2024-10-23: fix: UpdatedsendHILinterface2024-09-09: feat: Added interface for externally sending GPS messages2024-08-30: fix: Removed integrated model control-related interfaces, moved elsewhere2024-08-28: fix: Disabled channel control by default2024-08-14: fix: Updated HTML version of API documentation2024-07-29: fix: Maintained backward compatibility