Introduction
I needed to use MQTT for work and researched Mosquitto, which allows easy handling of MQTT. Although many have already documented Mosquitto installation, the methods differ slightly between Mac and Raspberry Pi, leading to some confusion. This article serves as my personal reference. Note that I won't delve into what MQTT is—please look it up if needed.
Installing Mosquitto
For Mac
You can install it using Homebrew.
brew install mosquitto
The software is installed in the following paths:
- mosquitto (broker): /usr/local/opt/mosquitto/sbin
- mosquitto_sub (for subscription): /usr/local/opt/mosquitto/bin
- mosquitto_pub (for publishing): /usr/local/opt/mosquitto/bin
Be sure to add these paths to your environment variable Path.
For Raspberry Pi
For Raspberry Pi or Linux, you can install Mosquitto with the following commands:
# Install Mosquitto (Broker).
sudo apt-get install mosquitto
# Install Mosquitto clients.
sudo apt-get install mosquitto-clients
Starting the Broker
The broker acts as a server that mediates MQTT communication. Typically, cloud services like AWS IoT are used, but for testing purposes, we will start the broker on either Mac or Raspberry Pi. You only need one broker running, so there's no need to start both simultaneously. Also, note the IP address of the broker terminal for the next testing step.
For Mac
Start Mosquitto's broker with the following command:
mosquitto
For Raspberry Pi
Start Mosquitto's broker with the following command:
sudo service mosquitto status
Testing
When you install Mosquitto using the steps above, it also installs simple clients for subscribing and publishing. We will use these clients for testing. Here’s the setup:
- Broker IP address: 192.168.11.18
- Topic name: tp1/test
- Message to publish: Hello
Open the terminal on the subscription terminal and subscribe to the topic with the command below. The subscription terminal can be on the same device as the broker.
mosquitto_sub -h 192.168.11.18 -t tp1/test
Open the terminal on the publishing terminal and publish a message to the topic with the command below. Again, the publishing terminal can be the same as the broker terminal.
mosquitto_pub -h 192.168.11.18 -t tp1/test -m Hello
If the message 'Hello' appears on the subscription terminal, the test is successful.
Conclusion
Using Mosquitto, we can easily set up an MQTT environment for testing.
Top comments (0)