Skip to content

Commit a799f54

Browse files
brentrubrentru
authored andcommitted
add non-blocking and blocking control loops, make wait_for_msg a private method
1 parent c9d6b8d commit a799f54

1 file changed

Lines changed: 29 additions & 9 deletions

File tree

adafruit_minimqtt.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ def publish(self, topic, msg, retain=False, qos=0):
391391
self._sock.write(msg)
392392
if qos == 1:
393393
while 1:
394-
op = self.wait_for_msg()
394+
op = self._wait_for_msg()
395395
if op == const(0x40):
396396
sz = self._sock.read(1)
397397
assert sz == b"\x02"
@@ -466,7 +466,7 @@ def subscribe(self, topic, qos=0):
466466
self._logger.debug('SUBSCRIBING to topic {0} with QoS {1}'.format(t, q))
467467
self._sock.write(packet)
468468
while 1:
469-
op = self.wait_for_msg()
469+
op = self._wait_for_msg()
470470
if op == 0x90:
471471
rc = self._sock.read(4)
472472
assert rc[1] == packet[2] and rc[2] == packet[3]
@@ -521,7 +521,7 @@ def unsubscribe(self, topic):
521521
if self._logger is not None:
522522
self._logger.debug('Waiting for UNSUBACK...')
523523
while 1:
524-
op = self.wait_for_msg()
524+
op = self._wait_for_msg()
525525
if op == const(176):
526526
return_code = self._sock.read(3)
527527
assert return_code[0] == const(0x02)
@@ -533,19 +533,39 @@ def unsubscribe(self, topic):
533533
self._subscribed_topics.remove(t)
534534
return
535535

536-
def check_for_msg(self):
537-
"""Checks if a pending message from the server is avaliable.
538-
If not, returns None.
536+
def loop_forever(self):
537+
"""Starts a blocking message loop. Use this
538+
method if you want to run a program
539+
forever. Network reconnection is handled within
540+
this call. Your code will not execute anything
541+
below this call.
542+
"""
543+
run = True
544+
while run:
545+
if self._is_connected:
546+
self._wait_for_msg(0.0)
547+
else:
548+
if self._logger is not None:
549+
self._logger.debug('Lost connection, reconnecting and resubscribing...')
550+
self.reconnect(resub_topics=True)
551+
if self._logger is not None:
552+
self._logger.debug('Connection restored, continuing to loop forever...')
553+
554+
def loop(self):
555+
"""Non-blocking message loop. Use this method to
556+
check incoming subscription messages. Does not handle
557+
network reconnection like loop_forever - reconnection must
558+
be handled within your code.
539559
"""
540560
self._sock.settimeout(0.1)
541-
self.wait_for_msg()
561+
return self._wait_for_msg()
542562

543-
def wait_for_msg(self):
563+
def _wait_for_msg(self, timeout=30):
544564
"""Reads and processes network events.
545565
Returns response code if successful.
546566
"""
547567
res = self._sock.read(1)
548-
self._sock.settimeout(0.0)
568+
self._sock.settimeout(timeout)
549569
if res in [None, b""]:
550570
return None
551571
if res == MQTT_PINGRESP:

0 commit comments

Comments
 (0)