1. 程式人生 > >pthon對emqtt的簡單操作

pthon對emqtt的簡單操作

需要先下載外部包

pip install paho-mqtt

釋出者

import paho.mqtt.client as mqtt

HOST = "192.168.44.31"
PORT = 1883

def Publish_Message():
    client = mqtt.Client()
    client.username_pw_set(username='admin', password='public')  # 用於添加了外掛認證方式後
    client.connect(HOST, PORT, 60)
    for x in range(10):
        Message = "hello" + str(x)
        client.publish("services", Message, 0)  # 釋出一個主題為'services',內容為‘hello x’的資訊
    # time.sleep(10)
    client.loop_forever()  # 保持連線狀態

if __name__ == '__main__':
    Publish_Message()

釋出者,主要內容:publish("topic_name","utf8_message",Qos)

  • Qos:0 --> 傳送者只發送一次訊息,不進行重試,Broker不會返回確認訊息。Broker可能沒有接收到訊息。(預設)
  • Qos:1 --> 傳送者最少傳送一次訊息,確保訊息達到Broker,Broker需要返回確認訊息PUBACK。Broker可能接收到重複訊息。
  • Qos:2 --> 使用兩階段確認來保證訊息的不丟失和不重複。Broker肯定會接收到訊息,且只收到一次。

訂閱者

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))  # rc表示返回來的狀態值
    client.subscribe("services")

def on_message(client, userdata, msg):
    print(msg.topic+" " + ":" + str(msg.payload))

if __name__ == "__main__":
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(username='admin', password='public')  # 用於添加了外掛認證方式後
    client.connect("192.168.44.31", 1883, 60)
    client.loop_forever()

訂閱者,資訊的產出在msg.payload

rc值代表的含義:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.