add reconnect feature

This commit is contained in:
interfisch 2023-08-19 11:29:56 +02:00
parent 279caf49b5
commit adeabcae00
1 changed files with 27 additions and 3 deletions

View File

@ -34,6 +34,10 @@ class Controller:
connected = False connected = False
displayL = None displayL = None
displayR = None displayR = None
basetopic = None
mqtthost = None
mqttport = None
def __init__(self, base_topic, mqtt_host, mqtt_port = 1883): 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 # set brightness, range 0-1.0, 1.0 max brightness
self.displayL.brightness = 1.0 self.displayL.brightness = 1.0
self.displayR.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 = mqtt.Client()
self.mqtt.on_connect = self.on_connect self.mqtt.on_connect = self.on_connect
self.mqtt.on_message = self.on_message self.mqtt.on_message = self.on_message
self.mqtt.on_disconnect = self.on_disconnect self.mqtt.on_disconnect = self.on_disconnect
self.mqtt.connect(mqtt_host, mqtt_port) self.mqtt.connect(self.mqtthost, self.mqttport)
self.topic = base_topic self.topic = self.basetopic
def on_disconnect(self, client, userdata, rc): def on_disconnect(self, client, userdata, rc):
print("MQTT disconnected") print("MQTT disconnected")
self.mode = Mode.STATIC
self.text = "- - - -"
self.connected = False self.connected = False
def on_message(self, client, userdata, message): 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 + "/" + "$hostname", socket.gethostname() , 1 )
self.mqtt.publish(self.topic + "/" + "$localip", self.get_ip() , 1 ) self.mqtt.publish(self.topic + "/" + "$localip", self.get_ip() , 1 )
#clear display
self.mode = Mode.STATIC
self.text = ""
def get_ip(self): def get_ip(self):
@ -242,7 +260,13 @@ class Controller:
run = True run = True
while run: 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 self.mqtt.loop(0.1) #with block timeout
if self.displayL is not None and self.displayR is not None: #displays initialized if self.displayL is not None and self.displayR is not None: #displays initialized