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¶
The following example uses the Redis key-value interface to write and read drone status. Before running, ensure the RflySim-compatible Redis service is started.
Reference example: [RflySim installation path]\RflySimAPIs\9.RflySimComm\2.AdvExps\e1.CoaGraNetSimExps\3.Redis\e1.2-KeyValueComm
import RedisUtils
redisConnect = RedisUtils.RedisUtils()
uavState = {
"CopterID": 1,
"uavTimeStmp": 0.0,
"uavPosNED": [0.0, 0.0, -10.0],
"uavVelNED": [0.0, 0.0, 0.0],
}
# Save structured data with "UAV1" as the key
redisConnect.set_data("UAV1", uavState)
# Other processes can actively read the latest status using the same key
data = redisConnect.get_data("UAV1")
if data is not False:
print(data)
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 data in 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 data items 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 | Channel name for Redis publish/subscribe |
| data | Any | Yes | None | Message data to be published; will be 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 | Channel name for Redis publish/subscribe |
| 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 on 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 | Redis channel name to subscribe to |
| callback | - | Yes | None | Callback function triggered upon message arrival; receives the parsed message as an argument |
Return Value (Returns): None
Exceptions (Raises): None
sub_singledata(message_type, channel, callback)¶
Function Description: Subscribes to single-data messages on 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 | Redis channel name to subscribe to |
| callback | - | Yes | None | Callback function triggered upon message arrival; receives the parsed message as an 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, containing multiple channels to be subscribed |
| 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, containing multiple channels to be subscribed |
| 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:
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_singledataare for operations on individual, independent key-value pairs, whereasset_data/get_dataare 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_dbdirectly 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_singledataandget_one_datareturnNone. 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_dataappends data to an existing list. If the intention is to overwrite the original list content,del_datashould 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
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, containing multiple channels to be subscribed |
| 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¶
The following example combines publish/subscribe and key-value read/write: a subscription thread receives multi-UAV status, and the callback function writes the aggregated results back to Redis.
Reference example: [RflySim installation path]\RflySimAPIs\9.RflySimComm\1.BasicExps\e4.RedisUAVsCommExps\2.NetSimMini_redis_nomat
import threading
import time
import RedisUtils
redisConnect = RedisUtils.RedisUtils()
uavData = {}
def sub_callback(channel, data):
uavData[channel] = data
print("Received", channel, data)
# After collecting data from all three UAVs, write the aggregated positions to a regular key-value pair
if len(uavData) == 3:
positions = [uavData[key]["uavPosNED"] for key in sorted(uavData)]
redisConnect.set_data("UavPositions", positions)
channels = ["UAV2", "UAV3", "UAV4"]
subThread = threading.Thread(
target=redisConnect.sub_data_multiple_channels,
args=("message", channels, sub_callback),
)
subThread.start()
time.sleep(0.5)
# Publish local status; other UAVs use their respective channel names
redisConnect.pub_data(
"UAV1",
{"CopterID": 1, "uavPosNED": [0.0, 0.0, -10.0]},
)
Notes and Pitfall Avoidance Guide¶
- Distinguish between batch and single-key operation methods:
set_singledata/get_singledataare for operations on individual, independent key-value pairs, whereasset_data/get_dataare 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_dbdirectly 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_singledataandget_one_datareturnNone. 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_dataappends data to an existing list. If the intention is to overwrite the original list content,del_datashould 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