Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions can/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def get_message(self, timeout: float = 0.5) -> Message | None:
not block after :meth:`can.BufferedReader.stop` has been called.

:param timeout: The number of seconds to wait for a new message.
Use :meth:`get_message_nowait` for an explicit non-blocking read.
:return: the received :class:`can.Message` or `None`, if the queue is empty.
"""
try:
Expand All @@ -116,6 +117,17 @@ def get_message(self, timeout: float = 0.5) -> Message | None:
except Empty:
return None

def get_message_nowait(self) -> Message | None:
"""
Retrieve the oldest queued message without waiting.

:return: the received :class:`can.Message`, or ``None`` if the queue is empty.
"""
try:
return self.buffer.get(block=False)
except Empty:
return None

def stop(self) -> None:
"""Prohibits any more additions to this reader."""
self.is_stopped = True
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/1919.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added ``BufferedReader.get_message_nowait()`` for explicit non-blocking reads.
13 changes: 13 additions & 0 deletions test/listener_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,19 @@ def testBufferedListenerReceives(self):
a_listener.stop()
self.assertIsNotNone(a_listener.get_message(0.1))

def testBufferedListenerGetMessageNowait(self):
listener = can.BufferedReader()
self.assertIsNone(listener.get_message_nowait())

first = generate_message(0xDADADA)
second = generate_message(0x123)
listener(first)
listener(second)

self.assertIs(listener.get_message_nowait(), first)
self.assertIs(listener.get_message_nowait(), second)
self.assertIsNone(listener.get_message_nowait())


def test_deprecated_loop_arg(recwarn):
try:
Expand Down