Skip to content

RflyADBLib Interface Documentation

Introduction

Overview: This file provides ADB connection, serial communication, and WiFi control functions required for UAV swarm communication, supporting connection management and command interaction with subordinate devices of swarm UAVs.

This module serves as the communication tool module for the RflySim UAV swarm simulation and real-flight system. It is developed specifically for unified management of multiple onboard devices in real-flight scenarios, encapsulating fundamental operations for different communication methods. It supports interfacing with onboard embedded devices via three mainstream communication methods: ADB, serial, and WiFi. Common operations such as device connection status detection, connection establishment and disconnection, network status detection, and device address identification can be performed, providing underlying communication support for subordinate device command issuance and status reporting in swarm missions.

This module is primarily applicable to device debugging and mission deployment scenarios for real-flight UAV swarms. Developers can quickly implement batch communication management for multiple onboard devices based on this module, without having to build the underlying logic for different communication methods from scratch, thus aligning with the RflySim platform’s swarm development workflow.

Quick Start

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

from RflySimSDK.swarm import RflyADBLib

# Custom command sending function; implementation can be adjusted according to actual ADB connection method
def my_send_command(cmd):
    """Example command sending function; replace with your own ADB command sending implementation in practice"""
    import subprocess
    result = subprocess.check_output(cmd, shell=True, text=True)
    print(f"Command output: {result}")
    return result

# 1. Initialize the WiFi command control object, passing in the custom command sending function
wifi_ctrl = RflyADBLib.wifi_command(send_command_function=my_send_command)

# 2. Turn on the onboard WiFi
wifi_ctrl.open_wifi()

# 3. Get current WiFi connection status
wifi_state = wifi_ctrl.statu_wifi()
print(f"Current WiFi status: {wifi_state}")

# 4. Print the name (SSID) of the currently connected WiFi
wifi_ctrl.current_wifi()

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: os, ppadb.client, re, serial, signal, subprocess, sys, time
  • Prerequisites: Before calling this interface, ensure the device is correctly connected and the communication environment (e.g., serial, ADB, or Wi-Fi) has been properly configured.

Core Interface Description

The module RflyADBLib.py contains 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

extract_specific_mac(text, interface_name="wlan0")

Function Description: Extracts the MAC address corresponding to a specified network interface from the given text.
Parameters:

  • text (Any): Source text containing network interface information, typically the output of system network configuration queries.
  • interface_name (Any): Target network interface name; defaults to wlan0.

Return Value:

  • str | None: Returns the corresponding MAC address string if successfully extracted; returns None if not found.

Exceptions: None


ping_ip(ip_address)

Function Description: Checks whether the specified IP address is reachable via the ping command.
Parameters:

  • ip_address (Any): Target IP address whose connectivity is to be tested.

Return Value:

  • bool: Returns True if the ping succeeds; otherwise, returns False.

Exceptions: None


start_adb(path)

Function Description: Starts the ADB (Android Debug Bridge) service, allowing specification of the ADB executable’s directory path.
Parameters:

  • path (Any): Directory path where the ADB executable resides.

Return Value:

  • None: No return value.

Exceptions: None


check_device_connected()

Function Description: Checks whether any Android device is successfully connected via ADB.
Parameters:
None
Return Value:

  • bool: Returns True if a device is connected; otherwise, returns False.

Exceptions: None


stop_adb()

Function Description: Stops the ADB service and closes the connection.
Parameters:
None
Return Value:

  • None: No return value.

Exceptions: None


signal_handler(sig, frame)

Function Description: Signal handler function used to catch program exit signals, perform resource cleanup, and then terminate the program.
Parameters:

  • sig (Any): Signal number to be handled.
  • frame (Any): Current stack frame object.

Return Value:

  • None: No return value.

Exceptions: None


SerialCommunication Class

Enables serial communication between the drone and the computer, supporting serial command transmission, data reading, and serial port disconnection. Suitable for serial communication in RflySim cluster development scenarios.

__init__(port, baudrate, debug_mode)

Function Description: Initializes the serial communication object and opens a serial connection with the specified parameters.
Parameters (Args):

