Skip to content

MavDataRec Interface Documentation

Introduction

Overview: This file defines the MavDataRec class, used to record and store MAVLink protocol data generated during drone flight operations.

MAVLink is a lightweight communication protocol widely adopted in the drone industry. During drone simulation and real-world flight missions, a large volume of communication data—including flight states, control commands, and sensor readings—is generated. Such data is crucial for mission reproduction, algorithm debugging, and performance analysis. This module belongs to the formation control module group of RflySimSDK and is designed for drone simulation scenarios within the RflySim platform. It enables users to retain all MAVLink communication data generated during simulation flights, facilitating subsequent offline analysis and algorithm iteration validation.

Quick Start

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

from RflySimSDK.phm.MavDataRec import MavDataRec
# Import the MAVLink connection object (replace with your own MAV connection in actual use)
from RflySimAPI import MavlinkInterface

# 1. Establish a MAVLink connection using RflySim's default configuration
mav = MavlinkInterface()
mav.connect()

# 2. Create an MAV data recording object, passing in the established MAV connection
data_rec = MavDataRec(mav)

# 3. Configure and start recording messages
# NameList: list of MAVLink message names to record; here, HIGHRES_IMU and ATTITUDE messages are recorded
# LenList: cache length for each message type; stores the latest 10 HIGHRES_IMU and 20 ATTITUDE messages respectively
data_rec.startRecMsg(NameList=['HIGHRES_IMU', 'ATTITUDE'], LenList=[10, 20])

# 4. Run a 10-second simulation mission, continuously recording data during this period
import time
time.sleep(10)

# 5. Retrieve the latest cached recorded data
rec_data = data_rec.getMavMsg()
# Print the retrieved HIGHRES_IMU data
print("Retrieved HIGHRES_IMU records:", rec_data['HIGHRES_IMU'])

# 6. Stop message recording
data_rec.stopRecMsg()

# Disconnect the MAVLink connection
mav.close()

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: threading
  • Prerequisites: Before calling this interface, RflySimSDK must be initialized and imported.

Core Interface Description

The module MavDataRec.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


MavDataRec Class

MAVLink message data recorder class, used to record specified types of MAVLink messages in RflySim drone simulations. Supports customizable message types and cache lengths, commonly used in offline flight data analysis and data collection for PHM (Prognostics and Health Management) applications.

__init__(self, mav)

Function Description: Initializes an MAVLink data recording instance and binds it to the MAVLink communication object.
Parameters (Args):

Parameter Name Type Required Default Value Description
mav object Yes - An established MAVLink communication object used to receive drone messages

Return Value (Returns):

  • MavDataRec instance object

Exceptions (Raises): None


startRecMsg(NameList=['HIGHRES_IMU'], LenList=[10])

Function Description: Starts recording specified MAVLink messages from the provided list, setting the cache length for each message type.
Parameters (Args):

Parameter Name Type Required Default Value Description
NameList list[str] No ['HIGHRES_IMU'] List of MAVLink message names to record; defaults to high-precision IMU messages
LenList list[int] No [10] Corresponding cache lengths for each message type, i.e., the maximum number of latest messages to store; must match the length of NameList

Return Value (Returns):

  • None

Exceptions (Raises): None


stopRecMsg()

Function Description: Stops all ongoing MAVLink message recordings and clears all registered recording entries.
Return Value (Returns):

  • None

Exceptions (Raises): None


getMavMsg()

Function Description: Retrieves all currently cached recorded MAVLink message data.
Return Value (Returns):

  • dict: Keys are message names; values are lists of corresponding cached message data

Exceptions (Raises): None

Example:

from RflySimSDK.phm import MavDataRec
# Bind an established MAVLink connection object 'mav'
recorder = MavDataRec(mav)
# Start recording IMU and attitude messages, caching 100 entries each
recorder.startRecMsg(NameList=['HIGHRES_IMU', 'ATTITUDE'], LenList=[100, 100])
# Retrieve recorded data during flight
recorded_data = recorder.getMavMsg()
imu_data = recorded_data['HIGHRES_IMU']
# Stop recording
recorder.stopRecMsg()

---

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

```python
import asyncio
from RflySimSDK.phm import MavDataRec
from concurrent.futures import ThreadPoolExecutor

# Batch-initialize multiple drone log recording tasks with asynchronous control over start/stop timing
async def batch_mav_data_rec(drone_id_list, rec_duration):
    rec_instances = [MavDataRec(drone_id) for drone_id in drone_id_list]
    # Start MAVLink message recording for all drones in batch
    for inst in rec_instances:
        inst.startRecMsg()
    print(f"Started message recording for {len(rec_instances)} drones, duration: {rec_duration} seconds")

    # Asynchronously wait for the recording duration; during this period, asynchronously fetch latest messages for preprocessing
    await asyncio.sleep(rec_duration)
    # Use multi-threading to concurrently fetch and store records locally, enhancing processing efficiency for high-throughput data
    with ThreadPoolExecutor(max_workers=len(rec_instances)) as pool:
        all_mav_data = list(pool.map(lambda x: x.getMavMsg(), rec_instances))
    # Stop all recording tasks in batch
    for inst in rec_instances:
        inst.stopRecMsg()
    return all_mav_data

# Execute multi-drone collaborative data acquisition task
if __name__ == "__main__":
    drone_list = [1, 2, 3]
    mav_data = asyncio.run(batch_mav_data_rec(drone_list, 10))
    for idx, data in enumerate(mav_data):
        print(f"Drone {drone_list[idx]} recorded {len(data)} MAVLink messages")

Notes and Pitfall Avoidance Guide

  • Duplicate Start Check Before Initialization: Prior to calling startRecMsg(), verify that the current recording task is not already active. Repeated invocation will cause message data to accumulate redundantly in memory, resulting in duplicated segments in the final retrieved data, consuming extra memory and interfering with subsequent analysis.

  • Timing Constraint for Message Retrieval: getMavMsg() must be called after startRecMsg() and before stopRecMsg(). Invoking it before the task starts or after it has stopped will return an empty list or only incomplete, partially cached data, preventing acquisition of the complete recorded dataset.

  • Resource Conflict Avoidance for Multiple Instances: Creating multiple MavDataRec instances for the same drone and concurrently calling startRecMsg() on them will cause competition for MAVLink port data reads, leading each instance to capture only fragmented, incomplete message subsets. It is recommended to maintain only one active recording instance per drone at any given time.

  • Memory Management for Long-Duration Recording: For flight data recordings exceeding 10 minutes, it is advisable to segment the recording process by repeatedly calling startRecMsg() and stopRecMsg() and storing messages in segments. This avoids continuous in-memory caching of all messages, which can cause steadily increasing memory usage, leading to application sluggishness or even out-of-memory errors.

Changelog

  • 2024-08-02: chore: Added code comments for HTML-format API generation
  • 2024-07-18: fix: Updated API homepage index
  • 2023-10-23: feat: Added required interface files