MQTT 笔记:apollo mqtt server + paho-mqtt python

记录下写client时遇到的一些问题

1. subscribe(topic, qos) 和 publish(topic, payload=None, qos=0, retain=False)

网上找到的简单的client代码subscribe都放在回调函数on_connect里。如下:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("Topic/#",2)

def on_message(client, userdata, msg):
    print("Topic: ",msg.topic, "Payload: ", msg.payload.decode())
 
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
client = mqtt.Client(client_id)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
HOST = "127.0.0.1"
client.connect(HOST, 61613, 60)
client.loop_forever()

我尝试把subscribe放在client.connect下总是报错,一直搞不清楚为什么,最后在subscribe前加了1s中的sleep,居然可以了。

import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

def on_message(client, userdata, msg):
    print("Topic: ",msg.topic, "Payload: ", msg.payload.decode())
 
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
client = mqtt.Client(client_id)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
HOST = "127.0.0.1"
client.connect(HOST, 61613, 60)
time.sleep(1)            #这1s很重要
client.subscribe("Topic/#",2)
client.loop_forever()

publish同样也是这样。没有加time.sleep(1)时,rec也是(0,1)。但是subscribe client 收不到message。加上后,rec也是(0,1),subscribe client 就可以收到message啦。

import paho.mqtt.client as mqtt
import time
 
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
client = mqtt.Client(client_id)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
HOST = "127.0.0.1"
client.connect(HOST, 61613, 60)
client.loop_start()
time.sleep(1)            #这1s很重要
rec = client.publish("Topic/Status","Open", 2)
print(rec)

你可能感兴趣的:(MQTT)