问题描述
我有应该无限期运行的代码,但事实并非如此.它会每隔几个小时从客户端端停止一次(停止发布,循环继续运行,但是代理未收到任何消息),唯一可以做的就是再次运行它.
I have this code that should run indefinitely, however, it doesn't. It keeps on stopping every few hours from the client's side (stop publishing, the loop keeps on running, but nothing is received at the broker), and the only thing that can be done is to rerun it again.
我被告知,以增加循环功能的max_packets数量,但此方法不起作用,客户端会停止随机发布而不继续.应该做什么?我尝试了1、3、5、50和1000的值,但没有用.
I was advised here to increase the number of max_packets for the loop function, but it's not working and the client stops publishing randomly without continuing. What should be done? I tried the values of 1, 3, 5, 50 and a 1000 but no use.
代码:
client = mqtt.Client()
client.connect(address, 1883, 60)
while True:
data = getdata()
client.publish("$ahmed/",data,0)
client.loop(timeout=1.0, max_packets = 1) # what should be the parameters here so it doesn't stop publishing?
time.sleep(0.2)
推荐答案
除了已发布/订阅的应用程序消息外,MQTT还具有内部keepalive以避免TCP连接半开的问题( 1 ).客户有责任确保发送保活消息.根据规范,代理将断开那些在保持活动时间间隔的一半和一半(没有其他消息的情况下)中不发送保持活动状态的客户端.
In addition to applications messages which are published/subscribed, MQTT also have internal keepalive to avoid problem of half open TCP connections(1). And it is the responsibility of client to make sure keepalives are sent. As per specification, the broker will disconnect clients which doesn't send keepalives in one and half times of keepalive time interval( in absence of other messages).
除了发送消息外,loop()*
函数还维护代理与客户端之间的这种保持活动的流量.
In addition to sending messages, the loop()*
functions also maintains this keepalive traffic flow between broker and client.
随机尝试:尝试一次使用loop_start()
,而不是在while循环中调用loop()
.例如
A random try: Try using loop_start()
once instead of calling loop()
in while loop. E.g.
client = mqtt.Client()
client.connect(address)
#runs a thread in background to call loop function internally.
#In addition, this also reconnects to broker on a lost connection.
client.loop_start()
while True:
data = getdata()
client.publish("$ahmed",data)
client.loop_stop()
这篇关于MQTT循环函数的max_packets的适当值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!