我尝试过多次迭代这段代码。这是最后一次尝试,我被难住了。除了没有断开连接之外,它从未看到已发布的消息。
#!/usr/bin/python3
import paho.mqtt.client as mqtt #import the client1
import time
def on_message(client, userdata, message):
print("received message =",str(message.payload.decode("utf-8")))
def on_disconnect(client, userdata, flags, rc):
client.connected_flag=False #set flag
print("disconnected OK")
def on_connect(client, userdata, flags, rc):
if rc==0:
client.connected_flag=True #set flag
print("connected OK")
client.subscribe("Phone/announcet")#subscribe
print("subscribed OK")
else:
print("Bad connection Returned code=",rc)
mqtt.Client.connected_flag=False#create flag in class
broker="192.168.1.71"
client = mqtt.Client() #create new instance
print("Connecting to broker ",broker)
client.username_pw_set(username="zzz",password="xxx")
while True:
client.on_connect=on_connect #bind call back function
client.on_disconnect=on_disconnect
client.connect(broker) #connect to broker
client.loop_start()
while not client.connected_flag: #wait in loop
print("In wait loop")
time.sleep(1)
print("in Main Loop")
time.sleep(2)
client.loop_stop() #Stop loop
client.disconnect() # disconnect
print("After disconnect")以下是输出的样子:
Connecting to broker 192.168.1.71
In wait loop
connected OK
subscribed OK
in Main Loop
After disconnect
in Main Loop
connected OK
subscribed OK
After disconnect
in Main Loop
connected OK
subscribed OK
After disconnect谢谢,吉姆
发布于 2019-11-03 15:54:55
首先,您没有在客户端上设置on_message回调,这就是为什么您没有收到任何消息。
第二,在循环中设置回调没有好处,最好将它们移到主循环之外。
第三,在调用断开之前停止循环,因为所有回调都在客户端事件循环上运行,因此on_disconnect将永远不会被调用。在on_disconnect中还有一个额外的参数,不应该有flags。
我也不确定你的connected_flag是否能工作,它应该被移动到一个全局变量
#!/usr/bin/python3
import paho.mqtt.client as mqtt #import the client1
import time
connected_flag=False
def on_message(client, userdata, message):
print("received message =",str(message.payload.decode("utf-8")))
def on_disconnect(client, userdata, rc):
global connected_flag
connected_flag=False #set flag
print("disconnected OK")
def on_connect(client, userdata, flags, rc):
global connected_flag
if rc==0:
connected_flag=True #set flag
print("connected OK")
client.subscribe("Phone/announcet") #subscribe
print("subscribed OK")
else:
print("Bad connection Returned code=",rc)
broker="192.168.1.71"
client = mqtt.Client() #create new instance
print("Connecting to broker ",broker)
client.username_pw_set(username="zzz",password="xxx")
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
while True:
client.connect(broker) #connect to broker
client.loop_start()
while not connected_flag: #wait in loop
print("In wait loop")
time.sleep(1)
print("in Main Loop")
time.sleep(3)
print(connected_flag)
client.disconnect() # disconnect
print("After disconnect")
print(connected_flag)
client.loop_stop()https://stackoverflow.com/questions/58679512
复制相似问题