楊皓程 2021/12/21, 2021/12/28
LINE: peter30234 (加我,請註明是陳永欽老師的學生)
A. Adafruit.io
root@localhost:~# sudo apt update root@localhost:~# sudo apt upgrade root@localhost:~# sudo apt install -y vim python pip root@localhost:~# sudo pip install paho-mqtt root@localhost:~# sudo pip install paho
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt #訂閱[hcyang0207/feeds/home.humi] def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("hcyang0207/feeds/home.humi") #收到訂閱 def on_message(client, userdata, msg): print(msg.topic+" "+ msg.payload.decode('utf-8')) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("hcyang0207","aio_BKwE178y7NDTg4K651**********") client.connect("io.adafruit.com", 1883, 60) client.loop_forever()
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt import random import json import time client = mqtt.Client() # 設定登入帳號密碼 client.username_pw_set("hcyang0207","aio_BKwE178y7NDTg4K651**********") client.connect("io.adafruit.com", 1883, 60) while True: #隨機濕度50~60 value = random.randint(50,60) #送出訊息 payload = {"value":value} print(payload) #發送目的 client.publish("hcyang0207/feeds/home.humi", json.dumps(payload)) #延遲5秒 time.sleep(5)
B. Adafruit.io
root@localhost:~# sudo apt update root@localhost:~# sudo apt upgrade root@localhost:~# sudo apt install -y mosquitto-clients
B-2. mosquitto-client 測試 Adafruit Subscribe
root@localhost:~# sudo mosquitto_sub -h io.adafruit.com -p 1883 -u hcyang0207 -P aio_BKwE178y7NDTg4K651********** -t "hcyang0207/feeds/home.humi" -vhcyang0207/feeds/home.humi 50
B-3. mosquitto-client 測試 Adafruit Publish
root@localhost:~# sudo mosquitto_pub -h io.adafruit.com -p 1883 -u hcyang0207 -P aio_BKwE178y7NDTg4K651********** -t "hcyang0207/feeds/home.humi" -m "{\"value\":50}"
適合用在自己管理的主機,電腦主機、Raspberry Pi、實體電腦等,雲端主機如AWS、GCP、Vultr、Linode...
C. 無安全性MQTT Server架設 + 測試
root@localhost:~# sudo apt update root@localhost:~# sudo apt upgrade root@localhost:~# sudo apt install -y mosquitto mosquitto-clients vim root@localhost:~# sudo vim /etc/mosquitto/conf.d/test.confallow_anonymous true listener 1883root@localhost:~# sudo systemctl restart mosquitto
C-2. mosquitto-client 測試 Subscribe
root@localhost:~# sudo mosquitto_sub -h localhost -p 1883 -t "testchanel" -vtestchanel Hello2 MQTT
C-3. mosquitto-client 測試 Publish
root@localhost:~# sudo mosquitto_pub -h localhost -p 1883 -t "testchanel" -m "Hello2 MQTT"
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt #訂閱[testchanel] def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("testchanel") #收到訂閱 def on_message(client, userdata, msg): print(msg.topic+" "+ msg.payload.decode('utf-8')) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) client.loop_forever()
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt import random import json import time client = mqtt.Client() client.connect("localhost", 1883, 60) while True: #隨機濕度50~60 value = random.randint(50,60) #送出訊息 payload = {"value":value} print(payload) #發送目的 client.publish("testchanel", json.dumps(payload)) #延遲5秒 time.sleep(5)
D. 有安全性MQTT Server架設 + 測試
root@localhost:~# sudo apt update root@localhost:~# sudo apt upgrade root@localhost:~# sudo apt install -y mosquitto mosquitto-clients vim root@localhost:~# sudo mosquitto_passwd -c /etc/mosquitto/passwd testPassword: test123 Reenter password: test123root@localhost:~# sudo vim /etc/mosquitto/conf.d/test.confallow_anonymous false password_file /etc/mosquitto/passwd listener 1883root@localhost:~# sudo systemctl restart mosquitto
D-2. mosquitto-client 測試 Subscribe
root@localhost:~# sudo mosquitto_sub -h localhost -p 1883 -u test -P test123 -t "testchanel" -vtestchanel Hello2 MQTT
D-3. mosquitto-client 測試 Publish
root@localhost:~# sudo mosquitto_pub -h localhost -p 1883 -u test -P test123 -t "testchanel" -m "Hello2 MQTT"
D-4. mqtt_auth_subscribe.py 下載
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt #訂閱[testchanel] def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("testchanel") #收到訂閱 def on_message(client, userdata, msg): print(msg.topic+" "+ msg.payload.decode('utf-8')) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("test","test123") client.connect("localhost", 1883, 60) client.loop_forever()
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt import random import json import time client = mqtt.Client() # 設定登入帳號密碼 client.username_pw_set("test","test123") client.connect("localhost", 1883, 60) while True: #隨機濕度50~60 value = random.randint(50,60) #送出訊息 payload = {"value":value} print(payload) #發送目的 client.publish("testchanel", json.dumps(payload)) #延遲5秒 time.sleep(5)
這個方式只能localhost本機測試,無法外部連線測試,適合新手練習。
E. 無安全性MQTT Server架設 + 測試
!apt install mosquitto !pip install paho-mqtt
!echo "allow_anonymous true" > /etc/mosquitto/conf.d/test.conf !echo "listener 1883" >> /etc/mosquitto/conf.d/test.conf !cat /etc/mosquitto/conf.d/test.conf !service mosquitto restart
import paho.mqtt.client as mqtt import threading import random import json import time #訂閱 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("testchanel") #訊息 def on_message(client, userdata, msg): print("[Subscribe]", "["+msg.topic+"] "+ msg.payload.decode('utf-8')) #推送 def test_publish(): for i in range(1,5): time.sleep(1) #隨機濕度50~60 value = random.randint(50,60) #送出訊息 payload = {"value":value} print("[Publish][testchanel]", payload) #發送目的 client.publish("testchanel", json.dumps(payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) threading.Thread(target=test_publish).start() client.loop_forever()
F. 有安全性MQTT Server架設 + 測試
!apt install mosquitto mosquitto-clients !pip install paho-mqtt
#設定MQTT !echo "allow_anonymous false" > /etc/mosquitto/conf.d/test.conf !echo "password_file /etc/mosquitto/passwd" >> /etc/mosquitto/conf.d/test.conf !echo "listener 1883" >> /etc/mosquitto/conf.d/test.conf !cat /etc/mosquitto/conf.d/test.conf #建立密碼檔 !rm /etc/mosquitto/passwd !echo "" > /etc/mosquitto/passwd !mosquitto_passwd -b /etc/mosquitto/passwd test test123 !cat /etc/mosquitto/passwd #重啟服務 !service mosquitto restart
import paho.mqtt.client as mqtt import threading import random import json import time #訂閱 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("testchanel") #訊息 def on_message(client, userdata, msg): print("[Subscribe]", "["+msg.topic+"] "+ msg.payload.decode('utf-8')) #推送 def test_publish(): for i in range(1,5): time.sleep(1) #隨機濕度50~60 value = random.randint(50,60) #送出訊息 payload = {"value":value} print("[Publish][testchanel]", payload) #發送目的 client.publish("testchanel", json.dumps(payload)) client = mqtt.Client() client.username_pw_set("test","test123") client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) threading.Thread(target=test_publish).start() client.loop_forever()
#include <ESP8266WiFi.h> #include <PubSubClient.h> // WiFi const char *ssid = "HCWifi"; // Enter your WiFi SSID const char *password = "09*****716"; // Enter WiFi password // MQTT Broker const char *mqtt_broker = "io.adafruit.com"; const char *topic = "hcyang0207/feeds/home.humi"; const char *mqtt_username = "hcyang0207"; const char *mqtt_password = "aio_BKwE178y7NDTg4K651**********"; const int mqtt_port = 1883; WiFiClient espClient; PubSubClient client(espClient); void setup() { // Set software serial baud to 115200; Serial.begin(115200); // connecting to a WiFi network WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); // connecting to a mqtt broker client.setServer(mqtt_broker, mqtt_port); client.setCallback(callback); while (!client.connected()) { String client_id = "esp8266-client-"; client_id += String(WiFi.macAddress()); Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str()); if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) { Serial.println("Public mqtt broker connected"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } } // publish and subscribe client.publish(topic, "{\"value\":60}"); client.subscribe(topic); } void callback(char *topic, byte *payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char) payload[i]); } Serial.println(); Serial.println("-----------------------"); } void loop() { client.loop(); }