A comprehensive Redis client library for ESP32 that supports both local storage using ESP32's preferences memory (NVS) and TCP communication with remote Redis servers using the Redis Serialization Protocol (RESP). Additionally, it can act as a Redis-compatible server that receives RESP commands and stores them locally. This library provides a Redis-compatible API for persistent data storage and network communication on ESP32 microcontrollers.
- Triple Mode Operation: Local storage (NVS), TCP Redis client, and TCP Redis server
- Redis Serialization Protocol (RESP): Full RESP protocol implementation for Redis communication
- Redis Server Mode: ESP32 can act as a Redis-compatible server
- Redis-compatible API: Familiar Redis commands and data structures
- Persistent Storage: Uses ESP32 Preferences (NVS) for non-volatile local storage
- WiFi Support: Built-in WiFi connectivity for TCP Redis communication
- Multiple Data Types: Strings, Lists, and Hashes
- Key Management: Expiration, renaming, and existence checking
- Memory Efficient: Optimized for ESP32's limited memory
- Easy Integration: Simple Arduino-style API
- Keep-Alive: Automatic connection maintenance for TCP connections
- Client Management: Handles multiple client connections
- Stores data in ESP32's non-volatile storage
- Data persists across reboots
- No network required
- Limited by ESP32's NVS space
- Connects to remote Redis servers via TCP
- Uses Redis Serialization Protocol (RESP)
- Full Redis server compatibility
- Requires WiFi connection
- ESP32 acts as a Redis-compatible server
- Receives RESP commands from clients
- Stores data locally in NVS
- Handles multiple client connections
- Perfect for IoT device communication
SET,GET,APPEND,STRLEN,SUBSTR
LPUSH,RPUSH,LPOP,RPOP,LINDEX,LLEN,LRANGE
HSET,HGET,HDEL,HEXISTS,HKEYS,HGETALL,HLEN
EXISTS,DEL,RENAME,EXPIRE,TTL,KEYS
FLUSHDB,DBSIZE,INFO
PING,ECHO,AUTH,SELECT,QUIT
-
Download the library files:
ESP32RedisClient.hESP32RedisClient.cpp
-
Place them in your Arduino project directory or create a library folder.
-
Include the header in your Arduino sketch:
#include "ESP32RedisClient.h"
#include <Arduino.h>
#include "ESP32RedisClient.h"
ESP32RedisClient redis;
void setup() {
Serial.begin(115200);
// Connect to local storage
if (redis.connect()) {
Serial.println("Connected to local Redis storage");
}
// Basic operations
redis.set("name", "ESP32");
String value = redis.get("name");
Serial.println("Name: " + value);
// List operations
redis.lpush("items", "apple");
redis.lpush("items", "banana");
// Hash operations
redis.hset("user", "name", "John");
redis.hset("user", "age", "30");
}
void loop() {
// Your main code here
}#include <Arduino.h>
#include "ESP32RedisClient.h"
ESP32RedisClient redis;
void setup() {
Serial.begin(115200);
// Connect to WiFi
if (redis.connect("YOUR_WIFI_SSID", "YOUR_WIFI_PASSWORD")) {
Serial.println("WiFi connected");
// Connect to Redis server
if (redis.connectTCP("192.168.1.100", 6379)) {
Serial.println("Connected to Redis server");
// Test connection
String response = redis.ping();
Serial.println("PING response: " + response);
// Basic operations via TCP
redis.set("name", "ESP32", true); // use_tcp = true
String value = redis.get("name", true);
Serial.println("Name: " + value);
// Send raw RESP commands
String set_response = redis.sendCommand("SET", "key", "value");
String get_response = redis.sendCommand("GET", "key");
Serial.println("SET response: " + set_response);
Serial.println("GET response: " + get_response);
}
}
}
void loop() {
// Your main code here
}#include <Arduino.h>
#include "ESP32RedisClient.h"
ESP32RedisClient redis;
void setup() {
Serial.begin(115200);
// Connect to WiFi
if (redis.connect("YOUR_WIFI_SSID", "YOUR_WIFI_PASSWORD")) {
Serial.println("WiFi connected");
// Start Redis server
if (redis.startServer(6379)) {
Serial.println("Redis server started on " + redis.getServerIP());
Serial.println("Port: " + String(redis.getServerPort()));
// Add some initial data
redis.set("server_name", "ESP32 Redis Server");
redis.hset("server_info", "version", "1.0.0");
redis.lpush("activity_log", "SERVER_STARTED");
}
}
}
void loop() {
// Handle incoming client connections
redis.handleServer();
delay(10);
}Constructor. Creates a Redis client instance.
namespace_name(optional): Namespace for preferences storage (default: "redis")
Connects to local Redis storage and initializes preferences storage.
- Returns:
trueif connection successful,falseotherwise
Connects to WiFi network.
- Parameters:
ssid: WiFi network namepassword: WiFi password
- Returns:
trueif WiFi connection successful,falseotherwise
Connects to a remote Redis server via TCP.
- Parameters:
host: Redis server IP address or hostnameport: Redis server port (default: 6379)
- Returns:
trueif TCP connection successful,falseotherwise
Disconnects from local Redis storage and closes preferences storage.
- Returns:
trueif disconnection successful,falseotherwise
Disconnects from TCP Redis server.
- Returns:
trueif disconnection successful,falseotherwise
Checks if the Redis client is connected (local or TCP).
- Returns:
trueif connected,falseotherwise
Checks if the client is in TCP mode.
- Returns:
trueif in TCP mode,falseotherwise
Starts the ESP32 as a Redis-compatible server.
- Parameters:
port: Server port (default: 6379) - Returns:
trueif server started successfully,falseotherwise
Stops the Redis server.
- Returns:
trueif server stopped successfully,falseotherwise
Handles incoming client connections and processes RESP commands.
- Note: Call this method in the main loop to process client requests
Checks if the ESP32 is in server mode.
- Returns:
trueif in server mode,falseotherwise
Checks if the Redis server is currently running.
- Returns:
trueif server is running,falseotherwise
Gets the IP address of the Redis server.
- Returns: Server IP address as String
Gets the port number of the Redis server.
- Returns: Server port number
Sends a RESP command to Redis server.
- Parameters:
command: Vector of command arguments - Returns: Parsed response from Redis server
Sends a single-argument RESP command.
- Parameters:
command: Command name - Returns: Parsed response from Redis server
Sends a two-argument RESP command.
- Parameters:
cmd1: First argumentcmd2: Second argument
- Returns: Parsed response from Redis server
Sends a three-argument RESP command.
- Parameters:
cmd1: First argumentcmd2: Second argumentcmd3: Third argument
- Returns: Parsed response from Redis server
Sends a four-argument RESP command.
- Parameters:
cmd1: First argumentcmd2: Second argumentcmd3: Third argumentcmd4: Fourth argument
- Returns: Parsed response from Redis server
Sends PING command to Redis server.
- Returns: "PONG" if server is responsive
Sends ECHO command to Redis server.
- Parameters:
message: Message to echo - Returns: Echoed message from server
Authenticates with Redis server.
- Parameters:
password: Redis server password - Returns: Authentication result
Selects Redis database.
- Parameters:
database: Database number (0-15) - Returns: Selection result
Closes connection to Redis server.
- Returns: Quit confirmation
Sets a key-value pair in local storage or TCP Redis server.
- Parameters:
key: The key namevalue: The value to storeuse_tcp:truefor TCP mode,falsefor local storage
- Returns:
trueif successful,falseotherwise
Gets the value for a key from local storage or TCP Redis server.
- Parameters:
key: The key nameuse_tcp:truefor TCP mode,falsefor local storage
- Returns: The value as String, empty string if key doesn't exist
Deletes a key from local storage or TCP Redis server.
- Parameters:
key: The key nameuse_tcp:truefor TCP mode,falsefor local storage
- Returns:
trueif key was deleted,falseif key didn't exist
Checks if a key exists in local storage or TCP Redis server.
- Parameters:
key: The key nameuse_tcp:truefor TCP mode,falsefor local storage
- Returns:
trueif key exists,falseotherwise
Sets a key-value pair.
- Parameters:
key: The key namevalue: The value to store
- Returns:
trueif successful,falseotherwise
Gets the value for a key.
- Parameters:
key: The key name - Returns: The value as String, empty string if key doesn't exist
Appends a value to an existing string.
- Parameters:
key: The key namevalue: Value to append
- Returns:
trueif successful,falseotherwise
Gets the length of a string value.
- Parameters:
key: The key name - Returns: Length of the string, 0 if key doesn't exist
Gets a substring of a string value.
- Parameters:
key: The key namestart: Start positionend: End position (-1 for end of string)
- Returns: The substring
Pushes a value to the left (beginning) of a list.
- Parameters:
key: The list keyvalue: Value to push
- Returns: New length of the list
Pushes a value to the right (end) of a list.
- Parameters:
key: The list keyvalue: Value to push
- Returns: New length of the list
Pops a value from the left (beginning) of a list.
- Parameters:
key: The list key - Returns: The popped value, empty string if list is empty
Pops a value from the right (end) of a list.
- Parameters:
key: The list key - Returns: The popped value, empty string if list is empty
Gets the value at a specific index in a list.
- Parameters:
key: The list keyindex: Index position (negative for reverse indexing)
- Returns: The value at the index, empty string if index out of range
Gets the length of a list.
- Parameters:
key: The list key - Returns: Length of the list
Gets a range of values from a list.
- Parameters:
key: The list keystart: Start indexend: End index (-1 for end of list)
- Returns: Vector of strings in the range
Sets a field-value pair in a hash.
- Parameters:
key: The hash keyfield: The field namevalue: The value to store
- Returns:
trueif successful,falseotherwise
Gets the value of a field in a hash.
- Parameters:
key: The hash keyfield: The field name
- Returns: The field value, empty string if field doesn't exist
Deletes a field from a hash.
- Parameters:
key: The hash keyfield: The field name
- Returns:
trueif field was deleted,falseif field didn't exist
Checks if a field exists in a hash.
- Parameters:
key: The hash keyfield: The field name
- Returns:
trueif field exists,falseotherwise
Gets all field names in a hash.
- Parameters:
key: The hash key - Returns: Vector of field names
Gets all field-value pairs in a hash.
- Parameters:
key: The hash key - Returns: Map of field-value pairs
Gets the number of fields in a hash.
- Parameters:
key: The hash key - Returns: Number of fields
Checks if a key exists.
- Parameters:
key: The key name - Returns:
trueif key exists,falseotherwise
Deletes a key.
- Parameters:
key: The key name - Returns:
trueif key was deleted,falseif key didn't exist
Renames a key.
- Parameters:
old_key: Current key namenew_key: New key name
- Returns:
trueif successful,falseotherwise
Sets expiration time for a key.
- Parameters:
key: The key nameseconds: Expiration time in seconds
- Returns: 1 if expiration was set, 0 if key doesn't exist
Gets the time to live for a key.
- Parameters:
key: The key name - Returns: TTL in seconds, -1 if no expiration, -2 if key doesn't exist
Gets all keys matching a pattern.
- Parameters:
pattern: Pattern to match (default: "*") - Returns: Vector of matching keys
Removes all keys from the database.
- Returns:
trueif successful,falseotherwise
Gets the number of keys in the database.
- Returns: Number of keys
Gets information about the Redis client and database.
- Returns: Information string
Prints all keys in the database to Serial.
Prints all data in the database to Serial.
Gets the approximate used space in bytes.
- Returns: Used space in bytes
Gets the approximate free space in bytes.
- Returns: Free space in bytes
ESP32RedisClient redis;
void setup() {
redis.connect();
// Store data
redis.set("sensor_temp", "25.5");
redis.set("sensor_humidity", "60");
// Retrieve data
String temp = redis.get("sensor_temp");
String humidity = redis.get("sensor_humidity");
Serial.println("Temperature: " + temp + "°C");
Serial.println("Humidity: " + humidity + "%");
}// Store sensor readings as a list
redis.rpush("readings", "25.5");
redis.rpush("readings", "26.1");
redis.rpush("readings", "24.8");
// Get all readings
std::vector<String> readings = redis.lrange("readings", 0, -1);
for (const String& reading : readings) {
Serial.println("Reading: " + reading);
}
// Get latest reading
String latest = redis.rpop("readings");
Serial.println("Latest: " + latest);// Store user profile
redis.hset("user:123", "name", "John Doe");
redis.hset("user:123", "email", "john@example.com");
redis.hset("user:123", "age", "30");
// Get user info
String name = redis.hget("user:123", "name");
String email = redis.hget("user:123", "email");
// Get all user data
std::map<String, String> user_data = redis.hgetall("user:123");
for (auto& pair : user_data) {
Serial.println(pair.first + ": " + pair.second);
}// Set a temporary value
redis.set("temp_data", "important_data");
redis.expire("temp_data", 60); // Expires in 60 seconds
// Check TTL
int ttl = redis.ttl("temp_data");
Serial.println("TTL: " + String(ttl) + " seconds");// Connect to WiFi and Redis server
redis.connect("WiFi_SSID", "WiFi_Password");
redis.connectTCP("192.168.1.100", 6379);
// Test connection
String pong = redis.ping();
Serial.println("Server response: " + pong);
// Send raw RESP commands
String set_result = redis.sendCommand("SET", "sensor_data", "25.5");
String get_result = redis.sendCommand("GET", "sensor_data");
// Use enhanced operations with TCP
redis.set("temperature", "25.5", true); // TCP mode
String temp = redis.get("temperature", true);
// List operations via TCP
redis.sendCommand("LPUSH", "readings", "25.5");
redis.sendCommand("LPUSH", "readings", "26.1");
String readings = redis.sendCommand("LRANGE", "readings", "0", "-1");
// Hash operations via TCP
redis.sendCommand("HSET", "device", "name", "ESP32");
redis.sendCommand("HSET", "device", "location", "Room1");
String device_name = redis.sendCommand("HGET", "device", "name");// Manual RESP command construction
std::vector<String> command = {"SET", "key", "value"};
String resp_command = redis.encodeRESPCommand(command);
Serial.println("RESP: " + resp_command);
// Output: *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n
// Send complex commands
String result = redis.sendCommand("MSET", "key1", "value1", "key2", "value2");
String info = redis.sendCommand("INFO", "server");
// Database operations
redis.select(1); // Switch to database 1
redis.set("db1_key", "db1_value", true);
redis.select(0); // Switch back to database 0// Start ESP32 as Redis server
redis.connect("WiFi_SSID", "WiFi_Password");
redis.startServer(6379);
// In main loop, handle client connections
void loop() {
redis.handleServer();
delay(10);
}
// Clients can now connect to ESP32 using:
// redis-cli -h ESP32_IP -p 6379
// Or another ESP32 with the client library// ESP32 Server (Device 1)
ESP32RedisClient server_redis;
server_redis.connect("WiFi_SSID", "WiFi_Password");
server_redis.startServer(6379);
// ESP32 Client (Device 2)
ESP32RedisClient client_redis;
client_redis.connect("WiFi_SSID", "WiFi_Password");
client_redis.connectTCP("192.168.1.100", 6379); // ESP32 Server IP
// Send data from client to server
client_redis.set("sensor_data", "25.5", true);
client_redis.sendCommand("HSET", "device_info", "location", "Room1");
// Server automatically stores data locally- Memory Constraints: ESP32 has limited NVS space (typically 1-2MB)
- TTL Implementation: TTL is approximate and requires periodic checking
- Key Length: Keys are limited to reasonable lengths for memory efficiency
- Value Size: Large values may impact performance
- Network Dependency: Requires stable WiFi connection
- Server Availability: Redis server must be running and accessible
- Memory Usage: TCP buffers consume additional RAM
- Latency: Network operations are slower than local storage
- Connection Management: TCP connections may timeout or drop
- RESP Parsing: Complex responses may require additional parsing
- Single Client: Handles one client connection at a time
- Memory Constraints: Limited by ESP32's RAM for client buffers
- Command Processing: Sequential command processing (no pipelining)
- Network Dependency: Requires stable WiFi connection
- No Persistence: Data stored in NVS, not traditional Redis persistence
- Limited Commands: Not all Redis commands are implemented
- The library uses ESP32 Preferences (NVS) for persistent storage
- Data persists across reboots
- Keys are stored with prefixes to avoid conflicts
- Metadata is stored separately for type information
- Uses WiFiServer for TCP server functionality
- Client connections handled sequentially
- RESP protocol parsing and response generation
- Data stored locally in NVS using existing storage methods
- Client buffers managed by WiFiClient library
- All methods return appropriate success/failure indicators
- Invalid keys or values are rejected
- Connection status is checked before operations
- Memory constraints are handled gracefully
- String operations are fastest
- List operations require parsing and rebuilding
- Hash operations are most memory-intensive
- Consider data size and frequency of operations
The library includes several example files to demonstrate different features:
Comprehensive example showing all local storage features including strings, lists, hashes, and key management operations.
Complete example demonstrating TCP Redis communication with RESP protocol, including WiFi connection, Redis server communication, and both local and remote operations.
Example showing ESP32 as a Redis-compatible server that receives RESP commands and stores them locally.
Example demonstrating how to connect to an ESP32 Redis server from another ESP32 client.
Comprehensive demo showing both server and client functionality on the same ESP32.
Educational example showing RESP protocol encoding and decoding without requiring a Redis server connection.
Test suite to verify library functionality with automated tests for all major features.