API Interface Documentation¶
Introduction¶
Overview: This document describes the drone control core module of the RflySimSDK drone simulation platform. It provides a drone control base class, various communication control modes, and PID controller implementations, supporting the development and deployment of diverse drone control algorithms.
This module is designed for drone development and simulation testing scenarios and serves as the foundational dependency for users to implement custom drone control logic. The Ctrl class provides the fundamental framework for drone control, while the CtMode class supports selection among different control communication modes (note: Redis mode is supported only in the enterprise edition), accommodating development requirements across different platform versions. The provided PID class is optimized for scenarios with stable control invocation intervals: it avoids redundant time-interval calculations within the controller and instead adjusts control outputs directly via PID parameters. This simplifies parameter tuning in fixed-frequency control scenarios and is suitable for various conventional fixed-frequency control tasks, such as drone position and attitude control.
Quick Start¶
Minimal working example; copy and modify only the essential configurations to run.
from RflySimSDK.ctrl import Ctrl
import time
# 1. Initialize the control object; by default, it uses local UDP connection to control drone ID 1
copter_ctrl = Ctrl(copter_id=1, ip="127.0.0.1")
# 2. Initialize the control loop; use position control mode (ct_mode=2 corresponds to position control), without enabling offboard mode
copter_ctrl.init_loop(ct_mode=2, offboard=False)
# 3. Wait for disarming and initialization to complete
time.sleep(3)
# 4. Command the drone to take off to a height of 10 meters in the NED coordinate system (note: height is negative in NED, so -10 is used here)
copter_ctrl.takeoff(height=-10)
# 5. Wait for takeoff to complete
time.sleep(10)
# 6. Maintain hover by continuously sending control commands to keep the connection alive
while True:
# Send an empty command to maintain position hover
if copter_ctrl.is_full_send():
time.sleep(0.01)
Environment & Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
DllSimCtrlAPI,PX4MavCtrlV4,numpy,time - Prerequisites: Before calling this interface, RflySimSDK must be initialized and the
RflySimSDK.ctrlmodule must be imported.
Core Interface Description¶
The module api.py contains configuration variables, helper functions, and core business classes.
Global Constants and Enumerations¶
This section lists all globally accessible constants and enumeration definitions that can be directly referenced in the module.
Standalone Constants¶
None
Global/Standalone Functions¶
None
Ctrl Class¶
PX4 flight controller control class, inheriting from PX4MavCtrler, providing basic drone control functionality and supporting connections to both simulated and real PX4 flight controllers.
__init__(copter_id=1, ip="127.0.0.1", com="udp", port=0, simulink_dll=False)¶
Function Description: Initializes a Ctrl object and establishes a connection to the PX4 flight controller (simulation or real hardware).
Arguments:
| Parameter | Type | Default | Description |
|---|---|---|---|
| copter_id | — | 1 | Drone ID used to distinguish between multiple drones in multi-drone scenarios |
| ip | — | 127.0.0.1 | IP address of the flight controller; for local simulation, the loopback address is used by default |
| com | — | udp | Communication protocol type; options are udp (network communication, commonly used in simulation) or serial communication |
| port | — | 0 | Communication port number; 0 indicates automatic port allocation |
| simulink_dll | — | False | Whether to use Simulink dynamic-link library (DLL) simulation mode; set to True for Simulink co-simulation |
Returns: None
Raises: None
init_loop(ct_mode="2", offboard=False)¶
Function Description: Initializes the control loop and sets the control mode and offboard option. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| ct_mode | None | No | "2" | Control mode parameter |
| offboard | None | No | False | Whether to enable offboard mode |
Returns: None
Raises: None
is_full_send()¶
Function Description: Checks whether full command transmission has been completed.
Arguments: None
Returns: Boolean; True indicates full transmission is complete, False indicates incomplete.
Raises: None
takeoff(height=0, pos_x=0, pos_y=0)¶
Function Description: Executes drone takeoff. The height is defined in the NED coordinate system. PX4 fixed-wing models support specifying the takeoff position after liftoff; the integrated model only supports specifying the height. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| height | None | No | 0 | Target takeoff altitude in the NED coordinate system, in meters |
| pos_x | None | No | 0 | Target x-coordinate in the NED coordinate system at takeoff, in meters; supported only for PX4 fixed-wing models |
| pos_y | None | No | 0 | Target y-coordinate in the NED coordinate system at takeoff, in meters; supported only for PX4 fixed-wing models |
Returns: None
Raises: None
return_home(height=0)¶
Function Description: Executes return-to-home (RTH) operation: moves horizontally to the Home point while maintaining the current altitude setting. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| height | None | No | 0 | Altitude to maintain during the return-to-home maneuver, in meters |
Returns: None
Raises: None
land(height=0)¶
Function Description: Executes landing operation: descends to the altitude corresponding to the Home point. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| height | None | No | 0 | Target landing altitude, in meters |
Returns: None
Raises: None
send_pos_ned(pos=None, yaw=None)¶
Function Description: Sends position control commands in the NED coordinate system. For PX4 models, each drone’s coordinates are relative to its takeoff point; for the integrated model, coordinates are relative to the UE center. This difference arises because the integrated model uses true position control, whereas PX4 uses filtered position control. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| pos | None | No | None | Position in x, y, z directions in the NED coordinate system, in meters |
| yaw | None | No | None | Target yaw angle, in radians |
Returns: None
Raises: None
send_pos_speed_fw(pos=None, speed=None)¶
Function Description: Sends combined position and speed control commands for the fixed-wing integrated model. Arguments:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| pos | None | No | None | Target position, in meters |
| speed | None | No | None | Target flight speed |
Returns: None
Raises: None
send_pos_global(pos=None, yaw=None)¶
Function Description: Sends position control commands in the global coordinate system. Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| pos | None | No | None | Target position in the global coordinate system |
| yaw | None | No | None | Target yaw angle, unit: rad |
Returns: None
Raises: None
send_vel_ned(vel=None, yaw_rate=None)¶
Function Description: Sends velocity control commands in the NED coordinate system
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| vel | None | No | None | Target velocity in x, y, z directions in the NED coordinate system, unit: m/s |
| yaw_rate | None | No | None | Target yaw rate, unit: rad/s |
Returns: None
Raises: None
send_vel_body(vel=None, yaw_rate=None)¶
Function Description: Sends velocity control commands in the body-fixed coordinate system
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| vel | None | No | None | Target velocity in x, y, z directions in the body-fixed coordinate system, unit: m/s |
| yaw_rate | None | No | None | Target yaw rate, unit: rad/s |
Returns: None
Raises: None
send_acc(acc=None)¶
Function Description: Sends acceleration control commands; applicable only to multirotor drones. The x and y axes in the NED coordinate system respond very quickly, while the z-axis responds slowly to maintain altitude.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| acc | None | No | None | Desired acceleration in the NED coordinate system, unit: m/s² |
Returns: None
Raises: None
send_att_thrust(att=None, thrust=None)¶
Function Description: Sends attitude and thrust control commands
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| att | None | No | None | Euler angles [roll, pitch, yaw], unit: rad |
| thrust | None | No | None | Thrust control command |
Returns: None
Raises: None
send_att(att=None)¶
Function Description: Sends attitude control commands
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| att | None | No | None | Euler angles [roll, pitch, yaw], unit: rad |
Returns: None
Raises: None
send_cruise_speed_fw(speed=None)¶
Function Description: Sets the cruise speed for fixed-wing aircraft; applicable only to fixed-wing aircraft. Corresponds to the QGC parameter FW_AIRSPD_TRIM. Speed range: 10–20 m/s, default value: 15 m/s. Speed constraints are defined in src/modules/fw_pos_control_l1/fw_pos_control_l1_params.c.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| speed | None | No | None | Target horizontal cruise speed for fixed-wing aircraft, unit: m/s |
Returns: None
Raises: None
send_cruise_radius_fw(radius=None)¶
Function Description: Sets the loiter radius for fixed-wing aircraft; applicable only to fixed-wing aircraft. Corresponds to the QGC parameter NAV_LOITER_RAD. Specifying values outside the valid range will appear as modified in QGC, but the actual value will remain clamped within the valid range.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| radius | None | No | None | Loiter radius for fixed-wing aircraft, unit: m. Valid range: 25–1000 m; typical accuracy error: ±10–20 m |
Returns: None
Raises: None
get_vehicle_id()¶
Function Description: Retrieves the ID of the currently controlled vehicle
Arguments: None
Returns: Vehicle ID; numbering starts from 1 by default
Raises: None
get_time_s()¶
Function Description: Retrieves the current simulation time
Arguments: None
Returns: Current simulation time, unit: seconds
Raises: None
get_pos_ned()¶
Function Description: Retrieves the current vehicle position in the NED coordinate system
Arguments: None
Returns: Position in the local NED coordinate system returned by PX4, where the origin is the takeoff point for each aircraft. For the综合 model, returns the global NED position (relative to the UE center), formatted as [north, east, down], unit: meters
Raises: None
get_pos_ned_global()¶
Function Description: Retrieves the current vehicle position in the global NED coordinate system
Arguments: None
Returns: Global NED position (relative to the UE center), formatted as [north, east, down], unit: meters
Raises: None
get_pos_global()¶
is_mav_no_gps()¶
Function Description: Determines whether the current communication mode is MAVLink GPS-disabled mode (i.e., MAVLink mode without GPS data transmission). Parameters (Args): - None
Returns:
- bool: Returns True if the current mode is MAVLink GPS-disabled mode; otherwise, returns False.
Raises: - None
Function Description: Determines whether the current communication mode is MAVLink GPS-less mode.
Return Value (Returns):
bool: ReturnsTrueif the current mode is MAVLink GPS-less mode; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_redis_full()¶
Function Description: Determines whether the current communication mode is Redis full mode (Enterprise Edition only).
Return Value (Returns):
bool: ReturnsTrueif the current mode is Redis full mode; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_redis_simple()¶
Function Description: Determines whether the current communication mode is Redis simplified mode (Enterprise Edition only).
Return Value (Returns):
bool: ReturnsTrueif the current mode is Redis simplified mode; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_udp()¶
Function Description: Determines whether the current communication mode belongs to the UDP type (includes both full and simplified modes).
Return Value (Returns):
bool: ReturnsTrueif the current mode is of UDP type; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_mav()¶
Function Description: Determines whether the current communication mode belongs to the MAVLink type (includes all MAVLink-related modes).
Return Value (Returns):
bool: ReturnsTrueif the current mode is of MAVLink type; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_redis()¶
Function Description: Determines whether the current communication mode belongs to the Redis type (includes both full and simplified modes; Enterprise Edition only).
Return Value (Returns):
bool: ReturnsTrueif the current mode is of Redis type; otherwise, returnsFalse.
Exceptions (Raises):
None.
is_full()¶
Function Description: Determines whether the current communication mode is full-data transmission mode (includes UDP full mode, MAVLink full mode, and Redis full mode).
Return Value (Returns):
bool: ReturnsTrueif the current mode is full-data transmission mode; otherwise, returnsFalse.
Exceptions (Raises):
None.
Example:
from RflySimSDK.ctrl import CtMode
# Initialize communication mode instance and set to MAVLink full mode
mode = CtMode()
mode.set(CtMode.MAVLink_Full)
# Determine communication mode type
print(mode.is_mav()) # Output: True
print(mode.is_full()) # Output: True
print(mode.is_udp()) # Output: False
---
### Predefined Class Constants
| Constant Name | Type | Value | Description |
| :--- | :---: | :---: | :--- |
| `UDP_Full` | `int` | `0` | UDP full communication mode |
| `UDP_Simple` | `int` | `1` | UDP simplified communication mode |
| `MAVLink_Full` | `int` | `2` | MAVLink full communication mode |
| `MAVLink_Simple` | `int` | `3` | MAVLink simplified communication mode |
| `MAVLink_NoSend` | `int` | `4` | MAVLink receive-only mode (no transmission) |
| `MAVLink_NoGPS` | `int` | `5` | MAVLink mode without GPS input |
| `Mavlink_Vision` | `int` | `6` | MAVLink vision-based positioning mode |
| `Redis_Full` | `int` | `7` | Redis full communication mode (Enterprise Edition only) |
| `Redis_Simple` | `int` | `8` | Redis simplified communication mode (Enterprise Edition only) |
### `PID` Class
This controller is suitable for scenarios where the invocation time interval is approximately constant. Within the controller, the time interval is not explicitly calculated; instead, adjustments are made via PID parameters. It is commonly used in drone flight control for fixed-period偏差 (deviation) regulation.
#### `__init__(p=0.0, i=0.0, d=0.0)`
**Function Description**: Initializes the PID controller by setting the proportional, integral, and derivative coefficients.
**Arguments (Args)**:
| Parameter Name | Type | Required | Default Value | Description |
| :--- | :--- | :---: | :--- | :--- |
| `p` | `float` | No | `0.0` | Proportional coefficient, used to adjust the proportional control gain |
| `i` | `float` | No | `0.0` | Integral coefficient, used to eliminate steady-state error |
| `d` | `float` | No | `0.0` | Derivative coefficient, used to suppress deviation changes and improve system stability |
**Returns**:
- `PID` instance object
**Raises**:
- None
---
#### `pid(err)`
**Function Description**: Computes the PID control output based on the input deviation value.
**Arguments (Args)**:
| Parameter Name | Type | Required | Default Value | Description |
| :--- | :--- | :---: | :--- | :--- |
| `err` | `float` | Yes | - | Current control deviation, i.e., setpoint minus actual value |
**Returns**:
- `float`: Computed PID control output
**Raises**:
- None
**Example**:
```python
# Create a PID controller with proportional coefficient 0.5 and integral coefficient 0.1
pid_ctrl = PID(p=0.5, i=0.1)
# Compute control output for the current deviation
output = pid_ctrl.pid(err=2.0)
reset()¶
Function Description: Resets the integral accumulation term and historical deviation of the PID controller, clearing previous control state.
Returns:
- None
Raises:
- None
Example:
pid_ctrl = PID(1.0, 0.2, 0.05)
pid_ctrl.reset()
---
## Advanced Usage Examples
> Demonstrates complex composite scenarios (e.g., multi-vehicle collaboration, asynchronous control, batch operations)
```python
import RflySimSDK.ctrl as rfly_ctrl
import time
from concurrent.futures import ThreadPoolExecutor
# Advanced example of coordinated takeoff for heterogeneous multi-vehicle formations (multirotor + fixed-wing)
# 1. Initialize control and communication modes for multiple drones of different types
vehicles = [
{"id": 1, "type": "multirotor", "ctrl": rfly_ctrl.Ctrl(), "mode": rfly_ctrl.CtMode()},
{"id": 2, "type": "fixedwing", "ctrl": rfly_ctrl.Ctrl(), "mode": rfly_ctrl.CtMode()},
{"id": 3, "type": "multirotor", "ctrl": rfly_ctrl.Ctrl(), "mode": rfly_ctrl.CtMode()},
]
# Batch set full UDP communication mode
for veh in vehicles:
veh["mode"].set(veh["mode"].is_udp_full())
veh["ctrl"].init_loop(veh_id=veh["id"])
# Asynchronous batch takeoff to avoid time wasted on sequential takeoff waits
def async_takeoff(veh):
if veh["type"] == "multirotor":
return veh["ctrl"].takeoff(target_alt=5.0)
return True
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(async_takeoff, vehicles))
time.sleep(8) # Wait for all drones to stabilize at takeoff altitude
# Formation position control, combining PID for position error correction
pid_x = rfly_ctrl.PID(kp=1.2, ki=0.1, kd=0.05)
pid_y = rfly_ctrl.PID(kp=1.2, ki=0.1, kd=0.05)
formation_offset = [(0, 2), (-2, 0), (0, -2)]
leader_ned = [0, 0, -5]
for step in range(100):
for idx, veh in enumerate(vehicles):
target_x = leader_ned[0] + formation_offset[idx][0]
target_y = leader_ned[1] + formation_offset[idx][1]
if veh["type"] == "multirotor":
vel_x = pid_x.pid(target_x - veh["current_x"])
vel_y = pid_y.pid(target_y - veh["current_y"])
veh["ctrl"].send_vel_body(vx=vel_x, vy=vel_y, vz=0, yaw_rate=0)
else:
veh["ctrl"].send_pos_speed_fw(north=target_x, east=target_y, down=-5, airspeed=12)
# Update leader position and continue loop
leader_ned[0] += 0.5
time.sleep(0.1)
# Batch return and landing
for veh in vehicles:
veh["ctrl"].return_home()
time.sleep(20)
for veh in vehicles:
veh["ctrl"].land()
Notes and Pitfall Avoidance Guide¶
- Initialization must match communication mode: Before calling
Ctrl.init_loop(), the corresponding communication mode must be set viaCtMode.set(). Mismatched mode settings will cause control commands to fail silently—no errors appear in simulation, yet drones do not respond to commands. - Fixed-wing and multirotor control methods are not interchangeable:
send_pos_speed_fwis a position-velocity control interface specifically for fixed-wing aircraft; using it directly on multirotors will have no effect. Conversely, the multirotor velocity control interfacesend_vel_bodyis incompatible with the fixed-wing’s altitude-holding logic. - PID controllers must reset state before reuse: When reusing the same PID controller for different drones or switching control tasks,
PID.reset()must be called to clear accumulated integral terms; otherwise, overshoot will abnormally increase. - Full-send mode must match link bandwidth: When using full-data transmission modes such as
is_udp_fulloris_mav_full, ensure sufficient simulation network bandwidth. If packet loss is severe, switch to the simplifiedis_udp_simplemode to reduce bandwidth usage.
Changelog¶
2026-03-03: feat: SDK adds IP handling mechanism, compatible with cloud deployment of local versions2024-09-09: update: simulation mode for Mavlink_Vision2024-07-18: fix: update API homepage index2023-11-09: feat: add cloud-compatible interfaces