MQTT是基於訂閱/發布的物聯網協議。
python測試需要一個發送進程和接收進程,即一個發送客戶端和一個接收客戶端,如果這兩個客戶端工作在同一個topic下,那么就能進行消息互通了。
服務器用“iot.eclipse.org”就好了,避免了自己搭建服務器,然后流程還可以跑通。
發送客戶端代碼:
import paho.mqtt.client as mqtt import paho.mqtt.publish as publish idx = 0
#往paho/temperature 一直發送內容 while True: print("send success") publish.single("paho/temperature", payload="this is message:%s"%idx, hostname="iot.eclipse.org", client_id="lora1", # qos = 0, # tls=tls, port=1883, protocol=mqtt.MQTTv311) idx += 1
接收客戶端代碼:
import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): #在這里處理業務邏輯 print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("iot.eclipse.org", 1883, 60)
#訂閱頻道 client.subscribe("paho/temperature") # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
然后運行兩個客戶端,就可以在接收端收到消息了。
MQTT服務器不負責存儲數據,需要編寫額外的接收客戶端來接收數據、分析、入庫等。
MQTT服務器用的是iot.eclipse.org,如果碰巧兩個人在用同一個頻道,那可能收到別人的消息哦~
如果要搭建自己的MQTT服務器,那么回頭再說。
玩一玩就好了,不要給服務器增加太多負擔喲~
參考資料: