Skip to content

Commit 816055f

Browse files
committed
Convert receiver into priority queue
1 parent 931c42d commit 816055f

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

plugwise_usb/connection/receiver.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from asyncio import (
2020
Future,
2121
Protocol,
22-
Queue,
22+
PriorityQueue,
2323
Task,
2424
TimerHandle,
2525
gather,
@@ -36,6 +36,7 @@
3636
from ..api import StickEvent
3737
from ..constants import MESSAGE_FOOTER, MESSAGE_HEADER
3838
from ..exceptions import MessageError
39+
from ..messages import Priority
3940
from ..messages.responses import (
4041
BROADCAST_IDS,
4142
PlugwiseResponse,
@@ -73,7 +74,7 @@ def __init__(
7374
self._buffer: bytes = bytes([])
7475
self._connection_state = False
7576
self._reduce_logging = True
76-
self._receive_queue: Queue[PlugwiseResponse | None] = Queue()
77+
self._receive_queue: PriorityQueue[PlugwiseResponse] = PriorityQueue()
7778
self._last_processed_messages: list[bytes] = []
7879
self._stick_future: futures.Future | None = None
7980
self._responses: dict[bytes, Callable[[PlugwiseResponse], None]] = {}
@@ -158,10 +159,10 @@ async def _stop_running_tasks(self) -> None:
158159
"""Cancel and stop any running task."""
159160
for task in self._delayed_processing_tasks.values():
160161
task.cancel()
161-
await self._receive_queue.put(None)
162-
if self._msg_processing_task is not None and not self._msg_processing_task.done():
163-
self._receive_queue.put_nowait(None)
164-
await self._msg_processing_task
162+
cancel_response = StickResponse()
163+
cancel_response.priority = Priority.CANCEL
164+
await self._receive_queue.put(cancel_response)
165+
await self._receive_worker_task
165166

166167
def data_received(self, data: bytes) -> None:
167168
"""Receive data from USB-Stick connection.
@@ -221,14 +222,14 @@ async def _receive_queue_worker(self):
221222
"""Process queue items."""
222223
_LOGGER.debug("Receive_queue_worker started")
223224
while self.is_connected:
224-
response: PlugwiseResponse | None = await self._receive_queue.get()
225+
response: PlugwiseResponse = await self._receive_queue.get()
226+
if response.priority == Priority.CANCEL:
227+
self._receive_queue.task_done()
228+
return
225229
_LOGGER.debug("Process from receive queue: %s", response)
226230
if isinstance(response, StickResponse):
227231
_LOGGER.debug("Received %s", response)
228232
await self._notify_stick_response_subscribers(response)
229-
elif response is None:
230-
self._receive_queue.task_done()
231-
return
232233
else:
233234
await self._notify_node_response_subscribers(response)
234235
self._receive_queue.task_done()

0 commit comments

Comments
 (0)