MQTT協議 Python客戶端
阿新 • • 發佈:2019-02-09
1、安裝模組
下載並解壓,開啟目錄執行命令安裝模組
python setup.py install
2、Python程式碼3、其他介面#-*-coding:utf-8-*- import paho.mqtt.client as mqtt # 當連線上伺服器後回撥此函式 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # 放在on_connect函式裡意味著 # 重新連線時訂閱主題將會被更新 client.subscribe("topic/sub") # 從伺服器接受到訊息後回撥此函式 def on_message(client, userdata, msg): print("主題:"+msg.topic+" 訊息:"+str(msg.payload)) client = mqtt.Client() #引數有 Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp") client.on_connect = on_connect #設定連線上伺服器回撥函式 client.on_message = on_message #設定接收到伺服器訊息回撥函式 client.connect("iot.eclipse.org", 1883, 60) #連線伺服器,埠為1883,維持心跳為60秒 client.loop_forever()
client.disconnect() #斷開連線
client.publish(topic, payload=None, qos=0, retain=False) #釋出訊息
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")
mqttc.on_disconnect = on_disconnect ##設定與伺服器斷開連接回調函式
def on_publish(client, userdata, mid): #釋出訊息完成回撥函式
...
4、參考文獻