我在Raspberry Pi上有一个简单的脚本,它每3秒发布一条示例消息。我已经声明了回调on_connect,on_publish和on_disconnect。此客户端连接成功,但未调用on_connect,调用发布和on_publish,调用disconnectcts和on_disconnect。
这是我的剧本
import paho.mqtt.client as mqtt
import time
def on_connect(mqttc, userdata, rc):
print("Connected with result code "+str(rc))
if rc!=0 :
mqttc.reconnect()
def on_publish(mqttc, userdata, mid):
print "Published"
def on_disconnect(mqttc, userdata, rc):
if rc != 0:
print("Unexpected disconnection. Reconnecting...")
mqttc.reconnect()
else :
print "Disconnected successfully"
# Setup MQTT
# broker='test.mosquitto.org'
broker = 'iot.eclipse.org'
broker_port=1883
# Create a client instance
mqttc=mqtt.Client(client_id="MyClient")
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_disconnect = on_disconnect
while 1:
mqttc.connect(broker, broker_port, 60)
# print "Connected." # I don't want this message.
# Why isn't the on_connect callback invoked?
try:
topic = "this/is/a/test/topic"
payload = "test_message"
print "Publishing " + payload + " to topic: " + topic + " ..."
mqttc.publish(topic, payload, 0)
except Exception as e:
print "exception"
log_file=open("log.txt","w")
log_file.write(str(time.time())+" "+e.__str__())
log_file.close()
mqttc.disconnect()
print ""
time.sleep(3)
虽然这个小故障" bug"不会影响消息发布,这主要是我想要实现的,为什么会发生,我该如何解决呢?
答案 0 :(得分:7)
这不起作用的原因是你没有调用任何loop*()
函数。这些处理网络流量。如果您不使用,则无法保证您的外发消息将被发送,并且绝对不会处理任何传入消息。
loop_forever()
是一个阻止调用来处理网络循环 - 可能不是你想要的。
loop_start()
启动一个线程来处理网络循环,因此立即返回。
我会这样做:
mqttc.connect(broker, broker_port, 60) # Don't forget to handle errors
mqttc.loop_start()
while 1:
try:
topic = "this/is/a/test/topic"
payload = "test_message"
print "Publishing " + payload + " to topic: " + topic + " ..."
mqttc.publish(topic, payload, 0)
except Exception as e:
print "exception"
log_file=open("log.txt","w")
log_file.write(str(time.time())+" "+e.__str__())
log_file.close()
print ""
time.sleep(3)
你仍然需要修复你的on_connect回调,因为@Kiran说。
每次都不需要断开连接 - 事实上,当您断开连接时,无法保证您的消息将被发送。您应该使用on_publish
回调来了解邮件的发送时间。
如果你想做一个简单的connect-publish-disconnect,那么可以使用paho.mqtt.publish
助手模块:
import paho.mqtt.publish as publish
while 1:
try:
topic = "this/is/a/test/topic"
payload = "test_message"
print "Publishing " + payload + " to topic: " + topic + " ..."
publish.single(topic, payload, 0, host=broker, port=broker_port)
except Exception as e:
print "exception"
log_file=open("log.txt","w")
log_file.write(str(time.time())+" "+e.__str__())
log_file.close()
print ""
time.sleep(3)
答案 1 :(得分:3)