Skip to content

AutoMavCtrl Interface Documentation

Introduction

Overview: AutoMavCtrl.py is the core module for automated control of drone swarms within the RflySimSDK platform, providing a complete closed-loop management capability spanning environment initialization, simulation monitoring, and multi-drone collaborative control.

This module is specifically designed for complex drone swarm simulation tasks, integrating three functional layers: environment configuration registration, simulation status monitoring, and automated control. The InitMavAutoEnv class handles initialization of multi-drone simulation environments and interfaces with underlying communication protocols. AutoMavMonitor and AutoMavCtrler respectively manage state monitoring threads and independent control threads, supporting lifecycle management of simulation software instances and drone threads through a two-tier monitoring mechanism (MavMonitor and SimMonitor). This module is suitable for research and engineering scenarios requiring high reliability and scalable swarm control, such as formation flight, cooperative obstacle avoidance, and distributed task planning.

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: Ass, AutoMavCmd, AutoMavDB, AutoREG, AutoVisConf, PX4MavCtrlV4, UE4CtrlAPI, cv2, numpy, os, re, subprocess, sys, threading, time, tkinter, tkinter.messagebox
  • Prerequisites: Before invoking this interface, ensure the simulation environment has been initialized and communication with the MAVLink flight controller has been established.

Core Interface Description

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

Global Constants and Enumerations

This section lists all globally accessible constants and enumeration definitions directly referenced within the module.

Standalone Constants

None


Enumerations

MAV_COMMON_REG
Name Type Value Description
AutoMavThreadsContainer unknown [] -
SimProcessStartContainer unknown [] -
SimProcessEndContainer unknown [] -
Lock str threading.Lock() -
DataRecordThreadsContainer unknown [] -
SimProcessObj unknown None -

Global / Standalone Functions

MavMonitor()

Function Description: Monitors all drone instance threads AutoMavCtrler.AutoMavThread. Once all drones are initialized, starts all threads AutoMavCtrler.AutoMavRun. Parameters: None
Return Value: None
Exceptions: None

SimMonitor()

Function Description: Monitors all simulation software objects; only launches the .bat script with the smallest airframe index. Parameters: None
Return Value: None
Exceptions: None

ReSetREG()

Function Description: (To be补充ed) Parameters: None
Return Value: None
Exceptions: None


InitMavAutoEnv Class

A configuration class for initializing multi-drone automated simulation environments, supporting multiple aircraft types, map loading, and .bat environment parameter settings.

__init__(mav, conf, map)

Function Description: Initializes the multi-drone automated simulation environment configurator
Parameters (Args):

Parameter Name Type Required Default Description
mav object Yes - Drone control object
conf object Yes - Environment configuration object
map object Yes - Map configuration object

Return Value (Returns):

  • Instance of InitMavAutoEnv

Exceptions (Raises):

  • None

InitMAVEnv()

Function Description: Initializes the MAV environment
Parameters (Args):

  • None

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

BInfo()

Function Description: Configures drone information, including number of drones, airframe framework, count of airframe frameworks, airframe framework dictionary, and test mode parameters
Parameters (Args):

  • None

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

BReset()

Function Description: Resets the .bat environment to its original state
Parameters (Args):

  • None

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

BatEnvConf()

Function Description: Modifies startup parameters, indices, and drone counts for .bat environments in multi-drone scenarios; retains only one set of startup configuration, starting index, and drone count for a single .bat software environment
Parameters (Args):

  • None

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

BSingle(Path)

Function Description: Configures single-drone path
Parameters (Args):

Parameter Name Type Required Default Description
Path str Yes - Path string

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

GetPath(Frame)

Function Description: Retrieves path configuration for a specified airframe type
Parameters (Args):

Parameter Name Type Required Default Description
Frame str Yes - Airframe framework name

Return Value (Returns):

  • str: Path configuration corresponding to the specified airframe

Exceptions (Raises):

  • None

BVNum(path, num)

Function Description: Sets the drone count corresponding to a given path
Parameters (Args):

Parameter Name Type Required Default Value Description
path str Yes - Path string
num int Yes - Number of aircraft

