Skip to content

NetUavAPI Interface Documentation

Introduction

Overview: This document defines the core network interaction class for the communication module of the RflySim UAV simulation platform, enabling network data transmission and connection state maintenance between the UAV side and the simulation ground station.

In RflySim’s distributed simulation scenarios, UAV simulation nodes, ground stations, and external computation nodes typically require inter-process or inter-device communication. This module provides a standardized network interaction infrastructure to support stable transmission of core UAV data such as position and status. It is applicable to scenarios requiring network communication, including multi-UAV cooperative simulation, external algorithm integration with simulation, and geographically distributed simulations. By implementing heartbeat maintenance and connection validation mechanisms, it ensures the reliability of the communication link, providing stable underlying network transmission support for upper-layer UAV control and status monitoring functionalities.

Quick Start

Minimal runnable example; copy and modify minimal configuration to run.

from RflySimSDK.comm.NetUavAPI import HeartServer
import time

# 1. Create a heartbeat server instance
heart_server = HeartServer()

# 2. Start the heartbeat server
heart_server.startHeartSer()

try:
    # 3. Continuously send heartbeats to maintain the connection (example runs for 10 seconds)
    for _ in range(10):
        heart_server.SendHeartSer()
        # Heartbeats are typically sent once per second; wait 1 second
        time.sleep(1)
finally:
    # 4. Stop the heartbeat server and release resources
    heart_server.endHeartSer()

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: PX4MavCtrlV4, copy, ctypes, datetime, math, numpy, os, pickle, socket, struct, sys, threading, time, win_precise_time
  • Prerequisites: Before calling this interface, ensure the network connection is functional and that initialization configuration of relevant communication nodes has been completed.

Core Interface Description

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

Global Constants and Enumerations

This section lists all globally accessible constants and enumerations defined in the module.

Standalone Constants

None


Global/Standalone Functions

None


CheckInfo Class

This class serves as a base class for the RflySimSDK communication module, typically used to store and validate UAV communication connection information. Specific functionality can be extended as needed.

__init__()

Function Description: Initializes an instance of the CheckInfo class
Parameters (Args):
None

Returns:

  • CheckInfo instance object

Raises: None


HeartBeartInfo Class

A data class used to store UAV heartbeat-related information within the UAV communication module of the RflySim simulation platform, carrying heartbeat status data.

__init__()

Function Description: Initializes an instance of the HeartBeartInfo class
Parameters (Args):
None
Returns:

  • HeartBeartInfo instance object

Raises: None


HeartServer Class

Used to maintain the heartbeat service for the RflySim UAV simulation communication link, detecting and preserving the connection state between client and server to ensure communication stability.

__init__()

Function Description: Initializes a heartbeat service instance
Parameters (Args):
None

Returns:

  • HeartServer instance object

Raises: None


startHeartSer()

Function Description: Starts the heartbeat service, begins listening for heartbeat messages, and maintains the connection
Parameters (Args):
None

Returns:

  • None

Raises: None

Example:

from RflySimSDK.comm import HeartServer
# Create and start the heartbeat server instance
heart_server = HeartServer()
heart_server.startHeartSer()

endHeartSer()

Function Description: Stops the heartbeat service, closes the connection, and releases related resources
Parameters (Args):
None

Returns:

  • None

Raises: None


SendHeartSer()

Function Description: Actively sends a heartbeat packet to inform the peer that this end’s connection is healthy
Parameters (Args):
None

Returns:

  • None

Raises: None


CheckConnectState()

Function Description: Checks the liveness status of the current communication connection
Parameters (Args):
None

Returns:

  • bool: Connection status; True indicates a healthy connection, False indicates disconnection

Raises: None

Example:

# Check current connection status
is_connected = heart_server.CheckConnectState()
print(f"Current connection status: {is_connected}")

---

#### `ReceiveHeartSer()`

**Function Description**: Receives heartbeat packets sent by the peer and updates the connection status.  
**Arguments (Args)**:  
None  

**Returns**:  
- None  

**Raises**:  
- None  

---

### `GlobalPosData` Class

A data container class for storing global position-related data of the UAV.

#### `__init__(cpID, iv)`

**Function Description**: Initializes a `GlobalPosData` instance.  
**Arguments (Args)**:

| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `cpID` | Any type | Yes | - | Parameter related to the mission point ID |
| `iv` | Any type | Yes | - | Parameter related to position-related values |

**Returns**:  
- `GlobalPosData` instance  

**Raises**:  
- None  

---

### `NetTransNode` Class

A network transmission node used to establish connections with the network simulation service, enabling network-based data transmission and reception for UAVs. Typically used in multi-UAV network communication simulation scenarios.

#### `__init__(mav=PX4MavCtrl.PX4MavCtrler(1))`

**Function Description**: Initializes the network transmission node instance and binds it to a PX4 flight controller control instance.  
**Arguments (Args)**:

| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `mav` | `PX4MavCtrler` | No | `PX4MavCtrl.PX4MavCtrler(1)` | PX4 flight controller control instance, used to retrieve and send UAV flight control data |

**Returns**:  
- `NetTransNode` instance  

**Raises**:  
- None  

---

#### `startNetServ(RecPort=-1, netSimPort=20030, netSimIP=224.0.0.10)`

