From 8fe69d400d74fb4681f76959b44587782621714a Mon Sep 17 00:00:00 2001 From: Christian Mayer Date: Mon, 15 Feb 2021 21:52:43 +0100 Subject: [PATCH] auto reconnect to homeassistant after connection lost --- core/connectors/homeassistant.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/core/connectors/homeassistant.py b/core/connectors/homeassistant.py index 8537fb1..a96b564 100644 --- a/core/connectors/homeassistant.py +++ b/core/connectors/homeassistant.py @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*- import json +import time from kivy.support import install_twisted_reactor install_twisted_reactor() from autobahn.twisted.websocket import WebSocketClientProtocol, \ WebSocketClientFactory +from twisted.internet.protocol import ReconnectingClientFactory from twisted.internet import reactor @@ -38,8 +40,7 @@ def onClose(self, was_clean, code, reason): self.factory.handler.print_message("WebSocket connection closed: {0}".format(reason)) self.factory._proto = None - -class HAClientFactory(WebSocketClientFactory): +class HAClientFactory(WebSocketClientFactory, ReconnectingClientFactory): protocol = HAClientProtocol def __init__(self, config, handler): @@ -51,6 +52,15 @@ def __init__(self, config, handler): self._proto = None self.protocol.config = config + def clientConnectionFailed(self, connector, reason): + self.handler.print_message("WebSocket connection failed. Retrying in 5 seconds") + time.sleep(5) + self.retry(connector) + + def clientConnectionLost(self, connector, reason): + self.handler.print_message("WebSocket connection lost. Reconnecting") + self.retry(connector) + class HomeAssistant: def __init__(self, app, config):