MQTT on the Raspberry Pi

The first step ist o get MQTT up and running on a Raspberry Pi to handle the data queues.

I'm just going to hit the basics  here, but check out for tons of additional information!

There are three steps to getting MQTT running on your Raspberry Pi:

  1. Install the software
  2. Configure the daemon
  3. Test the configuration

Step 1 - Install the software

The software is available through Raspbian's software distribution system, which makes it easy. First, be sure your system is up to date.

Download: file
sudo apt-get update
sudo apt-get upgrade

Next, install the Mosquitto packages you'll need.

Download: file
sudo apt-get install mosquitto mosquitto-clients mosquitto-dbg python-mosquitto python3-mosquitto

This will install all the components you will need to use a local instance of MQTT for this project.

Step 2 - Configure the daemon

 The MQTT software (Mosquitto) is controlled by a configuration file: /etc/mosquitto/conf.d/mosquitto.conf Please note that I am running this on a closed and encrypted network in my house, which is maintained separately from the kids' and guest networks. It is not appropriate to use this configuration on an MQTT broker that is exposed to the Internet.

Do not use this configuration for a broker that is exposed to outside networks like the Internet! It is insecure!!!!

Here is my copy of the mosquitto.conf file:

Download: file
# Config file for mosquitto
# See mosquitto.conf(5) for more information.

user mosquitto
max_queued_messages 200
message_size_limit 0
allow_zero_length_clientid true
allow_duplicate_messages false

listener 1883
autosave_interval 900
autosave_on_changes false
persistence true
persistence_file mosquitto.db
allow_anonymous true
password_file /etc/mosquitto/passwd

Once you have created the configuration file, you must stop and restart the process (called a daemon) that controls MQTT. You do that with the following two commands:

Download: file
sudo systemctl stop mosquitto.service
sudo systemctl start mosquitto.service

Step 3 - Test the configuration

Now you're ready to test the MQTT system. On the same machine as MQTT/Mosquitto is running, execute this command: 

Download: file
mosquitto_sub -v -t '\$SYS/#'

This should produce a stream of diagnostic data. The contents aren't important (unless you're curious about MQTT's internals), what's important is that they show up. Once you confirm that the daemon is running, use CTRL-C to exit the program. Then we're ready to start building hardware.

This guide was first published on Aug 20, 2016. It was last updated on Aug 20, 2016. This page (MQTT on the Raspberry Pi) was last updated on Jun 26, 2019.