**Function Description**: Starts the network transmission service. This method blocks until it receives a startup signal from the sender before returning.  
**Arguments (Args)**:

| Parameter Name | Type | Required | Default | Description |
| :--- | :--- | :---: | :--- | :--- |
| `RecPort` | `int` | No | `-1` | Local port number for receiving data; `-1` indicates automatic port allocation |
| `netSimPort` | `int` | No | `20030` | Port number of the network simulation service |
| `netSimIP` | `str` | No | `224.0.0.10` | IP address of the network simulation service; defaults to a multicast address |

**Returns**:  
- None  

**Raises**:  
- None  

**Example**:

```python
from RflySimSDK.comm import NetTransNode
from RflySimSDK.PX4MavCtrl import PX4MavCtrler
# Initialize flight controller controller and network transmission node
mav = PX4MavCtrler(1)
net_node = NetTransNode(mav)
# Start network service
net_node.startNetServ()

endNetServ()

Function Description: Terminates the network transmission service and stops the message receive/send loop.
Returns:
- None

Raises:
- None


ListenMsgLoop()

Function Description: Starts the network message receiving loop, continuously receiving UAV data sent by other nodes in the network and updating the local flight controller instance.
Returns:
- None

Raises:
- None


SendMsgLoop()

Function Description: Starts the network message sending loop, continuously sending the local UAV’s flight control data to other nodes in the network.
Returns:
- None

Raises:
- None

Example:

import threading
from RflySimSDK.comm import NetTransNode
from RflySimSDK.PX4MavCtrl import PX4MavCtrler

mav = PX4MavCtrler(1)
net_node = NetTransNode(mav)
net_node.startNetServ()

# Start sending and receiving threads
send_thread = threading.Thread(target=net_node.SendMsgLoop)
recv_thread = threading.Thread(target=net_node.ListenMsgLoop)
send_thread.start()
recv_thread.start()

---

## Advanced Usage Examples  
> Demonstrates complex composite scenarios (e.g., multi-class collaboration, asynchronous control, batch operations).

The following example implements asynchronous heartbeat maintenance and position data exchange for a drone swarm of 10 units. By decoupling heartbeat monitoring and business message listening into separate threads, it ensures stable communication for coordinated multi-node flight operations:

```python
from RflySimSDK.comm import HeartServer, NetTransNode, GlobalPosData
import threading
import time

# Initialize batch communication nodes
uav_num = 10
heart_servers = []
net_nodes = []

# Batch-start heartbeat services and network transmission services
for i in range(uav_num):
    # Assign dedicated ports for each drone
    heart_port = 8000 + i
    msg_port = 9000 + i
    # Start heartbeat keep-alive service
    hs = HeartServer()
    hs.startHeartSer(heart_port)
    heart_servers.append(hs)
    # Start message listening and transmission service
    node = NetTransNode()
    node.startNetServ(msg_port)
    # Launch asynchronous message listening loop
    listen_thread = threading.Thread(target=node.ListenMsgLoop, daemon=True)
    listen_thread.start()
    # Launch asynchronous message sending loop
    send_thread = threading.Thread(target=node.SendMsgLoop, daemon=True)
    send_thread.start()
    net_nodes.append(node)

# Periodically check connection status and broadcast position data
try:
    while True:
        # Batch-check connection status of all drones
        connect_states = [hs.CheckConnectState() for hs in heart_servers]
        # Broadcast global position if all drones are connected
        if all(connect_states):
            pos_data = GlobalPosData()
            for idx, node in enumerate(net_nodes):
                # Populate current position for this drone
                pos_data.set_pos(idx, 10*idx, 5*idx, 100 + idx*2)
                # Asynchronously send position data
                node.SendMsgLoop(pos_data.pack())
        # Send heartbeat packets to maintain connections
        for hs in heart_servers:
            hs.SendHeartSer()
        time.sleep(0.1)
finally:
    # Batch-shutdown all services upon exit
    for hs in heart_servers:
        hs.endHeartSer()
    for node in net_nodes:
        node.endNetServ()

Notes and Pitfall Avoidance Guide

  • Heartbeat Service Lifecycle Alignment: startHeartSer and endHeartSer must be called in pairs. Heartbeat services must be manually closed upon program exit; otherwise, ports remain occupied, leading to port binding errors on subsequent startups.
  • Thread Handling for Asynchronous Loops: Both ListenMsgLoop and SendMsgLoop are blocking loop methods and must run in dedicated daemon threads. Invoking them directly in the main thread will block subsequent business logic execution, preventing parallel processing across multiple nodes.
  • Avoiding Port Conflicts in Multi-Node Setups: When launching multiple HeartServer and NetTransNode instances in batch, each instance must be assigned a unique port number. Within the same LAN, a single port cannot be bound by multiple services simultaneously; otherwise, subsequent nodes will fail to start.
  • Timing of Connection State Checks: The CheckConnectState method must only be called after the heartbeat service has started and at least two heartbeat exchanges have occurred. Connection states obtained before completing the initial handshake are unreliable and may falsely indicate disconnection.

Changelog

  • 2025-09-11: fix: Added support for Linux port reuse
  • 2025-05-29: fix: Updated platform protocol summary page