What is MQTT?
In the last blog, we discussed what MQTT is, how it works, and how it was developed. We also discussed the components of MQTT.
MQTT BROKER LOCALLY ON RASPBERRY PI
In this blog, we will be installing the MQTT broker in Raspberry pi and use it locally. This is the cheapest broker you can have. You can use Raspberry pi 4 or Raspberry pi zero, which is affordable yet powerful. As we discussed in the last blog, a broker is the central part of the MQTT network, which is responsible for receiving all the messages and then forward the messages to the subscribed devices. The broker is also responsible for deciding which message to send to which devices, as it already has the information of devices, i.e., devices have already subscribed to different topics.
Mosquitto MQTT Broker
We will be installing the Mosquitto broker, which is an open-source message broker that implements the MQTT protocol versions 5.0 and 3.1.
Before starting, you will need to boot SD card to Raspbian OS and plug the card in Raspberry Pi and boot it.
Install Mosquitto Broker on Raspberry pi
After booting it up, open terminal and type,
sudo apt-get update
that will update your Raspberry pi and then type,
sudo apt install -y mosquitto mosquitto-clients
Now to make it run automatically on boot. Type,
sudo systemctl enable mosquitto.service
We are good to go now; you can check the installation by typing.
it will return the version of the broker installed on your Pi.
Let’s run the mosquitto service on background by typing,
Now we can test the broker by subscribing to a topic so we will open a terminal window and type,
mosquitto_sub -d -t Highvoltages
“Highvoltages” is a topic, so now let’s publish something on a topic, we will open another shell window and type,
mosquitto_pub -d -t Highvoltages -m "Hello world!"
and you will see the message in the first window.
Secure MQTT broker
So it works, now let’s make our broker protected by giving a username and password.
We can set the user name and password by typing,
mosquitto_passwd -c passwordfile pi
and it will ask us for the password. We can enter the password for user pi, and it will be protected. Now let’s check our broker from our laptop. Make sure pi and pc are on the same network. Get the pi IP first by typing if config and download the MQTT explorer.