gui: Fix a bug which GUI may recv two msgs at once

This commit is contained in:
linuswck 2024-06-17 12:53:04 +08:00
parent 92f6b83b16
commit 9002ca6992

View File

@ -654,7 +654,7 @@ class Kirdy:
self._reader = None
self._writer = None
async def _read_response(self, buffer_size=16384):
async def _read_response(self, buffer_size=16384, report=False):
"""
Decode newline delimited Json objects and return the latest json received inside the buffer.
- buffer_size: Integer
@ -663,16 +663,21 @@ class Kirdy:
raw_response = await asyncio.wait_for(self._reader.read(buffer_size), self.timeout)
response = raw_response.decode('utf-8', errors='ignore').split("\n")
print()
print(response)
items = []
for item in reversed(response):
try:
return json.loads(item)
items.append(json.loads(item))
except json.decoder.JSONDecodeError as e:
pass
return { "msg_type": "Exception"}
if len(items) > 0 :
if report:
return items[0]
else:
return items
else:
return { "msg_type": "EmptyResponse"}
except TimeoutError:
return { "msg_type": "Exception"}
return { "msg_type": "RecvTimeout"}
async def _send_raw_cmd_handler(self, cmd, lock=True, msg_type="Acknowledge"):
if lock:
@ -689,11 +694,12 @@ class Kirdy:
try:
self._writer.write(bytes(json.dumps(cmd), "UTF-8"))
await self._writer.drain()
response = await self._read_response()
if response["msg_type"] == msg_type:
return response
if response["msg_type"] == "InvalidCmd":
return InvalidCmd
responses = await self._read_response()
for response in responses:
if response["msg_type"] == msg_type:
return response
if response["msg_type"] == "InvalidCmd":
return InvalidCmd
except asyncio.exceptions.CancelledError:
return None
except Exception as e:
@ -737,10 +743,10 @@ class Kirdy:
try:
self._writer.write(bytes(json.dumps(cmd_dict), "UTF-8"))
await self._writer.drain()
response = await self._read_response()
print(f'retry attempts: {retry} msg_type: {msg_type}')
if response["msg_type"] == msg_type:
return response
responses = await self._read_response()
for response in responses:
if response["msg_type"] == msg_type:
return response
retry += 1
await asyncio.sleep(0.1)
@ -761,7 +767,7 @@ class Kirdy:
while self._report_mode_on:
await asyncio.sleep(report_interval)
async with self._cmd_lock:
yield await self._read_response(buffer_size)
yield await self._read_response(buffer_size, report=True)
await self.device.set_active_report_mode(False)