From adeabcae0045ffa6dc3c72705447a3c1056dd84c Mon Sep 17 00:00:00 2001 From: Fisch Date: Sat, 19 Aug 2023 11:29:56 +0200 Subject: [PATCH] add reconnect feature --- src/controller.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/controller.py b/src/controller.py index 13d898a..33d7700 100644 --- a/src/controller.py +++ b/src/controller.py @@ -34,6 +34,10 @@ class Controller: connected = False displayL = None displayR = None + + basetopic = None + mqtthost = None + mqttport = None def __init__(self, base_topic, mqtt_host, mqtt_port = 1883): @@ -72,19 +76,29 @@ class Controller: # set brightness, range 0-1.0, 1.0 max brightness self.displayL.brightness = 1.0 self.displayR.brightness = 1.0 - + + self.basetopic = basetopic + self.mqtthost = mqtt_host + self.mqttport = mqtt_port + + connectToMQTT() + + def connectToMQTT(self): + print("trying to connect to mqtt") self.mqtt = mqtt.Client() self.mqtt.on_connect = self.on_connect self.mqtt.on_message = self.on_message self.mqtt.on_disconnect = self.on_disconnect - self.mqtt.connect(mqtt_host, mqtt_port) - self.topic = base_topic + self.mqtt.connect(self.mqtthost, self.mqttport) + self.topic = self.basetopic def on_disconnect(self, client, userdata, rc): print("MQTT disconnected") + self.mode = Mode.STATIC + self.text = "- - - -" self.connected = False def on_message(self, client, userdata, message): @@ -161,6 +175,10 @@ class Controller: self.mqtt.publish(self.topic + "/" + "$hostname", socket.gethostname() , 1 ) self.mqtt.publish(self.topic + "/" + "$localip", self.get_ip() , 1 ) + + #clear display + self.mode = Mode.STATIC + self.text = "" def get_ip(self): @@ -242,7 +260,13 @@ class Controller: run = True while run: + + if !self.connected: + if (time.time()>self.last_reconnectTry+30): + connectToMQTT() + self.last_reconnectTry=time.time() self.mqtt.loop(0.1) #with block timeout + if self.displayL is not None and self.displayR is not None: #displays initialized