Install Mosquitto On Raspberry Pi
- Before installing the MQTT broker, update the operating system first.
sudo apt update
sudo apt full-upgrade
2. The mosquitto MQTT broker is available as part of the Raspbain repository, installing it becomes simple.
sudo apt install mosquitto mosquitto-clients
3. Verify the MQTT broker is running on my Raspberry Pi
sudo systemctl status mosquitto
If the broker running successfully, it will show:
Testing the Mosquitto Installation on the Raspberry Pi
- Start up a subscriber in the terminal. The subscriber is listening to MQTT broker that running on the Raspberry Pi.
- Here, use the Mosquitto client for subscribers that we installed earlier to do this.
- In this example, I connect to localhost and wait for messages from the broker on the “test/device_0”
mosquitto_sub -h localhost -t "test/device_0"
`-h` specifies the hostname.
`-t` argument to tell the subscriber what topic we should listen from.
2. Sending messages from the publisher. Here I use the MQTT publish client.
mosquitto_pub -h localhost -t "mqtt/pimylifeup" -m "Hello world"
Also, I use MQTT Explorer to send and receive test data from and to the MQTT broker.
Type in the host address and the port number to connect.
Config MQTT Broker
Now, everybody can access the MQTT broker and drop any message to the broker once they know the address and the default port. Which is not safe.
For safety consideration, the next step is to create a user and password that only allow the user who has the key to getting in the broker.
- Go to `mosquitto.conf` file to change the setting.
sudo nano /etc/mosquitto/mosquitto.conf
Add these line at the bottom of the .conf file.
password_file /etc/mosquitto/pwfile#Access permission configuration
2. Create pwfile for storing user and password
For creating user and password, activating the server and use
mosquitto_passwd command. For example:
mosquitto_passwd /etc/mosquitto/pwfile tmptest
Then, input the password twice.
3. Change the acl_file
sudo nano /etc/mosquitto/aclfile
4. Run the broker
mosquitto -c /etc/mosquitto/mosquitto.conf -d