Skip to content

Commit 5378f8f

Browse files
committed
reverted timestamps back to using ticks_ms from adafruit_ticks library
1 parent 120d8a9 commit 5378f8f

File tree

1 file changed

+30
-45
lines changed

1 file changed

+30
-45
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 30 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from random import randint
3737

3838
from adafruit_connection_manager import get_connection_manager
39+
from adafruit_ticks import ticks_ms, ticks_diff
3940

4041
try:
4142
from typing import List, Optional, Tuple, Type, Union
@@ -51,7 +52,7 @@
5152

5253
from .matcher import MQTTMatcher
5354

54-
__version__ = "0.0.0+auto.0"
55+
__version__ = "7.6.3"
5556
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT.git"
5657

5758
# Client-specific variables
@@ -181,7 +182,7 @@ def __init__(
181182
self._is_connected = False
182183
self._msg_size_lim = MQTT_MSG_SZ_LIM
183184
self._pid = 0
184-
self._last_msg_sent_timestamp_ns: int = 0
185+
self._last_msg_sent_timestamp: int = 0
185186
self.logger = NullLogger()
186187
"""An optional logging attribute that can be set with with a Logger
187188
to enable debug logging."""
@@ -220,7 +221,7 @@ def __init__(
220221
self.client_id = client_id
221222
else:
222223
# assign a unique client_id
223-
time_int = (self.get_monotonic_time_ns() % 10000000000) // 10000000
224+
time_int = int(ticks_ms() / 10) % 1000
224225
self.client_id = f"cpy{randint(0, time_int)}{randint(0, 99)}"
225226
# generated client_id's enforce spec.'s length rules
226227
if len(self.client_id.encode("utf-8")) > 23 or not self.client_id:
@@ -255,25 +256,6 @@ def get_monotonic_time(self) -> float:
255256

256257
return time.monotonic()
257258

258-
def get_monotonic_time_ns(self) -> int:
259-
"""
260-
Provide monotonic time in nanoseconds. Based on underlying implementation
261-
this might result in imprecise time, that will result in the library
262-
not being able to operate if running contiguously for more than 24 days or so.
263-
Keeping timestamps in nanosecond ints from monotonic_ns should preserve precision.
264-
"""
265-
if self.use_monotonic_ns:
266-
return time.monotonic_ns()
267-
268-
return int(time.monotonic() * 1000000000)
269-
270-
def diff_ns(self, stamp_ns) -> float:
271-
"""
272-
Taking timestamp differences using nanosecond ints before dividing
273-
should maintain precision. Returns time difference in seconds.
274-
"""
275-
return (self.get_monotonic_time_ns() - stamp_ns) / 1000000000
276-
277259
def __enter__(self):
278260
return self
279261

@@ -545,9 +527,9 @@ def _connect(
545527
if self._username is not None:
546528
self._send_str(self._username)
547529
self._send_str(self._password)
548-
self._last_msg_sent_timestamp_ns = self.get_monotonic_time_ns()
530+
self._last_msg_sent_timestamp = ticks_ms()
549531
self.logger.debug("Receiving CONNACK packet from broker")
550-
stamp_ns = self.get_monotonic_time_ns()
532+
stamp = ticks_ms()
551533
while True:
552534
op = self._wait_for_msg()
553535
if op == 32:
@@ -563,7 +545,7 @@ def _connect(
563545
return result
564546

565547
if op is None:
566-
if self.diff_ns(stamp_ns) > self._recv_timeout:
548+
if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout:
567549
raise MMQTTException(
568550
f"No data received from broker for {self._recv_timeout} seconds."
569551
)
@@ -600,7 +582,7 @@ def disconnect(self) -> None:
600582
self._connection_manager.close_socket(self._sock)
601583
self._is_connected = False
602584
self._subscribed_topics = []
603-
self._last_msg_sent_timestamp_ns = 0
585+
self._last_msg_sent_timestamp = 0
604586
if self.on_disconnect is not None:
605587
self.on_disconnect(self, self.user_data, 0)
606588

@@ -613,14 +595,14 @@ def ping(self) -> list[int]:
613595
self.logger.debug("Sending PINGREQ")
614596
self._sock.send(MQTT_PINGREQ)
615597
ping_timeout = self.keep_alive
616-
stamp_ns = self.get_monotonic_time_ns()
617-
self._last_msg_sent_timestamp_ns = stamp_ns
598+
stamp = ticks_ms()
599+
self._last_msg_sent_timestamp = stamp
618600
rc, rcs = None, []
619601
while rc != MQTT_PINGRESP:
620602
rc = self._wait_for_msg()
621603
if rc:
622604
rcs.append(rc)
623-
if self.diff_ns(stamp_ns) > ping_timeout:
605+
if ticks_diff(ticks_ms(), stamp):
624606
raise MMQTTException("PINGRESP not returned from broker.")
625607
return rcs
626608

@@ -689,11 +671,11 @@ def publish(
689671
self._sock.send(pub_hdr_fixed)
690672
self._sock.send(pub_hdr_var)
691673
self._sock.send(msg)
692-
self._last_msg_sent_timestamp_ns = self.get_monotonic_time_ns()
674+
self._last_msg_sent_timestamp = ticks_ms()
693675
if qos == 0 and self.on_publish is not None:
694676
self.on_publish(self, self.user_data, topic, self._pid)
695677
if qos == 1:
696-
stamp_ns = self.get_monotonic_time_ns()
678+
stamp = ticks_ms()
697679
while True:
698680
op = self._wait_for_msg()
699681
if op == 0x40:
@@ -707,7 +689,7 @@ def publish(
707689
return
708690

709691
if op is None:
710-
if self.diff_ns(stamp_ns) > self._recv_timeout:
692+
if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout:
711693
raise MMQTTException(
712694
f"No data received from broker for {self._recv_timeout} seconds."
713695
)
@@ -766,12 +748,12 @@ def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> N
766748
self.logger.debug(f"SUBSCRIBING to topic {t} with QoS {q}")
767749
self.logger.debug(f"payload: {payload}")
768750
self._sock.send(payload)
769-
stamp_ns = self.get_monotonic_time_ns()
770-
self._last_msg_sent_timestamp_ns = stamp_ns
751+
stamp = ticks_ms()
752+
self._last_msg_sent_timestamp = stamp
771753
while True:
772754
op = self._wait_for_msg()
773755
if op is None:
774-
if self.diff_ns(stamp_ns) > self._recv_timeout:
756+
if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout:
775757
raise MMQTTException(
776758
f"No data received from broker for {self._recv_timeout} seconds."
777759
)
@@ -843,13 +825,13 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None:
843825
for t in topics:
844826
self.logger.debug(f"UNSUBSCRIBING from topic {t}")
845827
self._sock.send(payload)
846-
self._last_msg_sent_timestamp_ns = self.get_monotonic_time_ns()
828+
self._last_msg_sent_timestamp = ticks_ms()
847829
self.logger.debug("Waiting for UNSUBACK...")
848830
while True:
849-
stamp_ns = self.get_monotonic_time_ns()
831+
stamp = ticks_ms()
850832
op = self._wait_for_msg()
851833
if op is None:
852-
if self.diff_ns(stamp_ns) > self._recv_timeout:
834+
if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout:
853835
raise MMQTTException(
854836
f"No data received from broker for {self._recv_timeout} seconds."
855837
)
@@ -949,26 +931,29 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
949931
self._connected()
950932
self.logger.debug(f"waiting for messages for {timeout} seconds")
951933

952-
stamp_ns = self.get_monotonic_time_ns()
934+
stamp = ticks_ms()
953935
rcs = []
954936

955937
while True:
956-
if self.diff_ns(self._last_msg_sent_timestamp_ns) >= self.keep_alive:
938+
if (
939+
ticks_diff(ticks_ms(), self._last_msg_sent_timestamp) / 1000
940+
>= self.keep_alive
941+
):
957942
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
958943
self.logger.debug(
959944
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
960945
)
961946
rcs.extend(self.ping())
962947
# ping() itself contains a _wait_for_msg() loop which might have taken a while,
963948
# so check here as well.
964-
if self.diff_ns(stamp_ns) > timeout:
949+
if ticks_diff(ticks_ms(), stamp) / 1000 > timeout:
965950
self.logger.debug(f"Loop timed out after {timeout} seconds")
966951
break
967952

968953
rc = self._wait_for_msg()
969954
if rc is not None:
970955
rcs.append(rc)
971-
if self.diff_ns(stamp_ns) > timeout:
956+
if ticks_diff(ticks_ms(), stamp) / 1000 > timeout:
972957
self.logger.debug(f"Loop timed out after {timeout} seconds")
973958
break
974959

@@ -1074,7 +1059,7 @@ def _sock_exact_recv(
10741059
:param float timeout: timeout, in seconds. Defaults to keep_alive
10751060
:return: byte array
10761061
"""
1077-
stamp_ns = self.get_monotonic_time_ns()
1062+
stamp = ticks_ms()
10781063
if not self._backwards_compatible_sock:
10791064
# CPython/Socketpool Impl.
10801065
rc = bytearray(bufsize)
@@ -1089,7 +1074,7 @@ def _sock_exact_recv(
10891074
recv_len = self._sock.recv_into(mv, to_read)
10901075
to_read -= recv_len
10911076
mv = mv[recv_len:]
1092-
if self.diff_ns(stamp_ns) > read_timeout:
1077+
if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout:
10931078
raise MMQTTException(
10941079
f"Unable to receive {to_read} bytes within {read_timeout} seconds."
10951080
)
@@ -1109,7 +1094,7 @@ def _sock_exact_recv(
11091094
recv = self._sock.recv(to_read)
11101095
to_read -= len(recv)
11111096
rc += recv
1112-
if self.diff_ns(stamp_ns) > read_timeout:
1097+
if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout:
11131098
raise MMQTTException(
11141099
f"Unable to receive {to_read} bytes within {read_timeout} seconds."
11151100
)

0 commit comments

Comments
 (0)