Skip to content

Commit

Permalink
Implement and use readuntil to read from stream
Browse files Browse the repository at this point in the history
  • Loading branch information
rrooggiieerr committed Oct 26, 2024
1 parent ecff09e commit 4a1802d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
22 changes: 22 additions & 0 deletions benqprojector/benqconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,28 @@ async def readline(self) -> bytes:
except TimeoutError:
return b""

async def readuntil(self, separator=b'\n'):
"""
Read data until separator is found.
"""
if self._reader.at_eof():
return b""

try:
return await asyncio.wait_for(
self._reader.readuntil(separator), timeout=self._read_timeout
)
except asyncio.IncompleteReadError as ex:
logger.exception("Incomplete read")
if ex.partial is not None:
return ex.partial
return b""
except ConnectionError as ex:
await self.close()
raise BenQConnectionError(ex.strerror) from ex
except TimeoutError:
return b""

async def write(self, data: bytes) -> int:
"""
Output the given string over the connection.
Expand Down
6 changes: 5 additions & 1 deletion benqprojector/benqprojector.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ class BenQProjector(ABC):

connection = None
has_prompt = None
_separator = b"\n"

_init: bool = True
_has_to_wait_for_prompt = True
Expand Down Expand Up @@ -335,6 +336,9 @@ async def connect(self, loop=None, interval: float = None) -> bool:
if self.has_prompt is None:
self.has_prompt = await self._detect_prompt()

if self.has_prompt is False:
self._separator = b'#'

power = None
try:
power = await self._send_command("pow")
Expand Down Expand Up @@ -707,7 +711,7 @@ async def _read_response(self) -> str:
response = b""
last_response = datetime.now()
while True:
_response = await self.connection.readline()
_response = await self.connection.readuntil(self._separator)
if len(_response) > 0:
response += _response
if any(c in _response for c in END_OF_RESPONSE):
Expand Down

0 comments on commit 4a1802d

Please sign in to comment.