Parameter Name Type Required Default Value Description
port str No "COM4" Serial port device name; typically in COMx format on Windows, and /dev/ttyUSBx on Linux.
baudrate int No 115200 Baud rate for serial communication.
debug_mode bool No False Whether to enable debug mode; when enabled, communication debug information is printed.

Return Value (Returns):

  • Instance of SerialCommunication

Exceptions (Raises): None


send_command(command)

Function Description: Sends a specified command string via the serial port.
Parameters (Args):

Parameter Name Type Required Default Value Description
command str Yes Serial command string to be sent.

Return Value (Returns):

  • None

Exceptions (Raises): None


read_serial_data()

Function Description: Reads response data returned from the serial port.
Parameters (Args):
None
Return Value (Returns):

  • str: The serial data string read from the port.

Exceptions (Raises): None


close_serial()

Function Description: Closes the currently open serial port connection and releases serial resources.
Parameters (Args):
None
Return Value (Returns):

  • None

Exceptions (Raises): None

Example:

# Initialize the serial communication object
serial_comm = SerialCommunication(port="COM4", baudrate=115200, debug_mode=True)
# Send an AT command
serial_comm.send_command("AT")
# Read the response data from the serial port
response = serial_comm.read_serial_data()
print(response)
# Close the serial port connection
serial_comm.close_serial()

---

### `adb_communication` Class

Implements drone device communication based on the ADB protocol, providing ADB command sending and communication management functionalities, suitable for interactive communication among mobile devices in multi-drone control scenarios.

#### `__init__(debug_mode=False)`

**Function Description**: Initializes the ADB communication object and configures the debug mode option.  
**Parameters (Args)**:

| Parameter Name | Type | Required | Default Value | Description |
| :--- | :--- | :---: | :--- | :--- |
| `debug_mode` | `bool` | No | `False` | Whether to enable debug mode; when enabled, additional debug log messages will be output |

**Return Value (Returns)**:

- Instance of `adb_communication`

**Exceptions (Raises)**:
- None

---

#### `send_command(cmd)`

**Function Description**: Sends a specified command to the connected ADB device and retrieves the command execution result.  
**Parameters (Args)**:

| Parameter Name | Type | Required | Default Value | Description |
| :--- | :--- | :---: | :--- | :--- |
| `cmd` | `str` | Yes | - | The ADB command string to be sent and executed |

**Return Value (Returns)**:

- `str`: Output result after executing the ADB command

**Exceptions (Raises)**:
- None

**Example**:

