Reconnecting client: reconnect if write fails

This commit is contained in:
Martin Bauer 2019-07-04 22:50:49 +02:00
parent b31f955945
commit 43c4eb5a07
1 changed files with 12 additions and 6 deletions

View File

@ -22,22 +22,28 @@ class ReconnectingClient:
self._writer = None self._writer = None
self._connection_last_state = 'UNKNOWN' self._connection_last_state = 'UNKNOWN'
self._connection_name = connection_name self._connection_name = connection_name
self._connection_task = None
async def start(self): async def start(self):
self._run = True self._run = True
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) 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): async def stop(self):
self._connection_task.cancel()
self._run = False self._run = False
self.connected = False self.connected = False
def write_line(self, line): def write_line(self, line):
if self._writer: try:
line += '\n' if self._writer:
self._writer.write(line.encode()) line += '\n'
else: self._writer.write(line.encode())
_LOGGER.warning(f"Skipping line '{line}'' because _writer is None") 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): async def _connection(self):
try: try: