From e632cbbfdd7461758a0e85b57d358c58d91c1d4f Mon Sep 17 00:00:00 2001 From: linuswck Date: Tue, 3 Sep 2024 16:49:46 +0800 Subject: [PATCH] driver: use readuntil to get response msg - The driver may recv partial ctrl msg, which causes a json decode error --- pykirdy/driver/kirdy.py | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/pykirdy/driver/kirdy.py b/pykirdy/driver/kirdy.py index b545d63..90f6030 100644 --- a/pykirdy/driver/kirdy.py +++ b/pykirdy/driver/kirdy.py @@ -806,21 +806,21 @@ class Kirdy: try: while True: if self._report_mode_on: - responses = await asyncio.wait_for(self._read_response(), self._timeout) + response = await asyncio.wait_for(self._read_response(), self._timeout) else: - responses = await self._read_response() - for response in responses: - if response["msg_type"] == 'HardReset': - raise asyncio.exceptions.CancelledError - if response["msg_type"] == 'Report' and not self._msg_queue_get_report: - if self._report_sig is None: - self._report_queue.put_nowait_overwrite(response) - else: - self._report_sig.emit(response) + response = await self._read_response() + + if response["msg_type"] == 'HardReset': + raise asyncio.exceptions.CancelledError + if response["msg_type"] == 'Report' and not self._msg_queue_get_report: + if self._report_sig is None: + self._report_queue.put_nowait_overwrite(response) else: - if self._msg_queue_get_report: - self._msg_queue_get_report = False - self._int_msg_queue.put_nowait_overwrite(response) + self._report_sig.emit(response) + else: + if self._msg_queue_get_report: + self._msg_queue_get_report = False + self._int_msg_queue.put_nowait_overwrite(response) except asyncio.exceptions.CancelledError: pass except (TimeoutError, ConnectionResetError, ConnectionError) as exec: @@ -860,18 +860,13 @@ class Kirdy: writer_sock = self._writer.get_extra_info("socket") writer_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - async def _read_response(self, buffer_size=16384): + async def _read_response(self): raw_response = b'' while len(raw_response) == 0: # Ignore 0 size packet - raw_response = await self._reader.read(buffer_size) + raw_response = await self._reader.readuntil() response = raw_response.decode('utf-8', errors='ignore').split("\n") - response = response[:-1] - - items = [] - for item in response: - items.append(json.loads(item)) - return items + return json.loads(response[0]) async def _send_raw_cmd(self, cmd, msg_type="Acknowledge", sig=None): if self.connected():