In the previous article I described the basic of the MQTT communication protocol, now I will discuss the practical use of communication using the Mosquitto broker.
Mosquitto is a lightweight broker that supports the MQTT protocol provided by the Eclipse Foundation under the EPL/EDL license.
Installing a Broker
The following method will install Mosquitto on the Ubuntu/Debian and Raspbian (Raspberry Pi) systems. Start the terminal and invoke the following commands:
sudo apt-get update sudo apt-get upgrade sudo apt-get install mosquitto
when the installation is finished, we can check if our server is working. We can do this by using the command:
systemctl status mosquitto
If you received a message containing a line in the style:
Active: Active (running) since Wed 2018-08-01 16:37:46 CEST; 2s ago
This means that the broker Mosquitto is working properly.
Installing client Programs
When our server is already running, we need clients that will generate the job. Installation in the Debian family is as simple as a broker:
sudo apt install mosquitto-clients
This way we now have two programs available:
- mosquitto_sub – subscribes to Topics
- mosquitto_pub – used to publish messages
Simple communication using MQTT
When we have a ready environment, we can begin this first test. To do this, we need to have open two terminal windows.
In the first window, we call the subscription command:
mosquitto_sub -t myTopic
and the second publication command:
mosquitto_pub -t myTopic -m "message"
When you call the publication command in a terminal window where we have opened a subscription we see our message.
The program -mosquitto_sub is constantly open and listening, and the program mosquitto_pub publishes the message within the subject and closes. The arguments with which the programs are executed means:
- -t [topic] – specifies the name of the topic
- -m [message] – specifies which message is to be published
MQTT communication between different devices
MQTT, of course, allows communication between different devices, the only thing the client application must know is the IP address of the device on which the broker works. For example, I run a Mosquitto server on a Raspberry Pi, which will also be one subscribing client, and I’ll start the publication and subscription for the PC.
A new feature is the subscription command:
mosquitto_sub -h 192.168.1.100 -t myTopic
and the Publish command:
Mosquitto_pub -h 192.168.1.100 -t myTopic -m "message"
Because they run on a different device than the broker is running, we need to provide the IP address of our server. This is used for the -h [IP adres] argumentt.
Summary
As can be seen from the above examples, MQTT is a very simple but powerful tool. The next section will show access control.