Skip to content
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

loop() timeout parameter should be absolute #169

Merged
merged 4 commits into from
Jul 8, 2023
Merged
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
25 changes: 9 additions & 16 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,11 +980,10 @@ def reconnect(self, resub_topics: bool = True) -> int:

def loop(self, timeout: float = 0) -> Optional[list[int]]:
# 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.
"""Non-blocking message loop. Use this method to check for incoming messages.
Returns list of response codes of any messages received or None.

:param float timeout: Socket timeout, in seconds.
:param float timeout: return after this timeout, in seconds.

"""

Expand All @@ -1002,23 +1001,19 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
return rcs

stamp = time.monotonic()
self._sock.settimeout(timeout)
rcs = []

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

return rcs if rcs else None

def _wait_for_msg(self, timeout: float = 0.1) -> Optional[int]:
def _wait_for_msg(self) -> Optional[int]:
# pylint: disable = too-many-return-statements

"""Reads and processes network events.
Expand All @@ -1039,8 +1034,6 @@ def _wait_for_msg(self, timeout: float = 0.1) -> Optional[int]:
return None
raise MMQTTException from error

# Block while we parse the rest of the response
self._sock.settimeout(timeout)
if res in [None, b"", b"\x00"]:
# If we get here, it means that there is nothing to be received
return None
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,4 @@ def message(client, topic, message):
print("Sending photocell value: %d" % photocell_val)
mqtt_client.publish(default_topic, photocell_val)
photocell_val += 1
time.sleep(0.5)
time.sleep(3)