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: