reconnect code

This commit is contained in:
oskar 2025-02-22 18:35:27 +01:00
parent fb54afa73d
commit 1be3812aaf

View file

@ -1,20 +1,45 @@
#!/usr/bin/python3
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import traceback
import os
import datetime
import time
monitor_state = 1
FIRST_RECONNECT_DELAY = 1
RECONNECT_RATE = 2
MAX_RECONNECT_COUNT = 12
MAX_RECONNECT_DELAY = 60
def on_connect(client, userdata, flags, reason_code, properties):
now = datetime.datetime.now()
print(str(now) + ": " +"Connected to %s:%s" % (mqttc._host, mqttc._port))
if reason_code == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", reason_code)
def on_disconnect(client, userdata, flags, reason_code, properties):
now = datetime.datetime.now()
print(str(now) + ": disconnected")
print("Disconnected with result code: %s", reason_code)
reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY
while reconnect_count < MAX_RECONNECT_COUNT:
print("Reconnecting in %d seconds...", reconnect_delay)
time.sleep(reconnect_delay)
try:
client.reconnect()
print("Reconnected successfully!")
return
except Exception as err:
print("%s. Reconnect failed. Retrying...", err)
reconnect_delay *= RECONNECT_RATE
reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)
reconnect_count += 1
print("Reconnect failed after %s attempts. Exiting...", reconnect_count)
def on_message(client, userdata, message):
global monitor_state
@ -73,7 +98,7 @@ def on_log(client, obj, level, string):
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
client_id = 'mqtt-client-pimirror2'
client_id = 'mqtt-client-solaria'
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id)
mqttc.on_message = on_message