MQTT (Message Queuing Telemetry Transport) is a messaging protocol that works on the principle of subscription / publication which was originally developed to simplify communication between machines and which is now an international standard for communication between machines (M2M) and objects (IoT). To save the battery of mobile devices as much as possible. MQTT consumes 11 times less energy to send messages and 170 times less to receive than the HTTP protocol. MQTT is also 93 times faster than the HTTP protocol.

For this to work, it requires a server/broker.

The command to install Mosquitto on Linux is

sudo apt install mosquitto

Installing a client can also be very useful for testing purpose. These tests will be done with the command mosquitto_sub or mosquitto_pub

sudo apt install mosquitto-clients

Let´s check that the server/broker is responding well … with the command:

systemctl status mosquitto

The service can be restarted with the command :

sudo systemctl restart mosquitto

You can view the Broker-configuration file with :

more /etc/mosquitto/mosquitto.conf

You will notice that you are asked to place your configuration files in /etc/mosquitto/conf.d/

We can therefore create one with nano. We will name it for example default.conf with the command :

sudo nano /etc/mosquitto/conf.d/default.conf

As an option, you can make it necessary to have a login/password to be able to connect to Mosquitto. Let´s create one like this :

sudo mosquitto_passwd -c /etc/mosquitto/passwd NOM_UTILISATEUR

// Then, you will be asked for your password twice, enter that too.

And declare it in the personal conf file, ie here in /etc/mosquitto/conf.d/default.conf

allow_anonymous false
password_file /etc/mosquitto/passwd

You can see the logs with the command :

tail -f /var/log/mosquitto/mosquitto.log

If you have activated the firewall on your Linux, consider authorizing port 1883 with a command like :

#Autoriser le port 1883 en entrée pour Mosquitto
iptables -t filter -A INPUT -p tcp --dport 1883 -j LOGACCEPT
echo "Mosquitto ok"

MOSQUITTO – TEST

We can test if the sending of messages works properly by launching 2 ssh terminals.
On the first, create a subscriber with a command like below.
(If you have not created a user to secure access to Mosquitto, it is not necessary to fill in the -u and -P options)

mosquitto_sub -h localhost -u votreuser -P lepassword -t topic/test

In another ssh session, create a publisher and a test message with a command like this:

mosquitto_pub -h localhost -u votreuser -P lepassword -t topic/test -m "Voici un test"

The first session with the subscriber must receive the message of the second

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *