Skip to content

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.ctrl module 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.

Function Description: Initializes a Ctrl object and establishes a connection to the PX4 flight controller (simulation or real hardware). Arguments (Args):

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 (Args):

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 (Args): 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 (Args):

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 (Args):

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 (Args):

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 (Args):

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 (Args):

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 (Args):

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

Return Value (Returns): None
Exceptions (Raises): None


send_vel_ned(vel=None, yaw_rate=None)

Function Description: Sends velocity control commands in the NED coordinate system
Arguments (Args):

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

Return Value (Returns): None
Exceptions (Raises): None


send_vel_body(vel=None, yaw_rate=None)

Function Description: Sends velocity control commands in the body-fixed coordinate system
Arguments (Args):

| Parameter Name | Type | Required | Default Value | Description | | :--- | :--- | :---

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

Return Value (Returns): None
Exceptions (Raises): None


get_vehicle_id()

Function Description: Retrieves the ID of the currently controlled vehicle
Arguments (Args): None
Return Value (Returns): Vehicle ID; numbering starts from 1 by default
Exceptions (Raises): None


get_time_s()

Function Description: Retrieves the current simulation time
Arguments (Args): None
Return Value (Returns): Current simulation time, unit: seconds
Exceptions (Raises): None


get_pos_ned()

Function Description: Retrieves the current vehicle position in the NED coordinate system
Arguments (Args): None
Return Value (Returns): Position in the local NED coordinate system returned by PX4, where the origin is the takeoff point for each aircraft. For the integrated model, returns the global NED position (relative to the UE center), formatted as [north, east, down], unit: meters
Exceptions (Raises): None


get_pos_ned_global()

Function Description: Retrieves the current vehicle position in the global NED coordinate system
Arguments (Args): None
Return Value (Returns): Global NED position (relative to the UE center), formatted as [north, east, down], unit: meters
Exceptions (Raises): None


get_pos_global()

Function Description: Retrieves the current vehicle's latitude, longitude, and altitude in the WGS84 coordinate system.
Arguments (Args): None
Return Value (Returns): Position in the WGS84 coordinate system, formatted as [latitude, longitude, altitude], with units of degrees, degrees, and meters, respectively.
Exceptions (Raises): None


get_home_pos()

Function Description: Retrieves the Home point position of the current vehicle in the WGS84 coordinate system.
Arguments (Args): None
Return Value (Returns): Home point position in the WGS84 coordinate system, formatted as [latitude, longitude, altitude], with units of degrees, degrees, and meters, respectively.
Exceptions (Raises): None


get_vel_ned()

Function Description: Retrieves the current vehicle’s velocity in the NED coordinate system.
Arguments (Args): None
Return Value (Returns): Velocity in the NED coordinate system, formatted as [north velocity, east velocity, down velocity], with units of m/s.
Exceptions (Raises): None


get_acc()

Function Description: Retrieves the current vehicle’s acceleration in the body-fixed coordinate system; currently supported only by the integrated model.
Arguments (Args): None
Return Value (Returns): Acceleration in the body-fixed coordinate system, formatted as [x-axis acceleration, y-axis acceleration, z-axis acceleration], with units of m/s².
Exceptions (Raises): None


get_euler()

Function Description: Retrieves the current vehicle’s Euler angle attitude.
Arguments (Args): None
Return Value (Returns): Euler angle attitude, formatted as [roll, pitch, yaw], with units of radians.
Exceptions (Raises): None


get_angular_rate()

Function Description: Retrieves the current vehicle’s angular rate.
Arguments (Args): None
Return Value (Returns): Angular rate in the body-fixed coordinate system, formatted as [x-axis angular rate, y-axis angular rate, z-axis angular rate], with units of rad/s.
Exceptions (Raises): None


get_quaternion()

Function Description: Retrieves the current vehicle’s attitude represented as a quaternion; currently supported only by the integrated model.
Arguments (Args): None
Return Value (Returns): Attitude represented as a quaternion, formatted as [w, x, y, z].
Exceptions (Raises): None


get_actuator_speed()

Function Description: Retrieves the rotational speeds of each motor.
Arguments (Args): None
Return Value (Returns): List of motor speeds, with each element in units of rpm (revolutions per minute), ordered according to motor ID.
Exceptions (Raises): None


