From 43c4eb5a073b4cb13cbf7ad532030f6a2710a1a1 Mon Sep 17 00:00:00 2001 From: Martin Bauer Date: Thu, 4 Jul 2019 22:50:49 +0200 Subject: [PATCH] Reconnecting client: reconnect if write fails --- custom_components/reconnecting_client.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/custom_components/reconnecting_client.py b/custom_components/reconnecting_client.py index fef3641..6a4deba 100644 --- a/custom_components/reconnecting_client.py +++ b/custom_components/reconnecting_client.py @@ -22,22 +22,28 @@ class ReconnectingClient: self._writer = None self._connection_last_state = 'UNKNOWN' self._connection_name = connection_name + self._connection_task = None async def start(self): self._run = True self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) - self.hass.loop.create_task(self._connection()) + self._connection_task = self.hass.loop.create_task(self._connection()) async def stop(self): + self._connection_task.cancel() self._run = False self.connected = False def write_line(self, line): - if self._writer: - line += '\n' - self._writer.write(line.encode()) - else: - _LOGGER.warning(f"Skipping line '{line}'' because _writer is None") + try: + if self._writer: + line += '\n' + self._writer.write(line.encode()) + else: + _LOGGER.warning(f"Skipping line '{line}'' because _writer is None") + except RuntimeError: + self._connection_task.cancel() + self._connection_task = self.hass.loop.create_task(self._connection()) async def _connection(self): try: