QGCCtrlAPI Interface Documentation¶
Introduction¶
Overview: This file implements a control interface for interacting with the QGroundControl ground station, and also provides a first-in-first-out (FIFO) cache utility class. It supports PX4 flight controller drone missions to send control commands and retrieve status information via QGroundControl.
In the RflySim drone simulation mission development workflow, QGroundControl is a commonly used ground station interaction tool, providing entry points for drone visualization monitoring, mission command transmission, and flight parameter debugging. This module encapsulates the QGroundControl communication and interaction logic adapted to the RflySim simulation environment, enabling developers to conveniently invoke ground station control functionalities in simulation missions. Additionally, the built-in FIFO cache class ensures stable handling of streaming data during interactions, safeguarding communication timing correctness.
This module is suitable for simulation mission development scenarios requiring coordination with the QGroundControl ground station, such as command relaying during third-party algorithm integration into simulations, manual ground station participation in simulation control, and flight state visualization debugging. It serves as the core foundational module for ground station interaction functionality within the RflySimSDK.
Quick Start¶
Minimal working example; copy and modify only the minimum required configurations to run.
from RflySimSDK.phm import QGCCtrlAPI
import time
# 1. Initialize the QGC control API, specifying drone ID as 1
qgc_ctrl = QGCCtrlAPI(ID=1)
# 2. Send disarming command to QGC (MAV_CMD_COMPONENT_ARM_DISARM=400, param1=1 indicates disarming)
qgc_ctrl.SendQgcCmdLong(command=400, param1=1)
print("Disarming command sent to drone")
time.sleep(2) # Wait for disarming to complete
# 3. Send takeoff command (MAV_CMD_NAV_TAKEOFF=22, param1 is target altitude, set to 5 meters)
qgc_ctrl.SendQgcCmdLong(command=22, param1=5)
print("Takeoff command sent, target altitude: 5 meters")
# 4. Retrieve text content output by QGC (example; modify to your actual flag file path)
flag_file_path = "C:/RflySim/WorkSpace/qgc_flag.txt"
content = qgc_ctrl.getTxtContent(flag_file_path)
print(f"Retrieved QGC text content: {content}")
# 5. Copy QGC log file to target location (example; modify to your own source and target paths)
# source_log = "C:/Program Files/QGroundGroundControl/log.txt"
# target_log = "./my_flight_log.txt"
# qgc_ctrl.copyLogFile(source_log, target_log)
# print("Log file copied successfully")
Environment and Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
copy,math,os,pymavlink.dialects.v20,shutil,socket,struct,sys,threading,time - Prerequisites: Before invoking this interface, ensure RflySimSDK is installed, and the PX4 flight controller and QGroundControl ground station simulation environment are launched in advance.
Core Interface Description¶
The module QGCCtrlAPI.py includes configuration variables, helper functions, and the core business class.
Global Constants and Enumerations¶
This section lists all globally accessible constants and enumerations defined in the module.
Standalone Constants¶
None
Global/Standalone Functions¶
None
QGCCtrlAPI Class¶
This class facilitates communication with the QGroundControl ground station, enabling transmission of PX4 long commands, retrieval of log text content, copying of log files, and requesting QGC logs. It is designed for ground station control and log collection scenarios in RflySim simulations.
__init__(ID=1)¶
Function Description: Initializes a QGCCtrlAPI object and binds it to a target drone ID.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
ID |
Any | No | 1 |
ID number of the target drone |
Return Value (Returns):
- Instance of
QGCCtrlAPI
Exceptions (Raises):
- None
SendQgcCmdLong(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0)¶
Function Description: Sends a PX4-formatted long command to QGroundControl to control the drone. Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
command |
Any | Yes | - | PX4 command ID specifying the type of command to send |
param1 |
Any | No | 0 |
Command parameter 1 |
param2 |
Any | No | 0 |
Command parameter 2 |
param3 |
Any | No | 0 |
Command parameter 3 |
param4 |
Any | No | 0 |
Command parameter 4 |
param5 |
Any | No | 0 |
Command parameter 5 |
param6 |
Any | No | 0 |
Command parameter 6 |
param7 |
Any | No | 0 |
Command parameter 7 |
Return Value (Returns):
- None
Exceptions (Raises):
- None
Example:
# Initialize QGC control object for drone ID 1
qgc_ctrl = QGCCtrlAPI(ID=1)
# Send disarming command (example command ID corresponds to PX4 disarming command ID)
qgc_ctrl.SendQgcCmdLong(400, 1, 0, 0, 0, 0, 0, 0)
---
#### `getTxtContent(flagFilePath)`
**Function Description**: Reads the content of a text file from a specified path, typically used to read marker files or log text generated by QGC.
**Parameters (Args)**:
| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `flagFilePath` | Any | Yes | - | Path to the text file to be read |
**Returns**:
- `str`: Content of the read text file
**Raises**:
- None
---
#### `copyLogFile(source, target)`
**Function Description**: Copies a log file generated by QGC from the source path to the target path, used for log backup and storage.
**Parameters (Args)**:
| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `source` | Any | Yes | - | Source path of the log file |
| `target` | Any | Yes | - | Target path of the log file |
**Returns**:
- None
**Raises**:
- None
---
#### `ReqQgcLog(timeout=180, CopterID=1)`
**Function Description**: Requests flight logs for a specified UAV from QGroundControl, with configurable timeout duration.
**Parameters (Args)**:
| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `timeout` | Any | No | `180` | Maximum wait time (in seconds) for log retrieval |
| `CopterID` | Any | No | `1` | ID of the UAV whose logs are to be retrieved |
**Returns**:
- None
**Raises**:
- None
**Example**:
```python
qgc_ctrl = QGCCtrlAPI(ID=1)
# Request logs for UAV 1, wait up to 3 minutes
qgc_ctrl.ReqQgcLog(timeout=180, CopterID=1)
# Copy logs to a specified path
qgc_ctrl.copyLogFile("qgc_default_log_path/log.txt", "my_experiment/log_20240101.txt")
# Read log content
log_content = qgc_ctrl.getTxtContent("my_experiment/log_20240101.txt")
fifo Class¶
A First-In-First-Out (FIFO) queue data structure for storing and managing data elements in the order they were inserted, adhering to the principle that the earliest written data is read first.
__init__()¶
Function Description: Initializes an empty FIFO queue object.
Parameters (Args): - None
Returns:
fifoinstance object
Raises: - None
write(data)¶
Function Description: Appends a data element to the tail of the queue.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
data |
Any type |
Yes | - | Data element to be written into the queue |
Returns: - None
Raises: - None
read()¶
Function Description: Reads and removes the earliest data element from the head of the queue.
Parameters (Args): - None
Returns:
Any type: The earliest data element written into the queue
Raises: - None
Example:
from RflySimSDK.phm import fifo
# Initialize FIFO queue
fifo_queue = fifo()
# Write data
fifo_queue.write(10)
fifo_queue.write("hello")
# Read data in order
first_data = fifo_queue.read()
second_data = fifo_queue.read()
# Output: first_data is 10, second_data is "hello"
Advanced Usage Examples¶
Demonstrates complex composite scenarios (e.g., multi-class collaboration, asynchronous control, batch operations)
```python import RflySimSDK.phm as phm import threading import time
Multi-threaded asynchronous log retrieval and batch storage: multi-task collaboration scenario¶
def async_log_worker(qgc_api, fifo, req_ids): # Batch request logs from multiple UAVs for req_id in req_ids: qgc_api.ReqQgcLog(req_id) time.sleep(0.5) # After retrieving all logs, write them into the pipe for main thread processing all_log = qgc_api.getTxtContent() fifo.write(all_log.encode('utf-8'))
Initialize API objects¶
qgc_ctrl = phm.QGCCtrlAPI() log_fifo = phm.fifo()
List of UAV IDs whose logs need to be fetched¶
target_uav_ids = [1, 3, 5, 7]
Start an asynchronous thread to handle log requests, avoiding blocking the main control flow¶
log_thread = threading.Thread(target=async_log_worker, args=(qgc_ctrl, log_fifo, target_uav_ids)) log_thread.start()
Main task continues executing UAV flight control while asynchronously retrieving logs¶
qgc_ctrl.SendQgcCmdLong("mode takeoff")
Read the batched logs retrieved asynchronously from the pipe¶
raw_log = log_fifo.read() parsed_log = raw_log.decode('utf-8')
Batch copy logs to a local backup directory¶
qgc_ctrl.copyLogFile("./uav_batch_log_backup/")
Notes and Pitfall Avoidance Guide¶
- SendQgcCmdLong Long Command Sending Limitation: The length of a single command sent via this method is constrained by the QGC ground station communication protocol. Do not send commands exceeding 1024 bytes; overly long commands will be directly discarded by the ground station without any error response.
- fifo Pipe Read/Write Order Dependency: When using the
fifoclass for inter-process data transfer, the write operation must be completed before initiating the read operation. Calling thereadmethod on an empty pipe will cause the thread to block indefinitely, preventing it from responding to other operations. - Log Pulling Timing Requirement: After calling
ReqQgcLogto request logs, you must wait at least 0.3 seconds before callinggetTxtContentto retrieve the content. Reading directly without waiting will result in empty content or incomplete log fragments. - copyLogFile Path Format Requirement: This method requires the provided storage path to end with a forward slash
/. Incorrect path formatting will cause log file storage to fail, and the target folder will not be automatically created.
Changelog¶
2024-08-02: chore: Added code comments for generating HTML-format API documentation2024-07-18: fix: Updated API homepage index2023-11-10: feat: Added interface for downloading logs via QGC, applicable to both hardware-in-the-loop and software-in-the-loop scenarios