Skip to content

Fetch all messages in loop, non-blocking mode #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Oct 10, 2022
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