Tooling Tuesday: MQTT PDQ
Message Query Telemetry Transport, explained Pretty Darn Quick!
MQTT is remarkable. We can send messages / data over any form of connection, even old GPRS / 2G mobile signals. It works across many platforms, and it is super simple to understand.
I've covered MQTT before, but only briefly, and right at the start of my journey with it.
So how does MQTT work?
Think of the MQTT flow like this.
A publisher (content creator) wants to publish a message (video) so they do this via an MQTT broker (YouTube). Then people who are looking for that message (video) subscribe to their channel and receive updates when a new video is released.
Dave Jones @waveform80 explained MQTT to a group of kids using this example. Thanks Dave!
So how can I use MQTT?
The quickest way is via the terminal, in my case via Ubuntu.
sudo apt install mosquitto mosquitto-clients
So who is the broker?
You can run your own MQTT broker, but for the purposes of this post we shall use a public broker at hivemq.com
As this is a public broker, your messages will be public and and that means anyone can see them! So don't be sending secret / sensitive information!
Subscribe to a topic
Topics are how messages are separated. For example On YouTube I can subscribe to videos on Electronics, RetroGaming etc. These are like topics. In MQTT I can subscribe to a topic on a server as follows.
mosquitto_sub -d -t blogpost -h broker.hivemq.com
mosquitto_sub
is the command to subscribe.
-d
is debug mode, where all the output is printed to the terminal, handy for finding issues.
-t
the topic to subscribe to, in this case blogpost.
-h
The broker who passes messages from publisher to subscriber. In this case broker.hivemq.com.
Running this command I see this output.
Publish to a topic
The syntax is similar to subscribing.
mosquitto_pub -d -t blogpost -h broker.hivemq.com -m "MESSAGE HERE"
mosquitto_pub
is the command to publish.
-d
is debug mode, where all the output is printed to the terminal, handy for finding issues.
-t
the topic to subscribe to, in this case blogpost.
-h
The broker who passes messages from publisher to subscriber. In this case broker.hivemq.com.
-m
The message to send.
So can I use MQTT with other platforms?
Sure you can!
Here is a quick demo where I send a message using MQTT with Node-RED. I then see this message in the debug tab of Node-RED. I can also see the message in the terminal which is set to subscribe to the same topic.
MQTT is really handy!
I've used MQTT for a few years now and it still offers great features. I've used it with a group of kids who built an IoT fairground where rides, sounds and lights were triggered using MQTT messages.