Mqtt слушать отключение и повторное подключение - PullRequest
0 голосов
/ 23 сентября 2019

Я написал сценарий для получения данных в реальном времени от какого-либо датчика IoT с понедельника по пятницу с 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. Разрыв можно прослушать и автоматически попытаться восстановить соединение.Может кто-нибудь сказать мне, что не так в этом коде и как решить проблему?Очень ценю!

1 Ответ

0 голосов
/ 23 сентября 2019

передать keepAliveInterval и свойства тайм-аута при подключении к брокеру mqtt.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...