Skip to content

RedisUtils Interface Documentation

Introduction

Overview: This file provides a Redis-based communication utility class, designed for handling data subscription callbacks in drone simulation scenarios. It supports Redis data exchange for the communication module of RflySimSDK.

In the RflySim drone simulation system, multiple modules require efficient inter-process data exchange. Redis, as a high-performance in-memory data store, is commonly used in drone simulations for relaying and distributing real-time flight data, status information, and sensor data. This module encapsulates common Redis communication operations and provides subscription callback handling capabilities. It is suitable for scenarios where different components in a simulation environment need to retrieve real-time flight data, monitor the status of other modules, and respond to data updates. This utility helps developers quickly build Redis-based simulation data communication pipelines without having to implement low-level logic for Redis connections and subscription callbacks.

Quick Start

A minimal working example; copy and modify only the necessary configurations to run. Ensure the local Redis service is running—default port 6379 is sufficient.

from RflySimSDK.comm.RedisUtils import RedisUtils

# Initialize Redis connection utility; by default connects to Redis service on localhost port 6379
redis_util = RedisUtils()

# Define test key name
test_key = "test_rfly_key"
# Prepare test data to store
test_data = {"vehicle_id": 1, "position": [120.1, 30.2, 100.5]}

# Write data to Redis
redis_util.set_data(test_key, test_data)
print(f"Data written successfully: {test_key} -> {test_data}")

# Read data from Redis
read_data = redis_util.get_data(test_key)
print(f"Data retrieved: {read_data}")

# Test writing a single simple data value
simple_key = "test_simple_key"
simple_data = "hello rflysim"
redis_util.set_singledata(simple_key, simple_data)
print(f"Simple data written successfully: {simple_key} -> {simple_data}")
read_simple = redis_util.get_data(simple_key)
print(f"Simple data retrieved: {read_simple}")

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: json, redis, threading, time
  • Prerequisites: Before calling this interface, ensure the Redis service is running properly and the relevant connection configurations are completed.

Core Interface Description

The module RedisUtils.py contains configuration variables, helper functions, and the core business class.

Global Constants and Enum Definitions

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

Standalone Constants

None


Global/Standalone Functions

sub_callback(channel, data)

Function Description: Message subscription callback function, used to process message data received on the corresponding channel. Typically used as the callback argument for subscription interfaces. Parameters:

  • channel: Identifier of the channel on which the message was received, indicating the source channel of the data.
  • data: Message data received on the corresponding channel, representing the actual content transmitted over the channel.

Return Value:

  • None

Exceptions: - None


RedisUtils Class

Redis utility class, providing Redis connection and data manipulation capabilities. It belongs to the RflySimSDK communication module.

__init__()

Function Description: Initializes an instance of the Redis utility class. Parameters (Args): - None Return Value (Returns): None Exceptions (Raises): None

set_data(key, data)

Function Description: Stores serialized data in Redis under the specified key. Parameters (Args):

Parameter Type Required Default Description
key Any Yes None Key name used to store data in Redis
data Any Yes None Data to be stored; will be automatically serialized

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


set_singledata(key, data)

Function Description: Stores raw string data in Redis under the specified key. Parameters (Args):

Parameter Type Required Default Description
key Any Yes None Key name used to store data in Redis
data str Yes None Raw string data to be stored

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


get_data(key)

Function Description: Retrieves and deserializes data from Redis for the specified key. Parameters (Args):

Parameter Type Required Default Description
key Any Yes None Key name used to retrieve data from Redis

Return Value (Returns): Deserialized original data; returns None if the key does not exist.
Exceptions (Raises): None


get_singledata(key)

Function Description: Retrieves raw string data from Redis for the specified key. Parameters (Args):

Parameter Type Required Default Description
key Any Yes None Key name used to retrieve data from Redis

Return Value (Returns): Raw string data; returns None if the key does not exist.
Exceptions (Raises): None


get_data_list()

Function Description: Retrieves a list of all key names in the current Redis database. Parameters (Args): None
Return Value (Returns): A list containing all key names.
Exceptions (Raises): None


del_data(key)

Function Description: Deletes data associated with the specified key in Redis. Parameters (Args):

Parameter Type Required Default Description
key Any Yes None Key name of the data to be deleted in Redis

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


key_count()

Function Description: Counts the total number of keys in the current Redis database. Parameters (Args): None
Return Value (Returns): Number of keys in the current database.
Exceptions (Raises): None


clear_db()

Function Description: Clears all data in the current Redis database. Parameters (Args): None
Return Value (Returns): None
Exceptions (Raises): None


insert_data(db, data)

Function Description: Inserts data into the tail (right end) of a specified Redis list queue. Parameters (Args):

Parameter Type Required Default Description
db str Yes None Key name of the Redis list queue
data Any Yes None Data to be inserted into the queue

Return Value (Returns): Length of the queue after the insertion operation.
Exceptions (Raises): None


get_one_data(db)

Function Description: Removes and retrieves one item from the head (left end) of a specified Redis list queue. Parameters (Args):

Parameter Type Required Default Description
db str Yes None Key name of the Redis list queue

Return Value (Returns): Retrieved data; returns None if the queue is empty.
Exceptions (Raises): None


get_all_data(db)

Function Description: Retrieves all data from a specified Redis list queue. Parameters (Args):

Parameter Type Required Default Description
db str Yes None Key name of the Redis list queue

Return Value (Returns): A list containing all data in the queue.
Exceptions (Raises): None


queue_count(db)

