Skip to content

Commit

Permalink
added _ns suffix to vars and func
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-tritz committed Mar 22, 2024
1 parent 89bf045 commit 639160a
Showing 1 changed file with 28 additions and 28 deletions.
56 changes: 28 additions & 28 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def __init__(
self._is_connected = False
self._msg_size_lim = MQTT_MSG_SZ_LIM
self._pid = 0
self._last_msg_sent_timestamp: int = 0
self._last_msg_sent_timestamp_ns: int = 0
self.logger = NullLogger()
"""An optional logging attribute that can be set with with a Logger
to enable debug logging."""
Expand Down Expand Up @@ -220,7 +220,7 @@ def __init__(
self.client_id = client_id
else:
# assign a unique client_id
time_int = (self.get_monotonic_time() % 10000000000) // 10000000
time_int = (self.get_monotonic_ns_time() % 10000000000) // 10000000
self.client_id = f"cpy{randint(0, time_int)}{randint(0, 99)}"
# generated client_id's enforce spec.'s length rules
if len(self.client_id.encode("utf-8")) > 23 or not self.client_id:
Expand All @@ -244,7 +244,7 @@ def __init__(
self.on_subscribe = None
self.on_unsubscribe = None

def get_monotonic_time(self) -> float:
def get_monotonic_ns_time(self) -> float:
"""
Provide monotonic time in nanoseconds. Based on underlying implementation
this might result in imprecise time, that will result in the library
Expand All @@ -256,12 +256,12 @@ def get_monotonic_time(self) -> float:

return int(time.monotonic() * 1000000000)

def diff_ns(self, stamp):
def diff_ns(self, stamp_ns):
"""
Taking timestamp differences using nanosecond ints before dividing
should maintain precision.
"""
return (self.get_monotonic_time() - stamp) / 1000000000
return (self.get_monotonic_ns_time() - stamp_ns) / 1000000000

def __enter__(self):
return self
Expand Down Expand Up @@ -534,9 +534,9 @@ def _connect(
if self._username is not None:
self._send_str(self._username)
self._send_str(self._password)
self._last_msg_sent_timestamp = self.get_monotonic_time()
self._last_msg_sent_timestamp_ns = self.get_monotonic_ns_time()
self.logger.debug("Receiving CONNACK packet from broker")
stamp = self.get_monotonic_time()
stamp_ns = self.get_monotonic_ns_time()
while True:
op = self._wait_for_msg()
if op == 32:
Expand All @@ -552,7 +552,7 @@ def _connect(
return result

if op is None:
if self.diff_ns(stamp) > self._recv_timeout:
if self.diff_ns(stamp_ns) > self._recv_timeout:
raise MMQTTException(
f"No data received from broker for {self._recv_timeout} seconds."
)
Expand Down Expand Up @@ -589,7 +589,7 @@ def disconnect(self) -> None:
self._connection_manager.close_socket(self._sock)
self._is_connected = False
self._subscribed_topics = []
self._last_msg_sent_timestamp = 0
self._last_msg_sent_timestamp_ns = 0
if self.on_disconnect is not None:
self.on_disconnect(self, self.user_data, 0)

Expand All @@ -602,14 +602,14 @@ def ping(self) -> list[int]:
self.logger.debug("Sending PINGREQ")
self._sock.send(MQTT_PINGREQ)
ping_timeout = self.keep_alive
stamp = self.get_monotonic_time()
self._last_msg_sent_timestamp = stamp
stamp_ns = self.get_monotonic_ns_time()
self._last_msg_sent_timestamp_ns = stamp_ns
rc, rcs = None, []
while rc != MQTT_PINGRESP:
rc = self._wait_for_msg()
if rc:
rcs.append(rc)
if self.diff_ns(stamp) > ping_timeout:
if self.diff_ns(stamp_ns) > ping_timeout:
raise MMQTTException("PINGRESP not returned from broker.")
return rcs

Expand Down Expand Up @@ -678,11 +678,11 @@ def publish(
self._sock.send(pub_hdr_fixed)
self._sock.send(pub_hdr_var)
self._sock.send(msg)
self._last_msg_sent_timestamp = self.get_monotonic_time()
self._last_msg_sent_timestamp_ns = self.get_monotonic_ns_time()
if qos == 0 and self.on_publish is not None:
self.on_publish(self, self.user_data, topic, self._pid)
if qos == 1:
stamp = self.get_monotonic_time()
stamp_ns = self.get_monotonic_ns_time()
while True:
op = self._wait_for_msg()
if op == 0x40:
Expand All @@ -696,7 +696,7 @@ def publish(
return

if op is None:
if self.diff_ns(stamp) > self._recv_timeout:
if self.diff_ns(stamp_ns) > self._recv_timeout:
raise MMQTTException(
f"No data received from broker for {self._recv_timeout} seconds."
)
Expand Down Expand Up @@ -755,12 +755,12 @@ def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> N
self.logger.debug(f"SUBSCRIBING to topic {t} with QoS {q}")
self.logger.debug(f"payload: {payload}")
self._sock.send(payload)
stamp = self.get_monotonic_time()
self._last_msg_sent_timestamp = stamp
stamp_ns = self.get_monotonic_ns_time()
self._last_msg_sent_timestamp_ns = stamp_ns
while True:
op = self._wait_for_msg()
if op is None:
if self.diff_ns(stamp) > self._recv_timeout:
if self.diff_ns(stamp_ns) > self._recv_timeout:
raise MMQTTException(
f"No data received from broker for {self._recv_timeout} seconds."
)
Expand Down Expand Up @@ -832,13 +832,13 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None:
for t in topics:
self.logger.debug(f"UNSUBSCRIBING from topic {t}")
self._sock.send(payload)
self._last_msg_sent_timestamp = self.get_monotonic_time()
self._last_msg_sent_timestamp_ns = self.get_monotonic_ns_time()
self.logger.debug("Waiting for UNSUBACK...")
while True:
stamp = self.get_monotonic_time()
stamp_ns = self.get_monotonic_ns_time()
op = self._wait_for_msg()
if op is None:
if self.diff_ns(stamp) > self._recv_timeout:
if self.diff_ns(stamp_ns) > self._recv_timeout:
raise MMQTTException(
f"No data received from broker for {self._recv_timeout} seconds."
)
Expand Down Expand Up @@ -938,26 +938,26 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
self._connected()
self.logger.debug(f"waiting for messages for {timeout} seconds")

stamp = self.get_monotonic_time()
stamp_ns = self.get_monotonic_ns_time()
rcs = []

while True:
if self.diff_ns(self._last_msg_sent_timestamp) >= self.keep_alive:
if self.diff_ns(self._last_msg_sent_timestamp_ns) >= self.keep_alive:
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
self.logger.debug(
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
)
rcs.extend(self.ping())
# ping() itself contains a _wait_for_msg() loop which might have taken a while,
# so check here as well.
if self.diff_ns(stamp) > timeout:
if self.diff_ns(stamp_ns) > timeout:
self.logger.debug(f"Loop timed out after {timeout} seconds")
break

rc = self._wait_for_msg()
if rc is not None:
rcs.append(rc)
if self.diff_ns(stamp) > timeout:
if self.diff_ns(stamp_ns) > timeout:
self.logger.debug(f"Loop timed out after {timeout} seconds")
break

Expand Down Expand Up @@ -1063,7 +1063,7 @@ def _sock_exact_recv(
:param float timeout: timeout, in seconds. Defaults to keep_alive
:return: byte array
"""
stamp = self.get_monotonic_time()
stamp_ns = self.get_monotonic_ns_time()
if not self._backwards_compatible_sock:
# CPython/Socketpool Impl.
rc = bytearray(bufsize)
Expand All @@ -1078,7 +1078,7 @@ def _sock_exact_recv(
recv_len = self._sock.recv_into(mv, to_read)
to_read -= recv_len
mv = mv[recv_len:]
if self.diff_ns(stamp) > read_timeout:
if self.diff_ns(stamp_ns) > read_timeout:
raise MMQTTException(
f"Unable to receive {to_read} bytes within {read_timeout} seconds."
)
Expand All @@ -1098,7 +1098,7 @@ def _sock_exact_recv(
recv = self._sock.recv(to_read)
to_read -= len(recv)
rc += recv
if self.diff_ns(stamp) > read_timeout:
if self.diff_ns(stamp_ns) > read_timeout:
raise MMQTTException(
f"Unable to receive {to_read} bytes within {read_timeout} seconds."
)
Expand Down

0 comments on commit 639160a

Please sign in to comment.