```python
# Initialize the ADB communication object
adb_comm = adb_communication(debug_mode=True)
# Send an ADB command to retrieve the device list
result = adb_comm.send_command("devices")
print(result)

wifi_command Class

Implements cluster drone command transmission management over WiFi channels, relying on an input callback function for command transmission.

__init__(send_command_function)

Function Description: Constructs a WiFi command transmission management object, accepting a callback function for command transmission. Parameters (Args):

Parameter Name Type Description
send_command_function None Callback function for actually sending WiFi commands, used to execute specific command transmission operations

Returns: No return value; constructs an object instance.
Raises: No exceptions thrown.


open_wifi()

Function Description: Opens the WiFi interface.
Parameters (Args): None
Returns: No return value
Raises: None


current_wifi()

Function Description: Checks the connection status of the wireless network interface (wlan0) and prints the name (SSID) of the currently connected wireless network.
Parameters (Args): None
Returns: No return value
Raises: None


statu_wifi()

Function Description: Retrieves the current WiFi status.
Parameters (Args): None
Returns: No return value
Raises: None


close_wifi()

Function Description: Closes the WiFi interface.
Parameters (Args): None
Returns: No return value
Raises: None


get_ip()

Function Description: Retrieves the IP address assigned to the connected WiFi interface.
Parameters (Args): None
Returns: No return value
Raises: None


create_wifihot(SSID="AP_150_HOT", PASSWD="droneyee", CHANNEL=11)

Function Description: Creates a WiFi hotspot.
Parameters (Args):

Parameter Name Type Required Default Value Description
SSID Any No AP_150_HOT Hotspot name
PASSWD Any No droneyee Hotspot password
CHANNEL Any No 11 Hotspot channel

Returns: No return value
Raises: None


modify_wifihot_ip(IPADDRESS=None)

Function Description: Modifies the hotspot IP address. Not recommended for use.
Parameters (Args):

Parameter Name Type Required Default Value Description
IPADDRESS Any No None New IP address for the hotspot

Returns: No return value
Raises: None


get_wifihot_passwd()

Function Description: Retrieves the password of the hotspot.
Parameters (Args): None
Returns: No return value
Raises: None


connect_wifi(WIFI_SSID=None, WIFI_PASSWD=None)

Function Description: Connects to a WiFi network.
Parameters (Args):

Parameter Name Type Required Default Value Description
WIFI_SSID Any No None SSID (name) of the WiFi network to connect to
WIFI_PASSWD Any No None Password of the WiFi network to connect to

Returns: No return value
Raises: None


echo_cmd(cmd=None, mode="0")

Function Description: Configures camera parameters. cmd specifies the command to append; mode=0 indicates append mode, mode=1 indicates overwrite mode.
Parameters (Args):

Parameter Name Type Required Default Value Description
cmd Any No None Command to append
mode Any No 0 Write mode: 0 for append, 1 for overwrite

Returns: No return value
Raises: None


replace_cmd(cmd=None, place=None, path=None)

Function Description: cmd specifies the target command content to replace; place indicates the line number to be replaced; path specifies the file path to be modified.
Note: When modifying /home/marvsmart/camera_udp/config.yaml, the corresponding line numbers are:
enable: line 5 or 13
ip: line 9 or 17
compress_rate: line 8 or 16
Camera configuration file path: /home/marvsmart/camera_udp/config.yaml
Autostart file path: /etc/./rc.local
Parameters (Args):

Parameter Name Type Required Default Value Description
cmd Any No None Target command content to replace
place Any No None Line number where the content needs to be replaced
path Any No None Path of the file to be modified

Returns: No return value
Raises: None


replace_cam_ip(ip=None, cam=None)

Function Description: Modifies the camera IP address. ip specifies the desired IP address (string format), and cam specifies which camera to modify (0 or 1).
Parameters (Args):

Parameter Name Type Required Default Value Description
ip Any No None Desired camera IP address, in string format
cam Any No None Camera identifier to modify, value is 0 or 1

Returns: No return value
Raises: No exceptions


replace_cam_compress(rate=None, cam=None)

Function Description: Modifies the camera image compression rate, where rate is the desired compression rate and cam specifies which camera to modify (0 or 1).
Arguments (Args):

Parameter Name Type Required Default Description
rate Any No None Desired image compression rate to set
cam Any No None Camera ID to modify, must be 0 or 1

Returns: No return value
Raises: No exceptions


replace_cam_ehable(enable=None, cam=None)

Function Description: Modifies the camera enable state, where enable is the desired enable state and cam specifies which camera to modify (0 or 1).
Arguments (Args):

Parameter Name Type Required Default Description
enable Any No None Desired camera enable state to set
cam Any No None Camera ID to modify, must be 0 or 1

Returns: No return value
Raises: No exceptions


replace_mav_link(ip=None, port="15502")

Function Description: Sets the IP address and port for MAVLink telemetry return.
Arguments (Args):

Parameter Name Type Required Default Description
ip Any No None Target IP address for MAVLink telemetry return
port Any No 15502 Target port for MAVLink telemetry return

Returns: No return value
Raises: No exceptions


aotuStartWIFI(SSID="AP_150_HOT", PASSWD="droneyee", CHANNEL=11, enable=1)

Function Description: Used to automatically start or disable a Wi-Fi hotspot.
Arguments (Args):

Parameter Name Type Required Default Description
SSID str No AP_150_HOT Wi-Fi hotspot name
PASSWD str No droneyee Wi-Fi hotspot password
CHANNEL int No 11 Wi-Fi hotspot channel
enable int No 1 1 enables automatic hotspot startup; 0 disables it

Returns: None
Raises: No exceptions


openCam()

Function Description: Opens the onboard camera service.
Arguments (Args): No arguments
Returns: None
Raises: No exceptions


getMac()

Function Description: Retrieves the MAC address of the development board’s wireless network interface.
Arguments (Args): No arguments
Returns: MAC address string of the wireless network interface
Raises: No exceptions


setStaticIp(SSID, ip)

Function Description: Sets a static IP address for a Wi-Fi connection with the specified SSID.
Arguments (Args):

Parameter Name Type Required Default Description
SSID str Yes None Wi-Fi name for which to set the static IP
ip str Yes None Static IP address to configure

Returns: None
Raises: No exceptions


pingIp(ip)

Function Description: Pings a specified IP address to test network connectivity.
Arguments (Args):

Parameter Name Type Required Default Description
ip str Yes None Target IP address to test connectivity for

Returns: Output result of the ping operation
Raises: No exceptions

Advanced Usage Examples

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

```python import asyncio from RflySimSDK.swarm import SerialCommunication, wifi_command

