Skip to content

mavRflyShell Interface Documentation

Introduction

Overview: This file implements a shell interaction feature on the drone side based on the MAVLink protocol, enabling access to the drone-side command-line shell via serial port connection.

This module belongs to the RflySimSDK cluster tools module and provides a channel for accessing the drone flight controller's command-line shell from the ground station side. It supports transparent transmission of shell commands and flight controller response data through the MAVLink protocol.

This module is suitable for scenarios requiring remote debugging of the flight controller in simulation environments, executing custom commands on the flight controller side, and viewing flight controller runtime status logs. It helps developers quickly verify flight controller configurations and troubleshoot flight controller-side issues in cluster simulations. The ConnectNsh function enables rapid connection establishment, while the core MavRflyShell class integrates MAVLink communication and shell interaction logic, supporting stable command sending and receiving interactions.

Quick Start

The following example detects the currently connected PX4 flight controller serial port. Returns a non-positive value when no device is detected.

Reference example: [RflySim installation path]\RflySimAPIs\1.RflySimIntro\2.AdvExps\e9.ConfigTools\e1.FCUETH_NetConfig

import sys

import mavRflyShell


nsh = mavRflyShell.MavRflyShell()
com = nsh.getPX4Com()
if com <= 0:
    print("No PX4 flight controller detected, please connect the device and try again")
    sys.exit(0)

print("Flight controller serial port detected:", com)

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: __future__, argparse, io, json, os, re, socket, subprocess, sys, time, timeit
  • Prerequisites: Before calling this interface, ensure that the MAVLink connection is ready and communication can be established.

Core Interface Description

The module mavRflyShell.py includes configuration variables, helper functions, and the core business class.

Global Constants and Enumerations

This section lists all globally accessible constants and enumeration definitions that can be directly referenced in the module.

Standalone Constants

None


Global/Standalone Functions

ConnectNsh()

Function Description: Connects to the NSH console of the PX4 simulation environment to enable command-line interaction control of the PX4 flight controller.
Parameters:
None
Return Value:
None
Exceptions:
None


MavlinkSerialPort Class

Implements serial port communication for the MAVLink protocol, supporting serial data reading/writing and debug output. Suitable for serial communication scenarios between drones and ground stations or external devices in RflySim.

__init__(portname, baudrate, devnum=0, debug=0)

Function Description: Initializes a Mavlink serial port object, opens the specified serial port, and configures communication parameters.
Parameters (Args):

Parameter Name Type Required Default Description
portname Yes - Serial port name, specifying the serial device to open
baudrate Yes - Serial port baud rate, configuring the communication speed
devnum No 0 Device number, used to distinguish between multiple serial port devices
debug No 0 Debug switch; debug output is enabled when non-zero

Return Value (Returns):

  • MavlinkSerialPort instance object

Exceptions (Raises): None


debug(s, level=1)

Function Description: Writes debug text and outputs debug information based on the debug level and initialization configuration.
Parameters (Args):

Parameter Name Type Required Default Description
s str Yes - Debug text content to output
level int No 1 Debug level; output occurs only when the level is greater than or equal to the initialized level

Return Value (Returns):

  • None

Exceptions (Raises): None


write(b)

Function Description: Writes byte data to the serial port, sending MAVLink or other binary data formats.
Parameters (Args):

Parameter Name Type Required Default Description
b bytes Yes - Byte data to write to the serial port

Return Value (Returns):

  • None

Exceptions (Raises): None


close()

Function Description: Closes the currently opened serial port and releases serial port resources.
Return Value (Returns):

  • None

Exceptions (Raises): None


read(n)

Function Description: Reads a specified number of bytes from the serial port.
Parameters (Args):

Parameter Name Type Required Default Description
n int Yes - Number of bytes to read

Return Value (Returns):

  • bytes: Byte data read from the serial port

Exceptions (Raises): None

Example:

# Initialize and open serial port
serial_port = MavlinkSerialPort("COM3", 115200, debug=1)
# Write byte data
data = bytes([0x01, 0x03, 0x00])
serial_port.write(data)
# Read returned data
recv_data = serial_port.read(10)
# Close serial port
serial_port.close()

RflyShell Class

A serial port interaction class for the PX4 flight controller's NuttX shell, used to send commands, modify parameters, and reboot the flight controller via serial port. Suitable for flight controller terminal control in RflySim simulation cluster scenarios.

__init__(port, baudrate=115200)

Function Description: Initializes the RflyShell serial port connection object.
Parameters (Args):

Parameter Name Type Required Default Description
port str Yes - Serial port device name/port number, e.g., COMx on Windows, /dev/ttyUSBx on Linux
baudrate int No 115200 Serial communication baud rate; PX4 default baud rate is 115200

Return Value (Returns):

  • RflyShell instance object

Exceptions (Raises): - None


