Skip to content

Commit

Permalink
Improve response reading
Browse files Browse the repository at this point in the history
  • Loading branch information
rrooggiieerr committed Feb 23, 2023
1 parent a6c4afa commit 1644482
Showing 1 changed file with 35 additions and 10 deletions.
45 changes: 35 additions & 10 deletions benqprojector/benqprojector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
RESPONSE_RE_LOSE = r"^\*?([^=]*)=([^#]*)#?$"

_SERIAL_TIMEOUT = 0.05
_RESPONSE_TIMEOUT = 5.0


class BenQProjectorError(Exception):
Expand Down Expand Up @@ -77,6 +78,17 @@ def __init__(self, command=None, action=None, response=None):
super().__init__(command, action)
self.response = response

class ResponseTimeoutError(BenQProjectorError):
"""
Invalid response error.
If the response format does not match the expected format.
"""

def __init__(self, command=None, action=None, response=None):
super().__init__(command, action)
self.response = response


class BenQProjector:
"""
Expand Down Expand Up @@ -282,7 +294,9 @@ def supports_command(self, command) -> bool:

def _sleep(self, seconds):
try:
asyncio.get_running_loop()
loop = asyncio.get_running_loop()
logger.debug("Sleep %s seconds", seconds)
loop.sleep()
# async def __sleep():
# await asyncio.sleep(seconds)
# asyncio.run(__sleep())
Expand Down Expand Up @@ -332,11 +346,7 @@ def _send_command(self, command: str, action: str = "?") -> str:
else:
raise EmptyResponseError(command, action)
else:
response = self._connection.readline()
response = response.decode()
# Cleanup response
response = response.strip(" \n\r\x00")
logger.debug("Response: %s", response)
response = self._read_response()

if response == "":
logger.debug("Empty line")
Expand Down Expand Up @@ -401,6 +411,24 @@ def _wait_for_prompt(self) -> bool:

return False

def _read_response(self) -> str:
response = b""
last_response = datetime.now()
while (datetime.now() - last_response).total_seconds() < _RESPONSE_TIMEOUT:
_response = self._connection.readline()
if len(_response) > 0:
response += _response
if any(c in _response for c in [b"\n", b"\r", b"\x00"]):
response = response.decode()
# Cleanup response
response = response.strip(" \n\r\x00")
logger.debug("Response: %s", response)

return response
last_response = datetime.now()

raise ResponseTimeoutError(response = response)

def _send_raw_command(self, command: str) -> str:
"""
Send a raw command to the BenQ projector.
Expand Down Expand Up @@ -473,10 +501,7 @@ def send_raw_command(self, command: str) -> str:
self._send_raw_command(command)

# Read and log the response
while _response := self._connection.readline():
response = _response.decode()
# Cleanup response
response = response.strip(" \n\r\x00")
while _response := self._read_response():
logger.debug(response)
except serial.SerialException as ex:
logger.exception(
Expand Down

0 comments on commit 1644482

Please sign in to comment.