Returns:

  • None

Raises:

  • None

BEnv(Path, Index, Num)

Function Description: Configures the Bat environment path, starting index, and number of aircraft.
Arguments:

Parameter Name Type Required Default Value Description
Path str Yes - Environment path
Index int Yes - Starting index
Num int Yes - Number of aircraft

Returns:

  • None

Raises:

  • None

BEMap(path)

Function Description: Sets the environment map, supporting scenarios such as Grasslands, OldFactory, RealForestLake, and NeighborhoodPark.
Arguments:

Parameter Name Type Required Default Value Description
path str Yes - Map scene path

Returns:

  • None

Raises:

  • None

BMap()

Function Description: Configures the map environment.
Arguments:

  • None

Returns:

  • None

Raises:

  • None

AutoMavMonitor Class

The UAV automatic monitoring class, used for multi-threaded monitoring of simulation process status, data logging, and simulation lifecycle management.

__init__()

Function Description: Initializes the monitor instance.
Arguments: No parameters.

Returns:

  • AutoMavMonitor instance object.

Raises:

  • None

AutoMavThreadMonitor()

Function Description: Automatic multi-rotor thread monitoring method, used to monitor the runtime status of threads related to automatic multi-rotor operations.
Arguments: No parameters.

Returns:

  • None

Raises:

  • None

SimProcessStartThreadMonitor()

Function Description: Simulation process startup thread monitoring method. Sets the aircraft model with the smallest serial number (Frame type) as the main control batch (main Bat), i.e., the one responsible for launching all simulation software for this batch. Therefore, the batch with the smallest serial number—the quadcopter (AutoREG.MAV_FRAME [1,2,3])—must be opened.
Arguments: No parameters.

Returns:

  • None

Raises:

  • None

Example:

monitor = AutoMavMonitor()
monitor.SimProcessStartThreadMonitor()  # Start simulation process monitoring for the model with the smallest serial number

---

#### `SimProcessEndThreadMonitor()`

**Function Description**: Simulation process end thread monitoring method. Sets the frame type with the smallest serial number as the main batch (main Bat), i.e., launches all simulation software for this batch. Therefore, the batch with the smallest serial numberthe quadcopter (AutoREG.MAV_FRAME [1,2,3])must be opened.

**Arguments (Args)**: None

**Returns**:

- None

**Raises**:

- None

**Example**:

