From e1c1ebdc64369c51c06f00d1f526d160c5a60a7c Mon Sep 17 00:00:00 2001 From: James Nimmo Date: Tue, 17 Dec 2024 07:26:13 +0000 Subject: [PATCH] Refactor timeout on sending commands to potentially fix #57 --- pyintesishome/intesisbase.py | 21 ++++++++++++--------- pyintesishome/intesishome.py | 8 +++++++- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/pyintesishome/intesisbase.py b/pyintesishome/intesisbase.py index 0e6b894..526d27b 100644 --- a/pyintesishome/intesisbase.py +++ b/pyintesishome/intesisbase.py @@ -80,14 +80,14 @@ async def _send_command(self, command: str): if self._writer: self._writer.write(command.encode("ascii")) await self._writer.drain() - try: - await asyncio.wait_for( - self._received_response.wait(), - timeout=5.0, - ) - except asyncio.TimeoutError: - print("oops took longer than 5s!") - await self.stop() + timeout = 5.0 + start_time = asyncio.get_event_loop().time() + while not self._received_response.is_set(): + if asyncio.get_event_loop().time() - start_time > timeout: + _LOGGER.error("Timeout waiting for response") + await self.stop() + break + await asyncio.sleep(0.1) except OSError as exc: _LOGGER.error("%s Exception. %s / %s", type(exc), exc.args, exc) except Exception as exc: @@ -102,11 +102,14 @@ async def _data_received(self): break data = raw_data.decode("ascii") _LOGGER.debug("Received: %s", data) - await self._parse_response(data) + await self._parse_response(data) + if not self._received_response.is_set(): _LOGGER.debug("Resolving set_value's await") self._received_response.set() + + except IncompleteReadError: _LOGGER.debug( "pyIntesisHome lost connection to the %s server", self._device_type diff --git a/pyintesishome/intesishome.py b/pyintesishome/intesishome.py index 6ceac32..018b629 100644 --- a/pyintesishome/intesishome.py +++ b/pyintesishome/intesishome.py @@ -65,12 +65,18 @@ async def _parse_response(self, decoded_data): elif resp["command"] == "rssi": # Wireless strength has changed self._update_rssi(resp["data"]["deviceId"], resp["data"]["value"]) + else: + _LOGGER.debug("Unexpected command received: %s", resp["command"]) + # Ensure the _received_response event is set + if not self._received_response.is_set(): + _LOGGER.debug("Setting _received_response event") + self._received_response.set() return async def _send_keepalive(self): try: while True: - await asyncio.sleep(240) + await asyncio.sleep(120) _LOGGER.debug("sending keepalive to {self._device_type}") device_id = str(next(iter(self._devices))) message = (