MQTT is the protocol of choice for M2M (Machine to Machine) and IoT (Internet of Things) applications. However, when it comes to choosing an MQTT broker, people most often turn to cloud-based brokers. A local MQTT broker can offer many advantages over cloud-based ones, such as security, flexibility, reliability, low latency, cost-effectiveness and better QoS implementation.
Mosquitto is an open-source iot.eclipse.org project. It implements versions 3.1 and 3.1.1 of the MQTT protocol. For more details, see http://mosquitto.org/.
Raspberry Pi:
The Raspberry Pi is a single-board computer developed by the Raspberry Pi Foundation. For more details, see https://www.raspberrypi.org/
Mosquitto on Raspberry Pi:
The Raspberry Pi has enough computing power to run Mosquitto and act as a personal MQTT broker capable of meeting most of our personal MQTT needs. So let’s go ahead and walk through the installation, testing and uninstallation process.
What you need:
- A Raspberry Pi running the Raspbian operating system
- An Ethernet or Wi-Fi connection to the internet
Installing Mosquitto (MQTT Broker):
log in to the Raspberry Pi via SSH and create a new directory for temporary files
mkdir mosquittocd mosquitto
Import the repository package signing key
wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.keysudo apt-key add mosquitto-repo.gpg.key
Make the repository available to apt
cd /etc/apt/sources.list.d/sudo wget http://repo.mosquitto.org/debian/mosquitto-stretch.list
Installing the Mosquitto MQTT Broker
sudo apt-get install mosquitto
Check the status of the Mosquitto service, the process and the default port (1883)
service mosquitto statusps -ef | grep mosqnetstat -tln | grep 1883
if the Mosquitto service is running and listening on TCP port 1883, you have a working MQTT broker.
Testing the Mosquitto MQTT broker with an MQTT client
You can use any MQTT client for testing. However, if Python 2.7 is installed on your computer, you can try it with the following sample Python scripts. To run these scripts, the Paho MQTT client must be installed on your computer. You can install it with pip
pip install paho-mqtt
Once the Paho client library is installed, you can download and run the following Python scripts (don’t forget to change the “MQTT_BROKER” IP address)
Uninstalling the Mosquitto MQTT Broker:
To uninstall Mosquitto, you can use the following commands:
sudo apt-get purge mosquitto
If, on the other hand, you want to remove Mosquitto completely along with all its associated configuration, use the following command:
sudo apt-get --purge remove mosquitto
Enjoy!
