System Overview
- Check if the mosquitto broker service is up and running:
systemctl status mosquitto
- If not, install it first:
sudo apt install mosquitto mosquitto-clients
- Setup the client authentication using
mosquitto_passwd -c pwfile username
where username is the username that the MQTT client is going to use. Enter password. You can add additional user/password usingmosquitto_passwd -b pwfile username password
- Move the password file pwfile under
/etc/mosquitto
directory if not yet. - Stop mosquitto service:
sudo systemctl stop mosquitto
- Modify the mosquitto configuration file :
Add the following lines to the file:
sudo nano /etc/mosquitto/mosquitto.conf
allow_anonymous false password_file /etc/mosquitto/pwfile listener 1883
- Restart the mosquitto service:
sudo systemctl restart mosquitto
- You can test if it works by running the command in one ssh terminal:
and the following commend in another ssh terminal:
mosquitto_sub -u username -P password -t Test
Where the username and password should be the ones that you just setup. If successful, the message "This is a test" should display in the mosquitto_sub terminal.mosquitto_pub -u username -P password -t Test -m "This is a test"
- Connect a BME280 to the Raspberry Pi via I2C.
- Install paho-mqtt package by running the command in ssh terminal:
pip install paho-mqtt
- download example code:
wget https://raw.githubusercontent.com/JZ2211/IIoT_wk6/main/mqttpub_bme280.py wget https://raw.githubusercontent.com/JZ2211/IIoT_wk6/main/savedata.py
- Modify the configuration related to the MQTT brokers at the top of the program:
nano mqttpub_bme280.py
- Save the file. Test the mqtt client:
If it runs sucessfully, you should observe a directory named as your hostname is created and files named after the date are saved under the directory.
python mqttpub_bme280.py
- If you want to run the program in background, you can use
crontab -e
to configure.
- Install paho-mqtt by running the command under the Windows Powershell:
pip install paho-mqtt
- Download the example code:
mqttsub_4windows.py
- Modify the HOMEPATH (where you want to save the data to) and the configurations related to the MQTT broker at the top the code.
- Run the python program. If it runs sucessfully, it will save received messaged in files under HOMEPATH.
- Connect a BME280 board to the NodeMCU via I2C.
- Download Arduino IDE if you haven't done so from https://www.arduino.cc/en/software
- Download the example code:
bme280_mqtt.ino
- Open the example file in Arduino IDE. Choose the correct COM port and board NodeMCU 1.0.
- Modify the wifi configuration and also the configurations related to MQTT server at the top of the program.
- Save the file and upload. You can use the serial monitor to observe if the program publish sensor data correctly.