How to Install Mosquitto Broker on Raspberry Pi

Introduction 

This post explains how to install the open-source message broker, mosquitto, on Raspberry Pi. The broker is the central body that is responsible for receiving all messages, filtering the messages, decide who is communicating with it and then publishing the message to all subscribed clients. 

You will need:
  • Raspberry Pi board
  • MicroSD Card – 16GB Class10
  • Raspberry Pi Power Supply (5V 2.5A)
Installing Mosquitto Broker on

 
 
pi@raspberry:~ $ sudo apt update
then we need to install the mosquitto and mosquitton client
pi@raspberry:~ $ sudo apt install -y mosquitto mosquitto-clients
pi@raspberry:~ $ sudo systemctl enable mosquitto.service
pi@raspberry:~ $ mosquitto -v
 
There are several brokers we can use instead of Raspberry Pi. I’ll make a separate blog on that, but now we’re installing the Mosquitto Broker installed on a Raspberry Pi.
 
Open Raspberry Pi terminal window

To install the Mosquitto Broker you need to update the raspberry pi first

Note: “-y” is for “yes” that automatically approves your installation otherwise you need to manually type “Y” (for manual approval) if we remove -y from our command.

Then we need to enable the mosquitto service

After the installation, we need to check the version of Mosquitto client

Note: sometimes command mosquitto -v show you message saying “Error: Address already in use“. That warning message means that your Mosquitto Broker is already running, so don’t worry about that. Just execute the following command

pi@raspberry:~ $ sudo systemctl restart mosquitto.service

pi@raspberry:~ $ sudo systemctl status mosquitto.service

You’ll get output like <active> in green color | then type “ctrl+c” to cancel

Run Mosquitto on the background as a daemon:

pi@raspberry:~ $ mosquitto -d

To subscribe to an MQTT topic with Mosquitto Client open a terminal and run

pi@raspberry:~ $ mosquitto_sub -d -t topic1

Note : “-t” = Topic name

And now open another terminal to send some packets to “Topic1”

Now we have to send the message from “Terminal 2” to “topic1 of Terminal 1” by executing the command

pi@raspberry:~ $ mosquitto_pub -d -t topic1 -m “Hello world!”

Here Terminal 2 works as a client are subscribed to Topic1 topic, receive “Hello world!” message, which is published by Terminal 2 to Terminal 1.

This is how MQTT works and this is how your devices (for example ESP8266/ESP32) could be subscribed to the same topic to receive messages or a device could publish messages to multiple devices. In the next blog, we’ll add a user into MQTT-server or broker and send our messages in a more secure way which includes username and password, then we can able to send the message to our broker from outside the network. Along with it, we’ll try to understand how to build our IoT architecture according to the different-different scenario.