is_prompt(data)

Function Description: Checks whether the received serial port data contains a complete shell prompt, used to determine if command output is complete.
Parameters (Args):

Parameter Name Type Required Default Description
data bytes Yes - Raw byte data read from the serial port

Return Value (Returns):

  • bool: Returns True if a complete prompt is found, otherwise returns False

Exceptions (Raises): - None


SendCmdNsh(cmd)

Function Description: Sends a NuttX shell command to the PX4 flight controller and waits for the output response.
Parameters (Args):

Parameter Name Type Required Default Description
cmd str Yes - NuttX shell command string to be sent

Return Value (Returns):

  • str: Output string returned after command execution

Exceptions (Raises): - None

Example:

from RflySimSDK.swarm import RflyShell
shell = RflyShell("COM3", 115200)
output = shell.SendCmdNsh("help")
print(output)

SendUpdateParam(ParamKey, ParamValue)

Function Description: Updates a PX4 flight controller parameter value to the flight controller.
Parameters (Args):

Parameter Name Type Required Default Description
ParamKey str Yes - Name of the PX4 parameter to be modified
ParamValue int/float Yes - New value to be set for the parameter

Return Value (Returns): - None
Exceptions (Raises): - None


SendCommitParam()

Function Description: Commits all modified PX4 parameters, saving the changes to the flight controller's flash memory.
Return Value (Returns): - None
Exceptions (Raises): - None


SendChangeParam(ParamKey, ParamValue)

Function Description: Modifies and commits a single PX4 flight controller parameter, combining update and commit operations.
Parameters (Args):

Parameter Name Type Required Default Description
ParamKey str Yes - Name of the PX4 parameter to be modified
ParamValue int/float Yes - New value to be set for the parameter

Return Value (Returns): - None
Exceptions (Raises): - None

Example:

shell = RflyShell("COM3", 115200)
# Modify PX4 firmware ID, corresponding to different aircraft models
shell.SendChangeParam("SYS_AUTOSTART", 4001)

SendShowParam(ParamKey)

Function Description: Queries the current value of a specified PX4 flight controller parameter.
Parameters (Args):

Parameter Name Type Required Default Description
ParamKey str Yes - Name of the PX4 parameter to be queried

Return Value (Returns):

  • str: Parameter query result string

Exceptions (Raises): - None


SendRebootPX4()

Function Description: Sends a command to reboot the PX4 flight controller.
Return Value (Returns): - None
Exceptions (Raises): - None

Example:

shell = RflyShell("COM3", 115200)
shell.SendRebootPX4()

SendClose()

Function Description: Closes the serial port connection and releases resources.
Returns:
None
Raises:
None


SendCmdNshS(ParamKey)

Function Description: Sends a specified NuttX shell command without additional output or return.
Args:

Parameter Name Type Required Default Description
ParamKey str Yes - NuttX shell command string to be sent

Returns:
None
Raises:
None


SendAirframe()

Function Description: Sends a command to view the current airframe configuration.
Returns:
None
Raises:
None


MavRflyShell Class

Manages serial communication, IP address configuration, and device detection for PX4 UAV flight controllers, supporting flight controller network and serial parameter configuration in multi-UAV networking scenarios.


getPX4Com()

Function Description: Retrieves the serial port device corresponding to the PX4 flight controller.
Args:
No parameters

Returns:
- str: Path of the available PX4 flight controller serial port

Raises:
None


getLocalIp()

Function Description: Retrieves the local LAN IP address of the host machine.
Args:
No parameters

Returns:
- str: Local LAN IP address as a string

Raises:
None


validate_ip(ip)

功能说明:Checks whether the IP address starts with 192.168.151. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
ip str - IP地址字符串 to be validated

返回值 (Returns):

  • bool: Returns True if the format matches, otherwise returns False

异常 (Raises): None


auto_configure_ip(targetID)

功能说明:Automatically configures the IP address of the flight controller. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
targetID int - Target flight controller ID to configure IP for

返回值 (Returns):

  • None

异常 (Raises): None


setSysIDIP(com, airplane_id, baud="921600", is_last=False)

功能说明:Sets the system ID and corresponding IP address of the flight controller via serial port. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
com str - Target serial port device path
airplane_id int - UAV system ID to be set
baud int 921600 Serial communication baud rate
is_last bool False Indicates whether this is the last UAV to be configured

返回值 (Returns):

  • None

异常 (Raises): None


monitorSerialPorts(com)

功能说明:Monitors the connection status of a specified serial port. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
com str - Serial port device path to monitor

返回值 (Returns):

  • None

异常 (Raises): None


checkSerialAvailable(com)

功能说明:Checks whether the current serial port is still available. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
com str - Serial port device path to check

返回值 (Returns):

  • bool: Returns True if the serial port is available, otherwise returns False

异常 (Raises): None