get_max_vel_xy()

Function Description: Retrieves the maximum horizontal velocity set for the vehicle.
Arguments (Args): None
Return Value (Returns): Maximum horizontal velocity, with units of m/s.
Exceptions (Raises): None


get_max_vel_z()

Function Description: Retrieves the maximum vertical velocity set for the vehicle.
Arguments (Args): None
Return Value (Returns): Maximum vertical velocity, with units of m/s.
Exceptions (Raises): None


get_max_acc_xy()

Function Description: Retrieves the maximum horizontal acceleration set for the vehicle.
Arguments (Args): None
Return Value (Returns): Maximum horizontal acceleration, with units of m/s².
Exceptions (Raises): None


get_max_acc_z()

Function Description: Retrieves the maximum vertical acceleration set for the vehicle.
Arguments (Args): None
Return Value (Returns): float: Maximum vertical acceleration, with units of m/s².
Exceptions (Raises): None


CtMode Class

A communication mode management class for drones, used to define and determine various communication modes between drones and the simulation environment in the RflySim platform. Note: Redis mode is supported only in the enterprise edition. This class predefines multiple commonly used communication mode constants for convenient direct usage by developers.

__init__()

Function Description: Initializes an instance of the CtMode class.
Arguments (Args): None
Return Value (Returns):
- CtMode instance object
Exceptions (Raises): None


set(mode)

Function Description: Sets the communication mode for the current instance.
Arguments (Args):

Parameter Name Type Required Default Value Description
mode int Yes - Communication mode to be set; predefined constants of this class can be used, such as CtMode.UDP_Full, CtMode.MAVLink_Full, etc.

Return Value (Returns): None
Exceptions (Raises): None


is_udp_full()

Function Description: Determines whether the current communication mode is UDP full mode.
Return Value (Returns):
- bool: Returns True if the current mode is UDP full mode; otherwise, returns False.
Exceptions (Raises): None


is_udp_simple()

Function Description: Determines whether the current communication mode is UDP simplified mode.
Return Value (Returns):
- bool: Returns True if the current mode is UDP simplified mode; otherwise, returns False.
Exceptions (Raises): None


is_mav_full()

Function Description: Determines whether the current communication mode is MAVLink full mode.
Return Value (Returns):
- bool: Returns True if the current mode is MAVLink full mode; otherwise, returns False.
Exceptions (Raises): None


is_mav_simple()

Function Description: Determines whether the current communication mode is MAVLink simplified mode.
Return Value (Returns):
- bool: Returns True if the current mode is MAVLink simplified mode; otherwise, returns False.
Exceptions (Raises): None


is_mav_no_send()

Function Description: Determines whether the current communication mode is MAVLink receive-only mode (no transmission).
Return Value (Returns):
- bool: Returns True if the current mode is MAVLink receive-only mode; otherwise, returns False.
Exceptions (Raises): None


is_mav_no_gps()

Function Description: Determines whether the current communication mode is MAVLink GPS-disabled mode.
Return Value (Returns):
- bool: Returns True if the current mode is MAVLink GPS-disabled mode; otherwise, returns False.
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: Returns True if the current mode is Redis full mode; otherwise, returns False.
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: Returns True if the current mode is Redis simplified mode; otherwise, returns False.
Exceptions (Raises): None


is_udp()

Function Description: Determines whether the current communication mode belongs

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

Return Value (Returns):

  • PID instance object

Exceptions (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

Return Value (Returns):

  • float: Computed PID control output

Exceptions (Raises):

  • None

Example:

# 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.
Return Value (Returns):

  • None

Exceptions (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)

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 via CtMode.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_fw is a position-velocity control interface specifically for fixed-wing aircraft; using it directly on multirotors will have no effect. Conversely, the multirotor velocity control interface send_vel_body is 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_full or is_mav_full, ensure sufficient simulation network bandwidth. If packet loss is severe, switch to the simplified is_udp_simple mode to reduce bandwidth usage.

Changelog

  • 2026-03-03: feat: SDK adds IP handling mechanism, compatible with cloud deployment of local versions
  • 2024-09-09: update: simulation mode for Mavlink_Vision
  • 2024-07-18: fix: update API homepage index
  • 2023-11-09: feat: add cloud-compatible interfaces