【发布时间】: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_id与clean_session = False结合的空字符串应该抛出ValueError。所以要么你过度简化了你的代码,要么你错过了一些东西。你试过没有clean_session=False吗?另外,重新连接应该通过调用loop_forever自动处理,所以我猜有一个更深层次的问题,可能是链接断开了?
标签: python python-3.x mqtt