```python
monitor = AutoMavMonitor()
monitor.SimProcessEndThreadMonitor()  # Ends simulation process monitoring for the frame type with the smallest serial number

DataRecordThreadMonitor()

Function Description: Data record thread monitoring method, used to monitor the runtime status of the data record thread.
Arguments (Args): No arguments

Returns:
- None

Raises:
- None

AutoMavCtrler Class

Autonomous controller class for unmanned aerial vehicles (UAVs), used to implement automated control of multi-rotor aircraft.

__init__(mav, conf)

Function Description: Initializes an AutoMavCtrler controller instance, configuring the simulation environment and vehicle type.

Arguments (Args):

Parameter Type Description
mav object MAVLink connection object or simulation interface instance
conf list Configuration list, formatted as ['Quadcopter', 'SITL', 3], representing vehicle type, simulation mode, and quantity, respectively

Returns: None

Raises: None

InitModelConf()

Function Description: Initializes the custom model framework and configuration paths. Supports multiple aircraft types:

  • 1: Quadrotor
  • 2: Fixed-wing aircraft
  • 3: Unmanned Surface Vehicle (USV)

Arguments (Args): No arguments

Returns: None

Raises: None


InitMavEnv()

Function Description: Initializes the MAV environment. Creates necessary resources and configurations required for the simulation environment.

Arguments (Args): No arguments

Returns: None

Raises: None


SimProcessLoopStart()

Function Description: Starts the simulation processing loop. Begins execution of the main simulation loop to advance simulation time.

Arguments (Args): No arguments

Returns: None

Raises: None


SimProcessLoopEnd()

Function Description: Ends the simulation processing loop. Stops the main simulation loop and releases associated resources.

Arguments (Args): No arguments

Returns: None

Raises: None


StartSimProcess()

Function Description: Starts the simulation process. Initializes and launches the entire simulation workflow, including environment configuration and communication setup.

Arguments (Args): No arguments

Returns: None

Raises: None


EndSimProcess()

Function Description: Ends the simulation process. Stops the entire simulation workflow and closes all related resources and communication connections.

Arguments (Args): No arguments

Returns: None

Raises: None


DataRecordLoop()

Function Description: Data recording loop. Continuously executes the data recording workflow, periodically sampling and storing simulation data.

Arguments (Args): No arguments

Returns: None

Raises: None


DataRecord()

Function Description: Executes data recording. Captures current simulation state data and saves it to a designated storage location.

Arguments (Args): No arguments

Returns: None

Raises: None


InitMavComm()

Function Description: Initializes MAV communication. Establishes communication connections with the simulator or real aircraft and configures communication parameters.

Arguments (Args): No arguments

Returns: None

Raises: None


EndMavComm()

Function Description: Terminates MAV communication. Closes communication connections with the simulator or aircraft and releases communication resources.

Arguments (Args): No arguments

Returns: None

Raises: None


AutoMavLoopStart()

Function Description: Starts the AutoMav loop. Begins execution of the main loop for autonomous control algorithms, enabling autonomous flight control of the aircraft.

Arguments (Args): No arguments

Returns: None

Raises: None


ShowWinLoop()

Function Description: Display window loop. Continuously updates and refreshes the visualization window to display simulation states and aircraft data.

Arguments (Args): No arguments

Returns: None

Raises: None


ShowWin()

Function Description: Display window. Creates or updates the visualization window to present the current simulation state and control information.

Arguments (Args): No arguments

Returns: None

Raises: None


AutoMavRun()

Function Description: Runs AutoMav. Launches the complete autonomous control workflow, integrating all functional modules including simulation, communication, control, and visualization.

Arguments (Args): No arguments

Returns: None

Raises: None


TRIGGERMAVCMD(ctrlseq)

Function Description: Triggers an MAV command. Executes the corresponding MAV control command based on the specified control sequence.

Arguments (Args):

Parameter Name Type Required Default Description
ctrlseq Any type Yes None Control sequence specifying the MAV command sequence to be executed

Returns: No return value specified

Raises: None

is_alive()

Function Description: Checks whether the controller is active.
Arguments (Args): No arguments

Returns: bool — Controller activity status; True indicates active, False indicates inactive.
Raises: None


calculate_flight_status(angular_velocity_data)

Function Description: Calculates flight status based on angular velocity data.
Arguments (Args):

Parameter Name Type Required Default Value Description
angular_velocity_data - Yes - Angular velocity data used for flight state calculation

Returns: Computed flight state information.
Raises: None


GetDesiredPV()

Function Description: Retrieves the desired position and velocity (Position and Velocity).
Args: No arguments

Returns: Desired position and velocity information.
Raises: None


Deviation(desired, true)

Function Description: Computes the deviation between the desired value and the actual value.
Args:

Parameter Name Type Required Default Value Description
desired - Yes - Desired target value
true - Yes - Actual true value

Returns: Deviation between the desired and actual values.
Raises: None


CMDANA(cmd)

Function Description: Analyzes and processes control commands (Command Analysis).
Args:

Parameter Name Type Required Default Value Description
cmd - Yes - Control command to be analyzed

Returns: Result of command analysis.
Raises: None


Get_TestResult(test_result)

Function Description: Retrieves or processes test results.
Args:

Parameter Name Type Required Default Value Description
test_result - Yes - Raw test result data generated during testing

Returns: Processed test result data.
Raises: None

Advanced Usage Example

Demonstrates complex composite scenarios (e.g., multi-class collaboration, asynchronous control, batch operations)

```python from RflySimSDK.phm.AutoMavCtrl import InitMavAutoEnv, AutoMavCtrler, AutoMavMonitor import threading import time

Scenario: Batch initialization of multiple UAVs with asynchronous monitoring

class BatchMavController: def init(self, mav_num=5): self.mav_env = InitMavAutoEnv() self.controllers = [] self.monitors = [] self.mav_num = mav_num

