ReqCopterSim Interface Documentation¶
Introduction¶
Overview: UE4 drone simulation state synchronization and request module, providing EKF initialization detection, timestamp synchronization, and multi-drone simulation state querying capabilities.
This module is specifically designed for the RflySim drone simulation platform's UE4 3D scene, addressing state synchronization challenges in multi-drone collaborative simulations. Core scenarios include:
- Distributed simulation: detecting EKF (Extended Kalman Filter) initialization states across multiple drones
- Timestamp synchronization between UE4 engine and CopterSim
- Batch querying of 3D position fix status for all drones (allCopterSim3DFixed)
The module implements non-blocking state polling via classes Ue4EKFInit and GetUe4EKFInit. Class RflyTimeStmp supports sending timestamp-synchronization messages with checksums to port 20005 on a specified remote host. ReqCopterSim encapsulates the request-response protocol with the CopterSim simulation core, making it suitable for hardware-in-the-loop (HIL) simulations and visual-inertial navigation algorithm validation scenarios requiring precise timing control.
Quick Start¶
Minimal working example; copy and modify minimal configuration to run.
# Import ReqCopterSim class for communication with RflySim's CopterSim
from RflySimSDK.ctrl import ReqCopterSim
# Create ReqCopterSim instance; by default, listens on port 20005 for RflyTimeStmp messages
req = ReqCopterSim()
# Get local IP address (static method, callable without instantiation)
local_ip = ReqCopterSim.getLocalIp()
print(f"Local IP: {local_ip}")
# Validate IP address format
is_valid = req.isValidIp("192.168.1.1")
print(f"IP validation result: {is_valid}")
# Get list of IP addresses for all network interfaces on this machine
all_ips = req.get_all_ip()
print(f"All IPs: {all_ips}")
Environment & Dependencies¶
- Python Environment:
>= 3.8.10 - Dependencies:
copy,os,psutil,re,socket,struct,threading,time - Prerequisites: Before calling this interface, an仿真 environment connection must first be established via UE4 or CopterSim.
Core Interface Description¶
The module ReqCopterSim.py includes configuration variables, helper functions, and core business classes.
Global Constants and Enumerations¶
This section lists all globally accessible constants and enumerations directly referenceable within the module.
Standalone Constants¶
None
Global/Standalone Functions¶
None
Ue4EKFInit Class¶
This class initializes the EKF (Extended Kalman Filter) state within the UE4 scene, typically resetting pose estimation before drone simulation begins.
__init__()¶
Function Description: Initializes an Ue4EKFInit instance, preparing EKF initialization functionality.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| - | - | - | - | No parameters required |
Returns:
Ue4EKFInitinstance object
Raises:
- None
reset()¶
Function Description: Resets the EKF state in the UE4 scene, restoring pose estimation to its initial values.
Parameters (Args):
| Parameter Name | Type | Required | Default | Description |
|---|---|---|---|---|
| - | - | - | - | No parameters required |
Returns:
- None
Raises:
- None
Example:
GetUe4EKFInit Class¶
This class is used to initialize and continuously detect the 3D fixed state of all CopterSim instances. Detection begins immediately after initialization, and external code must periodically query the allCopterSim3DFixed property to obtain the detection results.
__init__(expected_copter_ids, localIp="None")¶
Function Description: Initializes the detector and starts detecting the 3D fixed state of all specified CopterSim instances.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
expected_copter_ids |
list |
Yes | - | List of CopterSim IDs to be detected |
localIp |
str |
No | "None" |
Local IP address used for network communication |
Returns:
- Instance of
GetUe4EKFInit
Raises:
- None
RflyTimeStmp Class¶
RflyTimeStmp is a timestamp data structure for the RflySim simulation platform, primarily used for time synchronization in heartbeat packets. This structure contains the simulation start time, current timestamp, and heartbeat counter, and is transmitted via UDP to port 20005 on a specified remote computer, enabling time synchronization and heartbeat monitoring in multi-machine collaborative simulations.
__init__(iv)¶
Function Description: Initializes an RflyTimeStmp instance, setting up timestamp-related member variables based on the input parameters.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
iv |
list |
Yes | - | List containing timestamp data, formatted as [checksum, copterID, SysStartTime, SysCurrentTime, HeartCount] |
Returns:
- Instance of
RflyTimeStmp
Raises:
- None
Update(iv)¶
Function Description: Updates the timestamp data of an RflyTimeStmp instance, enabling dynamic updates for heartbeat packet data.
Parameters (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
iv |
list |
Yes | - | List containing updated timestamp data, formatted as [checksum, copterID, SysStartTime, SysCurrentTime, HeartCount] |
Returns:
- None
Raises:
- None
Example:
# Create a timestamp instance
timestamp_data = [123456789, 1, 1699123456789, 1699123466789, 100]
rfly_ts = RflyTimeStmp(timestamp_data)
# Update heartbeat data
new_data = [123456789, 1, 1699123456789, 1699123476789, 101]
rfly_ts.Update(new_data)
ReqCopterSim Class¶
A request class for communicating with the RflySim simulation environment, primarily responsible for listening on a specified port to obtain simulation timestamp information.
__init__(updateMsg=True)¶
Function Description: Initializes a ReqCopterSim instance and starts listening on port 20005 to receive RflyTimeStmp messages, thereby obtaining the simulation time information for a specified UAV.
Arguments (Args):
| Parameter Name | Type | Default Value | Description |
|---|---|---|---|
updateMsg |
bool |
True |
Whether to enable message update functionality; when set to True, the class automatically listens and updates messages |
Returns (Returns):
| Type | Description |
|---|---|
None |
Constructor returns no value |
Raises (Raises):
| Exception Type | Description |
|---|---|
socket.error |
Thrown when binding or listening on port 20005 fails |
OSError |
Thrown when network interface initialization fails |
getLocalIp()¶
Function Description: Retrieves the local IP address. It first attempts to connect to 8.8.8.8 to determine the local IP; if that fails, it tries 114.114.114.114; if both fail, it returns 127.0.0.1.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): str — Local IP address string, e.g., "192.168.1.100"
Raises (Raises): None
isValidIp(address)¶
Function Description: Validates whether the given string is a valid IPv4 address.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
address |
str |
Yes | — | The IP address string to validate |
Returns (Returns): bool — Returns True if address is a valid IPv4 address; otherwise returns False
Raises (Raises): None
get_all_ip()¶
Function Description: Retrieves a list of all IPv4 addresses assigned to the local machine’s network interfaces, including 127.0.0.1.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): list[str] — List containing all IPv4 addresses
Raises (Raises): None
get_all_enable_ip()¶
Function Description: Retrieves a list of IPv4 addresses from all active (enabled) network interfaces on the local machine, filtering out disabled or disconnected interfaces.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): list[str] — List containing all active IPv4 addresses
Raises (Raises): None
isIpLocal(IP)¶
Function Description: Determines whether the given IP address is a local address (including 127.0.0.1 and all IPs assigned to local network interfaces).
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
IP |
str |
Yes | — | The IP address string to check |
Returns (Returns): bool — Returns True if IP is a local address; otherwise returns False
Raises (Raises): None
getAllCopterID()¶
Function Description: Retrieves a list of all registered/active Copter (UAV) IDs in the current system.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): list[int] — List containing all Copter IDs
Raises (Raises): None
updateSimMsg()¶
Function Description: Updates (receives and processes) simulation messages from CopterSim. This method receives UDP packets and updates internal simulation state information.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): None
Raises (Raises): None
getSimIpList()¶
Function Description: Retrieves a list of IP addresses for all currently registered simulations.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters
Returns (Returns): list[str] — List containing all simulation IP addresses
Raises (Raises): None
getSimIpID(CopterID=1)¶
Function Description: Retrieves the simulation IP address corresponding to a given Copter ID. Returns an empty string if the ID is not found.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
CopterID |
int |
No | 1 |
The UAV ID to query |
Returns (Returns): str — Simulation IP address corresponding to the given ID; empty string if not found
Raises (Raises): None
getHostIP()¶
Function Description: Retrieves the host (Host) IP address. Similar to getLocalIp(), but may employ different strategies depending on specific network configurations.
Arguments (Args):
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
No parameters.
Returns: str – Host IP address string.
Raises: None.
sendReCopterSim(CopterID=1, isReqIP=1, UDP_mode=-1, isXyYaw=0, xyYaw=[0, 0, 0], isZRP=0, zRollPitch=[0, 0, 0], otherParams=[0, 0, 0, 0])¶
Function Description: Sends a request message to CopterSim to reconfigure simulation parameters, including requesting IP, setting initial position, modifying UDP mode, etc. Supports advanced configurations such as GPS origin setting and GPS position setting.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 1 | Target UAV ID for request validation |
| isReqIP | int |
No | 1 | Whether to request IP. >0 enables online connection and sends flight controller data to this computer |
| UDP_mode | int |
No | -1 | UDP transmission mode. <0: no response; ≥0: change to specified mode |
| isXyYaw | int |
No | 0 | Whether to set XY position and yaw angle. >0 uses xyYaw values to redeploy aircraft position. Special values: 2 sets GPS origin (lat/lon/alt); 3 sets GPS position (lat/lon/yaw) |
| xyYaw | list[float] |
No | [0, 0, 0] | XY position and yaw angle [x, y, yaw], in meters and degrees. When isXyYaw=2: [lat, lon, alt]; when isXyYaw=3: [lat, lon, yaw] |
| isZRP | int |
No | 0 | Whether to set Z altitude and roll/pitch angles. >0 uses zRollPitch values; otherwise, Z aligns with terrain and roll/pitch angles are 0 |
| zRollPitch | list[float] |
No | [0, 0, 0] | Z altitude, roll angle, pitch angle [z, roll, pitch], in meters and degrees; Z direction is positive downward |
| otherParams | list[int] |
No | [0, 0, 0, 0] | Reserved parameters, 4 bytes total, for future use |
Returns: None.
Raises: None.
sendReDllMap(CopterID=0, dllOrMap=-1, index=-1, name="")¶
Function Description: Requests to change the DLL model or map in CopterSim. Switching commands can be sent to a specified aircraft, all aircraft, or broadcast.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 0 | Target aircraft ID. 0: no response; -1: broadcast to all aircraft; >0: specify aircraft |
| dllOrMap | int |
No | -1 | Switching option. ≤0: no response; 1: change DLL model; 2: change map |
| index | int |
No | -1 | Option ID index. <0: no response; use name to specify option; ≥0: use index instead of name to specify option |
| name | str |
No | "" | Name of DLL model or map, max 48 bytes |
Returns: None.
Raises: None.
sendReSimDllName(CopterID=1, name="")¶
Function Description: Requests to set the DLL model name for a specified CopterSim instance.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 1 | Target UAV ID |
| name | str |
No | "" | Name of the DLL model |
Returns: None.
Raises: None.
sendReSimDllIdx(CopterID=1, index=-1)¶
Function Description: Requests to set the DLL model index for a specified CopterSim instance.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 1 | Target UAV ID |
| index | int |
No | -1 | DLL model index. <0 indicates using name-based setting |
Returns: None.
Raises: None.
sendReSimMapName(CopterID=1, name="")¶
Function Description: Requests to set the map name for a specified CopterSim instance.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 1 | Target UAV ID |
| name | str |
No | "" | Name of the map |
Returns: None.
Raises: None.
sendReSimMapIdx(CopterID=1, index=-1)¶
Function Description: Sends a map index reconfiguration request to switch the map scene for a specified UAV in the simulation.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int |
No | 1 | Target UAV ID |
| index | int |
No | -1 | Map index; -1 indicates unspecified |
Returns: None.
Raises: None.
sendReSimIP(CopterID=1)¶
Function Description: Sends an IP reconfiguration request to reconfigure the communication IP address for a specified UAV.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
Returns: None
Raises: None
sendReSimUdpMode(CopterID=1, UDP_mode=-1)¶
Function Description: Sends a UDP mode reconfiguration request to switch the UDP communication mode of a specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
| UDP_mode | int | No | -1 | UDP communication mode; -1 indicates unspecified |
Returns: None
Raises: None
sendReSimXYyaw(CopterID=1, xyYaw=[0, 0, 0])¶
Function Description: Sends an XY-plane position and yaw angle reconfiguration request to set the XY-plane position and yaw angle of a specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
| xyYaw | list | No | [0, 0, 0] | XY-plane position and yaw angle [x, y, yaw], units: meters, radians |
Returns: None
Raises: None
sendReGPSOrin(CopterID=1, LLA=[0, 0, 0])¶
Function Description: Sends a GPS origin reconfiguration request to set the GPS origin position (latitude, longitude, altitude) of a specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
| LLA | list | No | [0, 0, 0] | GPS origin [latitude, longitude, altitude], units: degrees, degrees, meters |
Returns: None
Raises: None
sendReGPSPos(CopterID=1, lat=0, lon=0, yaw=0)¶
Function Description: Sends a GPS position reconfiguration request to set the GPS position and yaw angle of a specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
| lat | float | No | 0 | Latitude, unit: degree |
| lon | float | No | 0 | Longitude, unit: degree |
| yaw | float | No | 0 | Yaw angle, unit: radian |
Returns: None
Raises: None
sendEnGpsMode(CopterID=1)¶
Function Description: Sends a request to enable GPS mode, activating GPS positioning for the specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
Returns: None
Raises: None
sendEnXyMode(CopterID=1)¶
Function Description: Sends a request to enable XY mode, activating XY-plane positioning for the specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
Returns: None
Raises: None
sendReSimXyzRPYaw(CopterID=1, Xyz=[0, 0, 0], RPYaw=[0, 0, 0])¶
Function Description: Sends a full pose reconfiguration request to set the 3D position and attitude (roll, pitch, yaw) of a specified drone.
Arguments:
| Parameter Name | Type | Required | Default Value | Description |
|---|---|---|---|---|
| CopterID | int | No | 1 | ID of the target drone |
| Xyz | list | No | [0, 0, 0] | 3D position [x, y, z], units: meters |
| RPYaw | list | No | [0, 0, 0] | Attitude angles [roll, pitch, yaw], units: radians |
Returns: None
Raises: None
Advanced Usage Examples¶
Demonstrates complex collaborative scenarios (e.g., multi-drone coordination, asynchronous control, batch operations)
```python from RflySimSDK.ctrl.ReqCopterSim import ReqCopterSim, Ue4EKFInit, GetUe4EKFInit, RflyTimeStmp
class MultiCopterManager: """Multi-copter collaborative manager: implements batch drone state monitoring and time synchronization"""
def __init__(self):
self.sim = ReqCopterSim()
self.ekf_init = GetUe4EKFInit()
self.time_sync = RflyTimeStmp()
self.active_copters = {}
def discover_and_sync(self):
# Batch discover all simulated drones
copter_ids = self.sim.getAllCopterID()
ip_list = self.sim.getSimIpList()
for cid in copter_ids:
ip = self.sim.getSimIpID(cid)
self.active_copters[cid] = {
'ip': ip,
'local': self.sim.isIpLocal(ip)
}
# Asynchronous time synchronization: update timestamps for all nodes
self.time_sync.Update()
return self.active_copters
def reset_all_ekf(self, copter_subset=None):
"""Batch reset EKF states for specified drones"""
targets = copter_subset or list(self.active_copters.keys())
for cid in targets:
if cid in self.active_copters:
# Local simulation resets directly; remote drones require communication
if self.active_copters[cid]['local']:
self.ekf_init.reset()
print(f"EKF states of {len(targets)} drones have been reset")
Usage example¶
manager = MultiCopterManager() manager.discover_and_sync() manager.reset_all_ekf([1, 3, 5]) # Batch reset EKF states for drones with specified IDs
Notes and Pitfall Avoidance Guide¶
-
IP Address Validation Pitfall:
isValidIpandgetLocalIpperform only format validation and do not guarantee target host reachability;isIpLocaldetermines network interface ownership, not the runtime status of the simulation instance—additional heartbeat checks are required for cross-subnet deployments. -
CopterID Dynamic Changes: The ID list returned by
getAllCopterIDchanges in real time with simulation startup/shutdown; caching old IDs in loops for sending control commands is prohibited; it is recommended to callupdateSimMsgbefore each operation to refresh the state. -
Asynchronous Delay in EKF Reset: After triggering
Ue4EKFInit.reset(), the UE4 rendering thread requires time (typically 50–200 ms) to complete the state reset; reading pose data immediately may yield outdated covariance values. For batch operations, execute sequentially with fixed delays inserted. -
Timestamp Cross-Platform Deviation:
RflyTimeStmp.Update()relies on system clock; timing precision differences between Windows (~1 ms) and Linux (~10 μs) can cause phase jitter in multi-vehicle coordinated control; for high-precision scenarios, hardware-based PTP synchronization is recommended. -
IP List Cache Invalidation:
getSimIpListandgetSimIpIDinternally maintain query caches; after an abnormal exit of a simulation node (e.g., crash instead of graceful shutdown), stale cache entries may persist, causinggetHostIPto return unreachable addresses. In production environments, a periodic full-refresh mechanism should be implemented.
Changelog¶
2026-03-30: fix: corrected SITL shell script rules, added git rules, fixed cloud SDK issues2026-03-07: fix: enhanced fault tolerance for requesting data from CopterSim within the LAN to ensure success rate2025-11-18: feat: added new interfaceget_all_enable_ipinReqCopterSim.pyto retrieve locally enabled IP addresses (priority: wired > Wi-Fi > others)2025-11-17: fix: optimized mechanism2025-11-17: fix: optimized IP acquisition mechanism2025-11-17: fix: resolved program error bug on Windows2025-11-14: added NAT mode network identification, enabling correct IP address requests2025-11-11: refactor: synchronized with latest DistSim modifications2025-11-05: [feat] provided interface to detect whether CopterSim has reached the Fixed state2025-09-11: fix: added support for port reuse on Linux2025-07-30: fix: updated2024-09-29: fix: resolved issue where NAT mode failed to request IPs in virtual machine mode2024-08-16: fix: updated local network interface acquisition mechanism2024-08-16: fix: updated code for retrieving local CopterSim instances2024-07-10: fix: resolved program error bug during network disconnection