This tutorial will show you what is Mosquitto MQTT Broker and how to install it on Raspberry Pi.
Contents
- What is MQTT?
- Installing Mosquitto MQTT on Raspberry Pi
- Creating an MQTT Broker on Raspberry Pi
- Sample Project
- Further Scope
What is MQTT?
MQTT stands for Message Queuing Telemetry Transport. It is a simple and lightweight protocol that works on the publish-subscribe principle. and transports messages between devices. It is based on TCP/IP, however, any network protocol that provides bi-directional, lossless, and ordered connections can support MQTT. This protocol is highly useful when the network bandwidth is limited or when low-power sensors are used.
To understand the publish/subscribe or the “pub/sub” principle better, let us take an example of a news website or app. The website acts as the “broker”, meaning that it it contains information about various “topics”, in this case, news articles. A client can subscribe to specific topics and will get information when anything related to the subscribed topics is “published”. The news agencies,in this case, will be the publishers. MQTT does not provide any hierarchy between publishers and subscribers. A client can both be a publisher and a subscriber. The publishers and subscribers use messages to communicate with one another. Every message is routed through the broker.
For this tutorial, we shall use the Mosquitto MQTT broker.
Installing Mosquitto MQTT on Raspberry Pi
First update the operating system on your Raspberry Pi:
sudo apt-get update
sudo apt-get upgrade
sudo reboot
Now, open a terminal and type the following command:
sudo apt install -y mosquitto mosquitto-clients
You can test your installation using the following command:
mosquitto -v
This will return the version of Mosquitto MQTT installed on your Raspberry Pi.
For the rest of this tutorial, you shall need the IP address of your Raspberry Pi. Type the following command and note down the IP address:
hostname -I
Creating an MQTT Broker on Raspberry Pi
The easiest way to understand this protocol is to create a broker on Raspberry Pi and use it to publish and subscribe to topics. Mosquitto MQTT provides a layer of security that authorizes only specific clients to publish or subscribe to topics. For this, we need to set up a username and password. This step is optional, however, it is recommended to use it in all your projects.
Type the following command:
sudo nano /etc/mosquitto/mosquitto.conf
The last line in the file will be:
include_dir /etc/mosquitto/conf.d
Remove this line and add the following lines at the end of the file:
allow_anonymous false
password_file /etc/mosquitto/pwfile
listener 1883
The above three lines will tell the broker, listening on port 1883, to prevent any communications from devices that do not have a valid username and password.
The above step is optional. Hence, to proceed without adding a username and password, remove the first two lines and directly go to the rebooting part.
sudo mosquitto_passwd -c /etc/mosquitto/pwfile username
Type the above command in a terminal window. Replace “username” with your username. You will be prompted to enter a password. Type a password and press Enter.
Finally, reboot the Pi for the changes to take effect.
sudo reboot
Subscribe to a Topic
Open a terminal and type the following command:
mosquitto_sub -d -u username -P password -t Test
In the command, replace username and password with the username and password you created before. In case that step was skipped, just type the following command:
mosquitto_sub -d -t Test
We have successfully subscribed to our Test topic. Now we have to publish a message to this topic.
Publish a message to a Topic
To publish a message to a topic, type the following command:
mosquitto_pub -d -u username -P password -t Test -m "Hello, World!"
Replace username and password with you username and password. In case that step was skipped, simply type the following command:
mosquitto_pub -d -t Test -m "Hello, World!"
Once the above message was published, the message is received by the subscriber as can be seen in the above image.
Congratulations, we have created a MQTT broker on Raspberry Pi and published/subscribed a topic.
Sample Project
Taking our knowledge further, let us use a NodeMCU device that publishes the reading from a LDR to Raspberry Pi.
Components Required
- Raspberry Pi (I have used a Model 4 B)
- NodeMCU 1.0 (ESP-12E Module)
- 1x LDR (Light Dependent Resistor)
- 1x 10K resistor
- Jumper Wires
Background
Check out our earlier post on NodeMCU here. We need to install the PubSubClient library. Download the zip file of the library from here. To set up NodeMCU with the Arduino IDE and install the downloaded library, check out my earlier post.
We are going to connect an LDR to the NodeMCU. The NodeMCU will publish the sensor reading to our Raspberry Pi broker. The Username and Password created above will be used in this project as well. We shall then subscribe to the topic using Raspberry Pi and hence, will be able to see the sensor reading.
Circuit Diagram
Once the circuit is rigged up, we can proceed to the code.
NodeMCU Code
Open an Arduino IDE and create a new file. Paste the following code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "YOUR_SSID"; // enter your WiFi SSID
const char* wifi_password = "YOUR_PASSWORD"; // enter your WiFi password
// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "Raspberry Pi IP Adress";
const char* mqtt_topic = "MQTT_Tutorial"; //any topic name of your choice
const char* mqtt_username = ""; //type your mosquitto mqtt username
const char* mqtt_password = ""; //type your mosquitto mqtt password
// The client id identifies the NodeMCU
const char* clientID = "ID"; // any name that identifies the client
// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker
int photo=A0; //analog pin of the NodeMCU
void setup() {
pinMode(photo, INPUT);
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
// Connect to the WiFi
WiFi.begin(ssid, wifi_password);
// Wait until the connection has been confirmed before continuing
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Debugging - Output the IP Address of the NodeMCU
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer("Raspberry Pi IP Address", 1883); // type your Raspberyry Pi IP address
// Connect to MQTT Broker
// client.connect returns a boolean value to let us know if the connection was successful.
// If the connection is failing, make sure you are using the correct MQTT Username and Password
if (client.connect(clientID, mqtt_username, mqtt_password)) {
Serial.println("Connected to MQTT Broker!");
}
else {
Serial.println("Connection to MQTT Broker failed...");
}
}
void loop() {
int val=analogRead(photo)/4;
char buf [4];
sprintf (buf, "%03i", val);
unsigned int p=4;
client.connect(clientID, mqtt_username, mqtt_password); //connects to the broker
//delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
client.publish(mqtt_topic,(const uint8_t*)buf,4);
delay(500); //delay between each message
}
Appropriate comments have been included in the code itself. After entering all the required credentials in the spaces shown in the code, compile, and run the code. You should see the following output in the Serial Monitor:
Raspberry Pi Broker/Subscriber
Now it is time to subscribe to the topic using Raspberry Pi. Keep the publish code on the NodeMCU running. Open a terminal on the Raspberry Pi and type the following comand:
mosquitto_sub -d -u username -P password -t MQTT_Tutorial
Replace username and password with the ones created earlier in the tutorial.
You should see the sensor value in the terminal.
The above tutorial shows how we can use NodeMCU to publish sensor values to a particular topic. We use Raspberry Pi as both broker and subscriber to the topic in which the sensor values are published.
Further Scope
MQTT is a simple protocol and can be used for a variety of low power sensors. We can build a simple home automation system using Mosquitto MQTT, NodeMCU, a few sensors, and Raspberry Pi as the broker. Using this system, we can monitor sensor values around the house such as temperature, humidity, ambient light (LDR), and many others. If you don’t have a NodeMCU, check out my previous post on building a home automation system using Raspberry Pi and Flask.
Thank you for checking out this tutorial and stay tuned for many more such tutorials.
Happy learning!