【问题标题】:Mqtt listen to disconnect and auto-reconnectMqtt 监听断开并自动重新连接
【发布时间】:2019-09-23 03:12:25
【问题描述】:

我写了一个脚本来从周一到周五上午 8:30 到晚上 19​​:00 从一些物联网传感器获取实时数据,但问题是脚本会停止,而不会每 50-60 分钟产生任何错误.所以我添加了一个回调来监听断开连接并尝试自动重新连接,但它不起作用。

import paho.mqtt.client as mqtt
import time
import datetime


ms_topic = ''  
client_id = ''


def stamp_to_time(time_stamp):
    #convert timestamp to datetime
    local_time = time.localtime(int(time_stamp))
    mytime = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    return datetime.datetime.strptime(mytime, "%Y-%m-%d %H:%M:%S")


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(ms_topic,2)


#The callback for when the client receives a disconnect response from the server
def on_disconnect(client, userdata, rc):
    current_time = stamp_to_time(time.time())
    if current_time.strftime("%H") != '19': #jump out the loop if it's 19:00 
        client.reconnect()


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    payload = str(msg.payload, encoding = 'utf-8')          

    current_time = stamp_to_time(time.time())
    if current_time.strftime("%H") == '19': #jump out the loop if it's 19:00 
        client.disconnect()


def test():  
    client = mqtt.Client(client_id, clean_session = False)    
    client.username_pw_set("", "")  
    client.reconnect_delay_set(min_delay = 1, max_delay = 10000)
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.connect("www.zeta-alliance.com", 1883, 60)
    client.loop_forever()


if __name__ == '__main__':  
    test()

我的目标是让它保持工作并接收从早上 8:30 到晚上 19​​:00 的实时数据,断开连接可以被监听并自动尝试重新连接。谁能告诉我这段代码有什么问题以及如何解决这个问题?真的很感激!

【问题讨论】:

  • %M 是分钟而不是小时...
  • 您已编辑问题,但如果分钟与小时确实解决了问题,则未包含任何更新。
  • 根据文档以及 paho-mqtt 的代码,client_idclean_session = False 结合的空字符串应该抛出 ValueError。所以要么你过度简化了你的代码,要么你错过了一些东西。你试过没有clean_session=False吗?另外,重新连接应该通过调用loop_forever自动处理,所以我猜有一个更深层次的问题,可能是链接断开了?

标签: python python-3.x mqtt


【解决方案1】:

在连接到 mqtt 代理时传递 keepAliveInterval 和 timeout 属性。

【讨论】:

  • 答案需要包含更多上下文。此外,这些值是可选的,将使用默认值填充,因此这不是解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-10-14
  • 2013-08-26
  • 2012-05-28
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
相关资源
最近更新 更多