Mqtt监听断开连接并自动重新连接

时间:2019-09-23 03:12:25

标签: python python-3.x mqtt

我编写了一个脚本,从周一至周五的8:30 AM-19:00 PM从某个IoT传感器获取实时数据,但是问题在于该脚本将停止运行,而不会每隔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 AM到19:00 PM接收实时数据,可以监听断开连接并自动尝试重新连接。谁能告诉我这段代码有什么问题以及如何解决该问题?真的很感激!

1 个答案:

答案 0 :(得分:0)

连接到mqtt代理时,

传递keepAliveInterval和timeout属性。