Multi-class collaboration + asynchronous batch configuration of drone swarm Wi-Fi hotspots

async def config_swarm_wifi_async(serial_dev_list, hot_ip_prefix, hot_passwd): # Store all connected device objects for unified resource cleanup later connected_devices = [] for idx, dev_port in enumerate(serial_dev_list): # Initialize serial communication and Wi-Fi control classes concurrently serial_comm = SerialCommunication(dev_port, baudrate=115200) wifi_comm = wifi_command(serial_comm) connected_devices.append((serial_comm, wifi_comm))

    # Batch configure hotspot IP and password for each node
    new_hot_ip = f"{hot_ip_prefix}.{idx+10}"
    # Asynchronously submit configuration tasks to avoid blocking the overall process due to a single device
    asyncio.create_task(config_single_device(wifi_comm, new_hot_ip, hot_passwd))

# Wait for all configurations to complete, then uniformly release resources
await asyncio.sleep(10)
for serial_comm, _ in connected_devices:
    serial_comm.close_serial()

async def config_single_device(wifi_comm: wifi_command, target_ip, passwd): # First, disable the existing Wi-Fi connection, then create a custom hotspot wifi_comm.close_wifi() # Modify the hotspot IP and apply the configuration wifi_comm.modify_wifihot_ip(target_ip) # Create the hotspot and verify the configuration success wifi_comm.create_wifihot() current_passwd = wifi_comm.get_wifihot_passwd() print(f"Hotspot created successfully, current password: {current_passwd}, configured IP: {target_ip}, current status: {wifi_comm.statu_wifi()}")

if name == "main": # Assuming there are 4 drones, batch-initialize hotspots device_ports = ["/dev/ttyUSB0", "/dev/ttyUSB1", "/dev/ttyUSB2", "/dev/ttyUSB3"] asyncio.run(config_swarm_wifi_async(device_ports, "192.168.1", "RflySwarm2024"))

Notes and Pitfall Avoidance Guide

  • Serial Port Resource Release: After completing communication using the SerialCommunication class, you must call the close_serial method to release the serial port resources; otherwise, subsequent programs will be unable to open the same serial port device, resulting in a permission occupation error.
  • WiFi Configuration Operation Sequence: Before modifying the drone’s hotspot IP, you must first call close_wifi to close the existing connection or hotspot; after modification, you must call create_wifihot again for the new IP configuration to take effect—direct modification alone will not update the configuration.
  • WiFi Status Reading Instructions: Before calling statu_wifi to retrieve the WiFi connection status, you must first call current_wifi to refresh the current connection information; otherwise, the cached status from the previous session will be returned, leading to incorrect status determination.
  • ADB Communication Permission Verification: Before using the send_command method of the adb_communication class to send drone control commands, ensure that ADB debugging permissions are enabled on the computer and that device access has been authorized; otherwise, the device will reject the commands, resulting in no response.

Changelog

  • 2024-08-29: Modified to automatically acquire paths
  • 2024-08-20: Fix: Improved API index
  • 2024-08-15: Fix: Updated ADB library