Worksheet 3 - Experimenting with Mosquitto and MQTT

From Sensors in Schools
Jump to navigation Jump to search

MQTT on a Raspberry Pi

An MQTT broker is a central server that facilitates the communication between devices using the MQTT (Message Queuing Telemetry Transport) protocol. The broker manages the message traffic by receiving data (messages) from publishers and routing it to subscribers who have subscribed to specific topics. It ensures that messages are delivered in a lightweight, efficient manner, making it ideal for IoT systems where bandwidth and power consumption are limited.


1. Update Your Raspberry Pi

Before setting up the broker, it’s essential to ensure your Raspberry Pi is updated:

sudo apt update
sudo apt full-upgrade -y


2. Install Mosquitto (MQTT Broker)

Mosquitto is one of the most widely used MQTT brokers, and it’s available in the default Raspbian repository. Install both Mosquitto (the broker) and Mosquitto clients (tools for testing):

sudo apt install mosquitto mosquitto-clients

Configure Mosquitto

When using Mosquitto on a Raspberry Pi, it is often necessary to modify the /etc/mosquitto/mosquitto.conf file to allow for proper operation, especially if you're setting up a public broker or communicating with external devices.


Open the Configuration File: First, open the mosquitto.conf file using a text editor like nano:

sudo nano /etc/mosquitto/mosquitto.conf


Add the Listener: By default, Mosquitto listens on port 1883 for MQTT traffic. You may need to explicitly define this in the configuration file:

Allow Anonymous Connections: If you’re setting up a simple local broker for testing and don’t want to deal with authentication, you can allow anonymous connections.

listener 1883
allow_anonymous true

3. Start and Enable Mosquitto

After installation, you need to start the Mosquitto service and enable it to start automatically on boot:

sudo systemctl start mosquitto
sudo systemctl enable mosquitto

4. Verify the Installation

To ensure that Mosquitto is running, you can check its status:

sudo systemctl status mosquitto


You should see an output indicating that Mosquitto is active and running.

5. Test the MQTT Broker

You can test the broker using the Mosquitto clients. Open two terminal windows:

In Terminal 1 (Subscriber): Subscribe to a topic called "test/topic" using the following command:

mosquitto_sub -h localhost -t "test/topic"

In Terminal 2 (Publisher): Publish a message to the topic "test/topic":

mosquitto_pub -h localhost -t "test/topic" -m "Hello from MQTT"

You should see the message appear in the subscriber terminal.