Introduction
In the following example, we’re trying to solve the problem of event-driven communication. A data sink is only updated when the source data is published. I strongly recommend reading my previous posts on this topic if you have not already done so. In this, Simple MQTT Examples #1 – Getting Started Easy, we give an introductory example, and in this, MQTT – How to consume a snapshot value published in the past., we talk about several possible solutions.
Running the Example
Source Code Location
https://github.com/siul72/python-iot-demo/releases/tag/1.0.0-request-force-event
Run the temperature_data_collector.py, this is the component that reads the sensor data and publishes it to the mqtt broker:
The collector starts normally and publish data every 60 seconds
Picture 1 – Start the temperature data collector
Run display_gateway.py, this software component subscribes to the sensor data and displays it to the GUI:
Picture 2 – command line display_gateway.py startup
An request update is required to the collector, and it sends an update event with the current value
Picture 3 – datacollector output with display request
As you notice the display gets updated as soon as it starts instead of waiting for the next event:
Additional features
Some additional features have been added to the previous version. For example, a small color square indicates when the display is connected to the MQTT broker. You can stop the Mosquito service and watch the display output to quickly test this feature.
iot-demo@ubuntu:~/workspace/python-iot-demo$ systemctl stop mosquitto.service
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to stop 'mosquitto.service'.
Authenticating as: iot-demo
Password:
==== AUTHENTICATION COMPLETE ===
iot-demo@ubuntu:~/workspace/python-iot-demo$
And the output is something like this:
I hope that these simple examples will help you with your first steps with MQTT for your home automation projects by showing some design patterns. Drop me a line if you have any further questions, or if you have a look at the implementation details!