【開發者筆記】MQTT python測試筆記
環境
本機Windows,Python3,paho-mqtt(通過python -m pip install paho-mqtt安裝)
MQTT服務器(可要可不要)
試驗1 [client發送與接收]本機python + [MQTT]iot.eclipse.org
MQTT是基於訂閱/發佈的物聯網協議。
python測試需要一個發送進程和接收進程,即一個發送客戶端和一個接收客戶端,如果這兩個客戶端工作在同一個topic下,那麼就能進行消息互通了。
服務器用“iot.eclipse.org”就好了,避免了自己搭建服務器,然後流程還可以跑通。
發送客戶端代碼:
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
idx = 0<br>#往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)<br>#訂閱頻道
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服務器,那麼回頭再說。
玩一玩就好了,不要給服務器增加太多負擔喲~
參考資料:
paho-qtt說明文檔
效果:
試驗2 [client發送與接收]本機python + [MQTT]自己的emqx服務器
將上面的iot.eclipse.org改爲自己的服務器地址。MQTT端口還是1883的。
控制檯地址:http://IP地址:18083
修改後運行,在服務器的控制檯可以查看該Topic以及訂閱後就可以查看client的信息。