Skip to content

Commit

Permalink
Merge pull request #122 from calcut/fetch_all_messages_in_loop
Browse files Browse the repository at this point in the history
Fetch all messages in loop, non-blocking mode
  • Loading branch information
FoamyGuy authored Oct 10, 2022
2 parents f2cb3bb + 8a65c4e commit aec7777
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -834,14 +834,16 @@ def reconnect(self, resub_topics=True):
feed = subscribed_topics.pop()
self.subscribe(feed)

def loop(self, timeout=1):
def loop(self, timeout=0):
# pylint: disable = too-many-return-statements
"""Non-blocking message loop. Use this method to
check incoming subscription messages.
Returns response codes of any messages received.
:param int timeout: Socket timeout, in seconds.
"""

if self._timestamp == 0:
self._timestamp = time.monotonic()
current_time = time.monotonic()
Expand All @@ -854,11 +856,28 @@ def loop(self, timeout=1):
)
rcs = self.ping()
return rcs

stamp = time.monotonic()
self._sock.settimeout(timeout)
rc = self._wait_for_msg()
return [rc] if rc else None
rcs = []

while True:
rc = self._wait_for_msg(timeout)
if rc is None:
break
if time.monotonic() - stamp > self._recv_timeout:
if self.logger is not None:
self.logger.debug(
f"Loop timed out, message queue not empty after {self._recv_timeout}s"
)
break
rcs.append(rc)

return rcs if rcs else None

def _wait_for_msg(self, timeout=0.1):
# pylint: disable = too-many-return-statements

"""Reads and processes network events."""
# CPython socket module contains a timeout attribute
if hasattr(self._socket_pool, "timeout"):
Expand Down

0 comments on commit aec7777

Please sign in to comment.