def batch_init(self):
    """Batch initialize multi-UAV environment"""
    # Configure environment parameters
    self.mav_env.BatEnvConf(mavNum=self.mav_num)
    self.mav_env.BEnv()  # Enable environment

    for i in range(self.mav_num):
        # Create an independent controller for each UAV
        ctrl = AutoMavCtrler()
        ctrl.InitMavEnv(mavID=i)
        ctrl.InitMavComm()  # Initialize communication

        # Create a monitor
        mon = AutoMavMonitor()

        self.controllers.append(ctrl)
        self.monitors.append(mon)

def async_start_all(self):
    """Asynchronously start all simulation processes"""
    threads = []
    for i, (ctrl, mon) in enumerate(zip(self.controllers, self.monitors)):
        t = threading.Thread(
            target=self._single_mav_process,
            args=(i, ctrl, mon)
        )
        threads.append(t)
        t.start()

    return threads

def _single_mav_process(self, mav_id, ctrl, mon):
    """Complete processing flow for a single UAV"""
    # Start simulation monitoring
    mon.SimProcessStartThreadMonitor(mavID=mav_id)

    # Start simulation process
    ctrl.StartSimProcess()
    ctrl.SimProcessLoopStart()

    # Data recording monitoring
    mon.DataRecordThreadMonitor(mavID=mav_id)
    ctrl.DataRecordLoop()

    # End flow
    ctrl.SimProcessLoopEnd()
    ctrl.EndSimProcess()
    mon.SimProcessEndThreadMonitor(mavID=mav_id)

    # Clean up communication
    ctrl.EndMavComm()

Usage Example

if name == "main": batch_ctrl = BatchMavController(mav_num=3) batch_ctrl.batch_init() threads = batch_ctrl.async_start_all()

# Wait for all threads to complete
for t in threads:
    t.join()
print("All drone batch tasks completed")

Notes and Pitfall Avoidance Guide

  • Call Order of InitMavEnv and InitMavComm: InitMavEnv must be called first to initialize environment configuration, followed by InitMavComm to establish the communication link. Reversing this order will cause communication initialization failure or prevent retrieval of correct MAV parameters.

  • Mutual Exclusivity of BVNum and BSingle: BVNum is used to set the number of batch drones, while BSingle marks single-drone mode. Using both in the same configuration may cause conflicts; select either batch mode or single-drone configuration based on actual requirements, and avoid calling both repeatedly to prevent abnormal environment configuration.

  • Lifecycle Management of Monitoring Threads: Monitoring methods of AutoMavMonitor (e.g., SimProcessStartThreadMonitor, DataRecordThreadMonitor) must be invoked before the corresponding simulation phase begins, and should be paired with the process methods of AutoMavCtrler. Premature termination or omission of monitoring may result in incomplete data recording or erroneous process state judgment.

  • Paired Invocation of SimProcessLoopStart and SimProcessLoopEnd: These two methods mark the boundaries of the main simulation loop. If SimProcessLoopEnd is not called due to an abnormal exit, it may leave simulation processes running and cause resource leaks. It is recommended to ensure the end method is executed within a try...finally block.

  • Map Loading Priority of BEMap and BMap: BEMap is used to load the environment map, while BMap handles basic map configuration. When both are present, pay attention to the loading order, as the environment map may override certain configurations from the basic map. It is recommended to complete all map-related configurations before invoking BEnv to enable the environment, to avoid inconsistencies in map parameters during runtime.

Changelog

  • 2026-04-08: 🐛 fix: Corrected variable name typo
  • 2025-04-01: fix
  • 2024-08-02: chore: Added code comments for generating HTML-format API documentation
  • 2024-07-18: fix: Updated API homepage index
  • 2024-05-01: fix: Added QGC startup command to prevent incorrect connection to the flight controller during simulation, and to avoid serial port conflicts (e.g., occupied during HITL or conflicting between serial port and UDP during SITL)
  • 2023-11-09: commit by Jinhu Tu
  • 2023-11-09: fix: Added interface class file for automated safety assessment