getAvailableSerialPorts()

功能说明:Retrieves the list of available serial ports on the current system. 参数列表 (Args):

No parameters

返回值 (Returns):

  • list[str]: List of paths of all available serial port devices

异常 (Raises): None


waitForNewDevice()

功能说明:Waits for the user to insert a new flight controller device. 参数列表 (Args):

No parameters

返回值 (Returns):

  • str: Serial port path of the newly inserted device

异常 (Raises): None

示例:

from RflySimSDK.swarm import MavRflyShell
shell = MavRflyShell()
# Get all available serial ports
ports = shell.getAvailableSerialPorts()
# Wait for a new device to be inserted
new_port = shell.waitForNewDevice()

check_udp_data(port)

功能说明:Reads data from a specified UDP port. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
port int - UDP port number from which to read data

返回值 (Returns):

  • bytes: Data read from the UDP port

异常 (Raises): None


connect_to_device(port, baud)

功能说明:Connects to a flight controller device on a specified serial port. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
port str - Serial port path where the flight controller device is connected
baud int - Baud rate for serial communication

返回值 (Returns):

  • object: Device object upon successful connection

异常 (Raises): None


query_mav_sys_id(rflyShell, sys_id)

功能说明:Queries MAVLink device information for a specified system ID. 参数列表 (Args):

参数名 类型 是否必填 默认值 说明
rflyShell object - Instance of MavRflyShell
sys_id int - MAVLink system ID to query

返回值 (Returns):

  • dict: Device information retrieved from the query

异常 (Raises): None

示例:

from RflySimSDK.swarm import MavRflyShell
shell = MavRflyShell()
# Automatically configure the IP for flight controller ID 1
shell.auto_configure_ip(targetID=1)
# Configure flight controller ID and corresponding IP
shell.setSysIDIP("COM3", airplane_id=1, baud=921600)

Advanced Usage Examples

The following example, after the user confirms the target SysID, sequentially configures the system ID and network address of multiple flight controllers through the same serial port. This operation modifies flight controller parameters, so the numbering order must be verified.

Reference example: [RflySim installation path]\RflySimAPIs\1.RflySimIntro\2.AdvExps\e9.ConfigTools\e1.FCUETH_NetConfig

import sys

import mavRflyShell


nsh = mavRflyShell.MavRflyShell()
com = nsh.getPX4Com()
if com <= 0:
    print("No PX4 flight controller detected")
    sys.exit(0)

targetIDs = input("Enter SysIDs to configure, separated by commas: ")
targetIDList = [int(value.strip()) for value in targetIDs.split(",")]

input("Press Enter to start configuration after confirming the flight controller connection order is correct")
for index, targetID in enumerate(targetIDList):
    isLast = index == len(targetIDList) - 1
    success = nsh.setSysIDIP(com, targetID, is_last=isLast)
    print("SysID", targetID, "configuration result:", success)
    if not success:
        break

Notes and Pitfall Avoidance Guide

  • Parameter Modification Submission Timeliness: After calling SendChangeParam to batch-modify multiple parameters, SendCommitParam must be invoked to write the modifications into the PX4 flight control firmware; otherwise, uncommitted parameter changes will be lost upon flight control reboot.
  • Serial Port Resource Concurrency Limitation: A single serial port cannot be simultaneously opened by multiple MavlinkSerialPort instances. After batch-scanning available serial ports, the close method must be promptly called to release resources of unavailable ports, preventing subsequent device connection detection failures.
  • IP Address Format Validation Requirement: Before calling setSysIDIP to bind the flight control system ID with an IP address, the IP format must first be validated using the validate_ip method. An invalid IP will cause UDP communication link establishment to fail, and no explicit error will be thrown proactively.
  • Command Sending Inter-Command Interval: When consecutively calling SendCmdNsh to send NSH commands, a minimum interval of 100 ms must be reserved between commands to allow the flight control to respond. Rapid consecutive sending will result in command packet loss, with the flight control executing only the last received command.

Changelog

  • 2024-12-10: fix: Update API documentation page
  • 2024-12-10: fix: Update cluster control interface comments
  • 2024-09-06: fix: Add HIL firmware flashing support for new airframe types
  • 2024-09-04: fix: 1. Add UDP validation function; 2. Add error handling and retry mechanism; 3. Fix bug where mav_id parameter cannot be found after flight control reboot; 4. Fix bug where configuration proceeds despite prior completion
  • 2024-09-03: fix: Add IP validation, serial port detection, and message delay
  • 2024-09-03: fix: Add IP validation, serial port detection, and message delay
  • 2024-09-03: fix: Add IP validation, serial port detection, and message delay
  • 2024-08-26: fix: Su Xiao MavRflyShell update
  • 2024-08-16: fix: Upgrade shell library
  • 2024-08-16: fix: Add initial flight control parameter configuration interface