Function Description: Retrieves the length of a specified Redis list queue.
Parameters (Args):

Parameter Name Type Required Default Value Description
db str Yes None Key name of the Redis list queue

Return Value (Returns): Number of elements in the queue
Exceptions (Raises): None


clear_queue(db)

Function Description: Clears all data from a specified Redis list queue.
Parameters (Args):

Parameter Name Type Required Default Value Description
db str Yes None Key name of the Redis list queue

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


pub_data(key, data)

Function Description: Publishes a serialized message to a specified Redis channel.
Parameters (Args):

Parameter Name Type Required Default Value Description
key Any Yes None Name of the Redis pub/sub channel
data Any Yes None Message data to be published; automatically serialized

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


pub_singledata(key, data)

Function Description: Publishes a raw string message to a specified Redis channel.
Parameters (Args):

Parameter Name Type Required Default Value Description
key Any Yes None Name of the Redis pub/sub channel
data str Yes None Raw string message to be published

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


sub_data(message_type, channel, callback)

Function Description: Subscribes to multi-data messages from a specified Redis channel; triggers the designated callback function upon message arrival for processing.
Parameters (Args):

Parameter Name Type Required Default Value Description
message_type - Yes None Data type of subscribed messages, used for parsing received messages
channel - Yes None Name of the Redis channel to subscribe to
callback - Yes None Callback function triggered upon message arrival; receives the parsed message as its argument

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


sub_singledata(message_type, channel, callback)

Function Description: Subscribes to single-data messages from a specified Redis channel; triggers the designated callback function upon message arrival for processing.
Parameters (Args):

Parameter Name Type Required Default Value Description
message_type - Yes None Data type of subscribed messages, used for parsing received messages
channel - Yes None Name of the Redis channel to subscribe to
callback - Yes None Callback function triggered upon message arrival; receives the parsed message as its argument

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


sub_data_multiple_channels(message_type, channels, callback)

Function Description: Subscribes to multi-data messages from multiple Redis channels simultaneously; triggers the designated callback function upon message arrival on any channel for processing.
Parameters (Args):

Parameter Name Type Required Default Value Description
message_type - Yes None Data type of subscribed messages, used for parsing received messages
channels - Yes None List of Redis channel names to subscribe to
callback - Yes None Callback function triggered upon message arrival; receives the parsed message and source channel information as arguments

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


sub_singledata_multiple_channels(message_type, channels, callback)

Function Description: Subscribes to single-data messages from multiple Redis channels simultaneously; triggers the designated callback function upon message arrival on any channel for processing.
Parameters (Args):

Parameter Name Type Required Default Value Description
message_type - Yes None Data type of subscribed messages, used for parsing received messages
channels - Yes None List of Redis channel names to subscribe to
callback - Yes None Callback function triggered upon message arrival; receives the parsed message and source channel information as arguments

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

Advanced Usage Examples

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

This example demonstrates asynchronous state synchronization and batch data processing for a heterogeneous multi-UAV task cluster based on RedisUtils, combined with an asynchronous I/O framework to achieve concurrent read/write operations across multiple tasks, meeting real-time multi-vehicle state update requirements in large-scale simulations:

```python import asyncio from RflySimSDK.comm import RedisUtils

async def process_uav_status(uav_id, redis_utils): # Asynchronously retrieve the current flight status of a single UAV current_status = redis_utils.get_singledata(f"uav:{uav_id}:status") if current_status is None: return # Update the status based on mission requirements and write it back current_status["mode"] = "formation_keep" redis_utils.set_singledata(f"uav:{uav_id}:status", current_status)

async def batch_update_uavs(uav_count, redis_utils): # Batch generate tasks and concurrently update statuses of multiple UAVs tasks = [process_uav_status(uav_id, redis_utils) for uav_id in range(1, uav_count + 1)] await asyncio.gather(*tasks)

def main(): # Initialize connection redis_utils = RedisUtils(host='localhost', port=6379, db=0) # Pre-store batch mission waypoint data waypoint_list = [[(10, 10, 100), (20, 20, 100)], [(15, 15, 100), (25, 25, 100)]] for idx, waypoints in enumerate(waypoint_list): redis_utils.insert_data(f"uav:{idx+1}:waypoints", waypoints) # Execute asynchronous batch updates asyncio.run(batch_update_uavs(2, redis_utils)) # Count the number of stored UAV data entries print(f"Current number of stored UAV data entries: {redis_utils.key_count()}")

if name == "main": main()

Notes and Pitfall Avoidance Guide

  • Distinguish between batch and single-key operation methods: set_singledata/get_singledata are for operations on individual, independent key-value pairs, whereas set_data/get_data are for list-like collection data. Mixing them will cause data structure anomalies and prevent normal retrieval of results.
  • Risk warning for database clearing: Calling clear_db directly clears all key-value pairs in the currently selected Redis database, including flight state and configuration information stored by the RflySim simulation core. It should only be invoked after custom data tasks are fully completed, and must not be used during simulation execution.
  • Handling of null-value returns: When the queried key does not exist, get_singledata and get_one_data return None. Directly accessing attributes or indices on the returned result will trigger a null pointer exception; a null-check must be added before usage.
  • Key duplication issue in batch insertion: insert_data appends data to an existing list. If the intention is to overwrite the original list content, del_data should be called first to delete the old key, followed by the insertion; otherwise, a mix of old and new data will occur, leading to errors.

Changelog

  • 2025-05-29: fix: Update the platform protocol summary page