Raspberry Pi

Summary

This is a very short introduction to setup MQTT using Mosquitto, on a Raspberry Pi. We have a more detailed manual found here: MQTT on Raspberry Pi. The ambition of this document is to simplify the setup with ready made components and quickly build up an IoT Raspberry Pi Device (this guide however works stand-alone as well).

Mosquitto Installation

  • Mosquitto is an MQTT Broker listening to publisher events. Consequently, events are gathered in topic trees and served to Subscribers.

MQTT on the network

Installing core components

  • SSH into the server gateway
  • Install the broker
sudo apt install mosquitto
  • Install the clients for mosquitto
sudo apt install mosquitto-clients

Testing Functionality

Open another (second) SSH session: those will be called SSH1 / SSH2 respectively. SSH1 will be used as subscriber, SSH2 as publisher

  • [SSH1]: set subscriber to listen to topic test/topic1
mosquitto_sub -d -t test/topic1
  • [SSH2]: send publisher message to the same topic test/topic1
mosquitto_pub -d -t test/topic1 -m "message sent"
  • Validate the message is received in [SSH1]

For some more testing, you might want to send content to several topics. If you want to subscribe to several topics at once (in your [SSH1] terminal session), you can use MQTT wildcards. There are basically only two: # and +. You can learn more in MQTT documentation, but basically you either subscribe to all subtopics with #, or substitute a topic tree with +.

Assuming we publish on the following topics:

a/b/c/d
a/b/c/e
a/x/c/d
a/x/c/e

The subscription below selects all topics

mosquitto_sub -d -t a/#

The subscription below

mosquitto_sub -d -t a/b/#

selects these topics

a/b/c/d
a/b/c/e

And the subscription

mosquitto_sub -d -t a/+/c/d

selects these topics

a/b/c/d
a/x/c/d

Notes

  • Only the server component needs to install the mosquitto broker. Clients only need the clients component

  • For many projects, please also install paho MQTT components. They are typically used for their Python libraries, from within code. You need PIP for this, so the instructions below setup both.

sudo apt install python-pip
sudo pip install paho-mqtt

If you wish to run the paho components on Python3 (recommended), use the following instead:

sudo apt install python3-pip
sudo pip3 install paho-mqtt