Using Redis with MudPi

MudPi uses an event system at its core to communicate between systems bother internal and external. One of the protocols this even system uses is Redis which has a large support base across platforms making it ideal to exchange data between them.

Using Redis CLI Tools

When redis is installed it also has a redis-cli tool for you to use. Using your terminal of choice you can enter the redis-cli command to enter into the tool.

Get Data from Key/Value Store

Redis contains a key/value store as well as the pub/sub event system. MudPi will store a copy of states for you inside Redis. You can access this data by using the GET command followed by the key of the data to fetch. Below is an example of getting data stored under an example key.

GET example

Set Data in Key/Value Store

In conjunction with the GET command you can also SET data in the store as well. Use the SET command followed but the key and data to store. The follow example will store the value of 10 under the key example.

SET example 10

Publish Data

To publish an event over Redis containing data you can use the PUBLISH command to publish the event. The following example will publish the number 10 over the mudpi/example/topic channel.

PUBLISH mudpi/example/topic 10  

Redis only uses strings for its data so you should encode data using something like JSON. Here is an example of sending a dict over a mudpi/example/topic channel.

PUBLISH mudpi/example/topic '{"data": "10"}'

Subscribe to a Topic

Using the SUBSCRIBE command you can subscribe to a topic and listen for data to be emitted.

SUBSCRIBE "mudpi/example/topic"

Interact with Redis using Python

You can also publish data over Redis with Python through the support of redis python library. If you do not have it installed you can run pip3 install redis.

Publish Event Data

The script below will show you an example of how to create a connection to a redis server and use a pubsub client to publish an event. The data 10 is being sent over the topic mudpi/example/topic in this case.

import redis
import json
r = redis.Redis(host='', port=6379, decode_responses=True)
r.publish('mudpi/example/topic', json.dumps('10'))

Subscribe to Events

You can also subscribe to a topic and listen for events as well. The example below will subscribe to the mudpi/example/topic topic and print out any data it receives.

import redis
import json

r = redis.Redis(host='', port=6379, decode_responses=True)
pubsub = r.pubsub()

def print_event(data):



Once you subscribe to a topic you need to periodically call the get_message() function in order to check for new events to be handled. Typically this is ran in a loop with short delay between each check.

MudPi Smart Garden
Getting Started with a Raspberry Pi from Scratch
1 Preparing the SD Card 4:02
2 Booting Up & Configuring Raspbian 4:48
3 SSH and SSH Keys (Video Coming Soon)
4 Updating Python on Raspbian & Installing Useful Packages (Video Coming Soon)