RflyRosStart Interface Documentation¶
Introduction¶
Overview: This file provides the
RflyRosStartclass, which is used to create ROS communication connection instances adapted to the RflySim platform. It supports two methods for initializing communication: via aircraft ID or custom communication port numbers.
In RflySim drone simulation development, third-party functional development based on ROS, as well as communication and interaction between external nodes and simulated drones on the simulation side, require a standardized communication entry point. This module handles the initialization configuration of communication instances, aligning with the platform’s communication rules. It not only allows developers to quickly establish a communication link with a specified simulated drone using the aircraft ID, but also supports flexible configuration of non-standard communication scenarios via custom port numbers. This makes it suitable for secondary development, ROS node extension, custom external control interaction, and other development scenarios.
Quick Start¶
Minimal working example; copy and modify only the minimum required configuration to run.
from RflySimSDK.ctrl import RflyRosStart
import time
# 1. Initialize RflyRosStart object with default configuration: local connection, aircraft ID 1, UDP communication
ros_start = RflyRosStart(ID=1, ip="127.0.0.1", Com="udp", port=0, simulinkDLL=False)
# 2. Start ROS and MAVROS communication loop
ros_start.InitRosLoop()
print("MAVROS started, maintaining communication for 10 seconds...")
# 3. Keep running to simulate a 10-second communication process
time.sleep(10)
# 4. Terminate ROS communication loop
ros_start.EndRosLoop()
# 5. Terminate MAVROS process
ros_start.KillMavRos()
print("MAVROS closed, program exiting")
Environment and Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
ctrl.IpManager,math,os,platform,psutil,pymavlink,socket,struct,subprocess,sys,threading,time - Prerequisites: Before calling this interface, you must complete the RflySimSDK environment setup and import the corresponding module.
Core Interface Description¶
The module RflyRosStart.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
RflyRosStart Class¶
Creates an instance for communication between the RflySim platform and the ROS environment. Supports multiple connection modes including UDP, direct serial connection to the flight controller, and direct UDP connection, making it adaptable to both simulation and real-aircraft scenarios.
__init__(ID=1, ip=127.0.0.1, Com=udp, port=0, simulinkDLL=False)¶
Function Description: Initializes the RflyRosStart communication instance and configures different connection modes and communication parameters based on input arguments.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
ID |
int |
No | 1 |
If ID ≤ 10000, it represents the CopterID of the drone; if ID > 10000, it represents the communication port number port, compatible with the legacy interface rule: port = 20100 + CopterID * 2 - 2 |
ip |
str |
No | 127.0.0.1 |
Target IP address for data transmission; defaults to localhost. For distributed simulation, specify a LAN IP or use the broadcast address 255.255.255.255 |
Com |
str |
No | 'udp' |
Connection mode to Pixhawk: udp indicates receiving MAVLink messages forwarded by CopterSim; a serial port address (e.g., COM3 on Windows, /dev/ttyUSB0 on Linux) indicates direct USB/telemetry connection to the flight controller; Direct indicates direct UDP mode, where the same port is used for both sending and receiving data |
port |
int |
No | 0 |
In UDP mode, setting to 0 automatically calculates the port based on CopterID; a value greater than 0 forces usage of the specified port. In serial mode, it specifies the baud rate, with 0 corresponding to the default 57600. In Direct mode, it specifies the send/receive port number. In Redis mode, it specifies the server port, with 0 corresponding to the default 6379 |
simulinkDLL |
bool |
No | False |
Whether it is the Simulink-generated DLL mode, for compatibility with Simulink co-simulation scenarios |
Returns:
RflyRosStartinstance object
Raises:
- None
InitRosLoop()¶
Function Description: Initializes the ROS communication loop and starts MAVLink data reception and ROS node-related processes.
Parameters (Args): - None
Returns:
- None
Raises:
- None
Example:
# Initialize simulation UDP communication mode and start ROS loop
ros_comm = RflyRosStart(ID=1)
ros_comm.InitRosLoop()
KillMavRos()¶
Function Description: Terminates MAVLink and ROS-related processes and closes the communication connection.
Parameters (Args): - None
Returns:
- None
Raises:
- None
EndRosLoop()¶
Function Description: Ends the ROS communication loop and cleans up communication-related resources.
Parameters (Args): - None
Returns:
- None
Raises:
- None
Example:
# Serial connection to real aircraft, initialize and terminate communication
ros_comm = RflyRosStart(ID=1, Com='COM3', port=57600)
ros_comm.InitRosLoop()
# After business logic processing, terminate communication
ros_comm.EndRosLoop()
---
## Advanced Usage Example
> Demonstrates complex composite scenarios (e.g., multi-agent collaboration, asynchronous control, batch operations)
This example illustrates a multi-agent collaboration scenario in multi-UAV simulation tasks:
batch launching corresponding MavROS nodes for each UAV via the PX4 flight controller control class, asynchronously executing the simulation mission, then sequentially shutting down the nodes after mission completion, and finally terminating the ROS process loop.
```python
import RflySimSDK.ctrl as rfly_ctrl
from RflySimSDK.vehicle import PX4Vehicle
# Batch initialize ROS node process loops for 5 UAVs
ros_manager = rfly_ctrl.RflyRosStart()
vehicle_list = [PX4Vehicle(i+1) for i in range(5)]
for vehicle in vehicle_list:
# Launch an independent MavROS node for each UAV
ros_manager.InitRosLoop(vehicle.vehicle_id)
# Asynchronously execute multi-UAV formation mission
async def run_coop_task():
await [vehicle.takeoff(alt=5) for vehicle in vehicle_list]
await [vehicle.go_to(-100 + 20*i, 0, 5) for i, vehicle in enumerate(vehicle_list)]
await [vehicle.land() for vehicle in vehicle_list]
# Batch shut down nodes after mission completion
import asyncio
asyncio.run(run_coop_task())
for vehicle in vehicle_list:
ros_manager.KillMavRos(vehicle.vehicle_id)
# Finally terminate the entire ROS loop process
ros_manager.EndRosLoop()
Notes and Pitfall Avoidance Guide¶
InitRosLoopCall Order Requirement: This method must be invoked after the RflySim simulation environment and the PX4 flight controller process have been fully started. Calling it prematurely will result in failure to connect to the flight controller, directly throwing a node startup failure exception.- MavROS Node Resource Release: The
EndRosLoopmethod can only be called after each individual UAV’s MavROS node has been closed viaKillMavRos. Unreleased nodes will persist as background system processes, consuming port and memory resources. - Correctness of IDs in Multi-UAV Scenarios: The arguments passed to
InitRosLoopandKillMavRosmust strictly match the actual UAV IDs. Mismatched IDs may cause unintended shutdown of other UAVs’ nodes, leading to complete simulation mission failure. - Resource Conflicts from Repeated Initialization: Do not invoke
InitRosLooprepeatedly for the same UAV ID. Duplicate startups will cause multiple processes to occupy the same ROS port, resulting in node startup failure.
Changelog¶
2026-03-03: feat: SDK adds IP handling mechanism for compatibility with cloud deployment of local versions2024-11-20: Added support for real-world hardware integration2024-11-19: Updated management of multi-level subprocess calls2024-11-19: Optimized MavROS startup script, primarily in process management; supports ROS1/ROS2 kill operations2024-08-14: fix: Updated HTML version of API documentation2024-07-18: fix: Updated API homepage index2024-05-19: fix: Updated2024-05-15: fix: Optimized initialization mechanism2024-04-16: Fixed subprocess-based MavROS startup blocking issues for ROS1/ROS2 compatibility2024-03-08: Adapted interface for ROS2; fixed subprocess module usage issues2024-01-29: fix: Added MavROS control example