In this post are we going to talk a bit about MQTT and give you a quick example of how you can publish a simple message to a MQTT-Broker from a simple computer system (here: an Orange Pi Zero).
MQTT is a light-weight messaging protocol that resides on top of the TCP/IP protocol.
MQTT stands for Message Queue Telemetry Transport.
MQTT does not require much bandwidth and this “lightweight” protocol is also rather energy efficient which is a big plus!
MQTT is an event-driven publish/subscribe architecture. And the whole communication is driven by the MQTT Broker.
The MQTT Broker is in charge of receiving and dispatching the messages between the senders and the rightful receivers.
The different receivers all subscribe to different topics, and the Broker relay messages published on that topic to the correct receivers.
To show you a simple example, we need both a Broker and a two clients.
We are going to implement BOTH the Broker AND one of the clients on the same Orange PI Zero. It’s first filled with armbian, before the open source MQTT Broker Mosquitto is installed. And Paho is installed to make it simple to make a MQTT client in Python.
In the end we made a simple MQTT client that sends messages in to the Broker (that resides on the same IP). We did also use the MQTT Client MQTT.fx to look at what is happening.
Through SSH against the Orange PI we installed all the necessary tools for this test:
root@orangepizero:~# apt-get update && apt-get upgrade root@orangepizero:~# apt-get install mosquitto python3-pip root@orangepizero:~# pip3 install paho-mqtt root@orangepizero:~# reboot
After everything necessary was installed we checked that Mosquitto was active by running:
root@orangepizero:~# systemctl status mosquitto
Note that it uses port 1883 by default!
After this was done, we created a simple python program that published the CPU temperature to the topic “myTemperature”.
#!/usr/bin/env python3 import subprocess import paho.mqtt.client as mqtt from time import sleep client = mqtt.Client() # Connect to the MQTT Broker! client.connect("localhost",1883,60) for x in range(0,10): #get CPU temperature by calling a shell command and storing the result temp = subprocess.check_output("cat sys/devices/virtual/thermal/thermal_zone0/temp", shell=True) client.publish("myTemperature",temp) sleep(1) client.disconnect()
We started our external client (MQTT.fx) and subscribed to the topic
myTemperature after we had connected to our MQTT Broker.
After the client was started and subscribed to the topic
myTemperature, we started the publisher by running
python3 file.py in a the shell on the Orange Pi.
This showed us that the python client published data on the topic “myTemperature” to the Broker. Then did the Broker relay the message to the subscriber which was the MQTT.fx client.
Now everybody that subscribe to the “myTemperature”-topic will get this data!
We will continue down this MQTT path in close future so stay tuned for the next post =)