Monday, March 4, 2019

Talking MQTT

This post will be about using MQTT from the command line. Don't be afraid, next post will be instructions on how to do the same thing through the GUI. This post will allow someone to do some troubleshooting if the GUI isn't working, as well as some familiarity with some of the concepts of MQTT.

Before getting started, ensure Mosquitto is installed and running on an agent. For now, it doesn't need to be on the final server, it can be on any supported platform. There is no need even for another node. If running on a Linux system including Raspberry PI be sure to install both the server/agent as well as the clients:

sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients

Once mosquitto is running, then it will be necessary to have two windows connected to the server, where commands can be entered. In one window, enter the command "mosquitto_sub" to subscribe to a topic using the local agent:

pi@raspberrypi:~ $ mosquitto_sub -h localhost -t test

In the other window, enter "mosquitto_pub" to publish a message to that topic:

pi@raspberrypi:~ $ mosquitto_pub -h localhost -t test -m "hello world"

The "-t" option to both "mosquitto_sub" and "mosquitto_pub" indicates the topic the message will be published to. The "-h" option to both is the agent that will handle the messages for the topic, and can be the host name, or the ip address. The mosquitto_pub has a "-m" option for setting the payload of the message that will be published. The mosquitto_sub will just output the payload to stdout. The two windows look something like:


Multiple windows can be opened to be subscribers. When the pub message is sent, they all will receive identical copies of the payload:


If there are nodes, payloads can be sent to them as well. The server/agent host (-h option) must be the same server/agent that the node is attached to. An example, the alarm sounder from the last post can be turned on using the mostuitto_pub application. The topics it is subscribed to are "alarm/light" for the LED, and "home/alarm" for the tone generator.

 pi@raspberrypi:~ $ mosquitto_pub -h localhost -t alarm/light -m "on"

or 

pi@raspberrypi:~ $ mosquitto_pub -h localhost -t home/alarm -m "off"

Using a simple topic/payload combination many items can be controlled. The next post will be the beginning of using Node-Red, a GUI for these commands. 


Stay tuned...

No comments:

Post a Comment