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.
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.
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
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
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"}'
Using the SUBSCRIBE
command you can subscribe to a topic and listen for data to be emitted.
SUBSCRIBE "mudpi/example/topic"
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
.
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='127.0.0.1', port=6379, decode_responses=True)
r.publish('mudpi/example/topic', json.dumps('10'))
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='127.0.0.1', port=6379, decode_responses=True)
pubsub = r.pubsub()
def print_event(data):
print(data)
pubsub.subscribe(**{'mudpi/example/topic':print_event})
pubsub.get_message()
time.sleep(1)
pubsub.unsubscribe('mudpi/example/topic')
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.
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) |