ขั้นตอนการติดตั้ง MQTT และการตั้งค่า
(บทความนี้ใช้ user root ในการเขียนบทความ จึงไม่ได้ใช้คำสั่ง sudo)
- เปิด port TCP:1883
- install Mosquitto Broker
apt install mosquitto
- Install the Clients and Test
apt install mosquitto-clients
- ทดสอบการทำงานของ MQTT (mosquitto) ด้วยการเปิด terminal 2 หน้าต่าง โดยหน้าต่างแรกทำหน้าที่ subscribe (คอยรับข้อความ) และอีกหน้าต่างทำหน้าที่ publish (ส่งข้อความ)
4.1 subscribe topic เช่น PM25mosquitto_sub -t "PM25"
4.2 publish topic PM25 ด้วยข้อความ “PM2.5 value is 10”mosquitto_pub -t "PM25" -m "PM2.5 value is 10"
ถ้าหากทำถูกต้อง จะมีข้อความแสดงบนหน้าต่าง terminal แรกว่า “PM2.5 value is 10” - เพิ่มความปลอดภัยในการใช้งาน
5.1 Secure with a Passwordmosquitto_passwd -c /etc/mosquitto/passwd mqtt_user_name
Password: mqtt_password
5.2 Create a configuration file for Mosquitto pointing to the password file we have just created.nano /etc/mosquitto/conf.d/default.conf
พิมพ์บรรทัดเหล่านี้เข้าไปแล้ว save fileallow_anonymous false
password_file /etc/mosquitto/passwd - Restart mosquitto
systemctl restart mosquitto
หลังจากนี้หากจะ subscribe หรือ publish ต้องใช้ username และ password เสมอเช่น
subscribemosquitto_sub -t "PM25" -u "Davika" -P "password"
publishmosquitto_pub -t "PM25" -m "PM2.5 value is 10" -u "Davika" -P "password"
หากไม่ใส่ username และ password จะขึ้น error ดังนี้Connection Refused: not authorised.
Error: The connection was refused.
Sources