Building a next-gen IoT sensor network
Les Pounder introduces us to a lightweight messaging protocol that can be used to send data anywhere around the world.
Amature IoT ecosystem requires standards. Enter MQTT, a machine-to-machine application platform. Using a Publisher/Subscriber model, data can be sent from a Publisher using topics and filtered with subjects by the Subscriber, which can then react in a predictable manner.
We’re going to build a MQTT network. The Publisher, a Pi Zero W, will send temperature data over the MQTT network, where a Subscriber, another Pi Zero W, will react by changing the colour of LEDs on a Blinkt board.
Our hardware setup is split between the two Pi Zero W boards. The Publisher board has a DS18B20 temperature sensor connected to it as per the project diagram. Once connected, boot up the Publisher Pi to the Pixel desktop and from the main menu go to Preferences and then click on Raspberry Pi Configuration to load the application. Once opened, click on the Interfaces tab and enable the 1-Wire: interface before rebooting the Pi. We have now successfully enabled the interface for our DS18B20 temperature sensor.
The Subscriber board simply has a Pimoroni Blinkt LED board attached to the GPIO.
We start by setting up the Raspberry Pi that will act as a Broker between the Publisher and Subscriber. Open a terminal and install the Mosquitto (MQTT) service: $ sudo apt update && sudo apt install mosquitto mosquittoclients Also make a note of the Broker IP address using. $ hostname -I
The Publisher is the Pi Zero W sending the data collected via the DS18B20 temperature sensor attached to the GPIO to the Subscriber Pi Zero W.
Open a terminal and update the list of software packages then download the Python library that will enable the sensor to communicate using Python. Lastly we install the MQTT library for Python 3: $ sudo apt update $ sudo apt install python3-w1thermsensor $ sudo pip3 install paho-mqtt
Once installed we can now move on to writing the Python 3 code for this project. For this we shall use Python 3 Editor, found in the Programming menu. Once the editor opens, immediately click on File > New to create a blank document. Next click on File > Save and call the file MQTT-Publish.py.
Start by importing the libraries, our first is the time library, for controlling the duration between sensor readings. Next is the MQTT library, followed by the DS18B20 sensor library.
import time import paho.mqtt.client as mqtt from w1thermsensor import W1ThermSensor We next create two variables that will be used as objects for our sensor and for connecting to MQTT. sensor = W1ThermSensor() client = mqtt.Client()
Our next line of code connects the Publisher to our Broker Pi. Use the Broker IP address that you recorded earlier. We also need to specify the port the data will be sent to and lastly the duration to keep the connection alive, this is in seconds. client.connect("BROKER IP ADDRESS”, 1883, 60)
Use a while True: loop to get the current temperature using the sensor, then save it as a variable. We called it hall as the sensor was in the hallway. We then publish the data using MQTT, publishing the data to the topic temp and then passing the temp variable containing the temperature data. We then print the data to the shell, this is for debug purposes. Lastly we sleep for ten seconds before the loop repeats. In real use this sleep would be for far longer. while True: temp = sensor.get_temperature()
hall = temp client.publish("temp”,hall) print(hall) time.sleep(10)
With the code completed, remember to save your work and then click Run > Run Module. The data will now be sent to the MQTT Broker, as well as being printed to the Python shell to show that the code is working.
Our final piece is the Subscriber, the device(s) that are listening to a certain topic. Our Subscriber is another Pi Zero W with the Blinkt LED board attached. We use Blinkt to show the temperature of our hall using the eight LEDs on the board.
We start configuring the Subscriber Pi by first opening a terminal and installing the MQTT library for Python: $ sudo pip3 install paho-mqtt
Next we run the Blinkt installer script, created by the Pimoroni team, which automates installing the library and examples to illustrate the boards abilities. In a terminal type: $ curl -sS https://get.pimoroni.com/blinkt | bash
Follow the script and after a short while your Subscriber Pi will have the Blinkt library and examples installed.
Now for the Python 3 code for this project. Create a new file and call it MQTT-Subscriber.py. Importing the libraries for the Subscriber, we start with the MQTT library and then import a handful of functions from the Blinkt library, namely setting the pixel colour, the brightness, showing changes, clearing the pixels and changing the colour of every pixel. import paho.mqtt.client as mqtt from blinkt import set_pixel, set_brightness, show, clear, set_all Set the brightness for the Blinkt LEDs to 0.1, and on the next line we then ensure that all of the LEDs are turned off. set_brightness(0.1) clear()
Create a function that will handle the Subscriber connecting to the MQTT Broker. The function requires arguments to be passed, chiefly the IP address of the Broker, the port to connect to and the amount of time to wait for a connection. The function will also print the result code depending on if we successfully connect to the Broker. It will then subscribe to the topic “temp”. def on_connect(client, userdata, flags, rc): print("Connected with result code “+str(rc)) client.subscribe("temp") Our next function handles the messages sent to the
Subscriber via MQTT. It creates a variable called message that converts the message into a string. We then slice the string so that we remove any unneeded information, then the message is converted to a float before it is printed to the Python shell for debug purposes. def on_message(client, userdata, msg): message = str(msg.payload) message = message[2:(len(message)-1)] message = float(message) print(message)
Use an if, else if conditional test to check the contents of the message variable. The first test is to see if the temperature in message is less than 10°C and greater than or equal to 0°C, then print a debug message to the shell. Then we set all of the LEDS to blue, using the RGB value (0,0,255) to only turn on the blue part of the LEDs. We then have to call the show() function in order to see the changes. if message < 10.0 and message >= 0.0: print("The hall is cold") clear() set_all(0,0,255) show()
Create an object called client which shortens the MQTT library reference. When we connect, run the on_connect function, and then the on_message function . We then connect to the IP address of our MQTT Broker, specifying the port and the connection wait time. Lastly we instruct the MQTT client to constantly look the code waiting for a message to arrive. Save the code and click on Run > Run Module. You should see the LEDs of the Blinkt react to the data that is being sent over MQTT.
Congratulations you can now send and act on data over a network using MQTT. LXF