Skip to content

Commit

Permalink
formatted with Black
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-tritz committed Mar 22, 2024
1 parent 70f963b commit 89bf045
Showing 1 changed file with 20 additions and 41 deletions.
61 changes: 20 additions & 41 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,7 @@ def __init__(
self._username = username
self._password = password
if (
self._password and len(password.encode(
"utf-8")) > MQTT_TOPIC_LENGTH_LIMIT
self._password and len(password.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT
): # [MQTT-3.1.3.5]
raise MMQTTException("Password length is too large.")

Expand All @@ -225,8 +224,7 @@ def __init__(
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:
raise ValueError(
"MQTT Client ID must be between 1 and 23 bytes")
raise ValueError("MQTT Client ID must be between 1 and 23 bytes")

# LWT
self._lw_topic = None
Expand Down Expand Up @@ -263,7 +261,7 @@ def diff_ns(self, stamp):
Taking timestamp differences using nanosecond ints before dividing
should maintain precision.
"""
return (self.get_monotonic_time() - stamp)/1000000000
return (self.get_monotonic_time() - stamp) / 1000000000

def __enter__(self):
return self
Expand Down Expand Up @@ -317,8 +315,7 @@ def will_set(
self.logger.debug("Setting last will properties")
self._valid_qos(qos)
if self._is_connected:
raise MMQTTException(
"Last Will should only be called before connect().")
raise MMQTTException("Last Will should only be called before connect().")
if payload is None:
payload = ""
if isinstance(payload, (int, float, str)):
Expand All @@ -342,8 +339,7 @@ def add_topic_callback(self, mqtt_topic: str, callback_method) -> None:
If a callback is called for the topic, then any "on_message" callback will not be called.
"""
if mqtt_topic is None or callback_method is None:
raise ValueError(
"MQTT topic and callback method must both be defined.")
raise ValueError("MQTT topic and callback method must both be defined.")
self._on_message_filtered[mqtt_topic] = callback_method

def remove_topic_callback(self, mqtt_topic: str) -> None:
Expand Down Expand Up @@ -391,8 +387,7 @@ def username_pw_set(self, username: str, password: Optional[str] = None) -> None
"""
if self._is_connected:
raise MMQTTException(
"This method must be called before connect().")
raise MMQTTException("This method must be called before connect().")
self._username = username
if password is not None:
self._password = password
Expand Down Expand Up @@ -521,8 +516,7 @@ def _connect(
remaining_length += (
2 + len(self._lw_topic.encode("utf-8")) + 2 + len(self._lw_msg)
)
var_header[7] |= 0x4 | (self._lw_qos & 0x1) << 3 | (
self._lw_qos & 0x2) << 3
var_header[7] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos & 0x2) << 3
var_header[7] |= self._lw_retain << 5

self._encode_remaining_length(fixed_header, remaining_length)
Expand Down Expand Up @@ -651,8 +645,7 @@ def publish(
else:
raise MMQTTException("Invalid message data type.")
if len(msg) > MQTT_MSG_MAX_SZ:
raise MMQTTException(
f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.")
raise MMQTTException(f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.")
assert (
0 <= qos <= 1
), "Quality of Service Level 2 is unsupported by this library."
Expand Down Expand Up @@ -699,8 +692,7 @@ def publish(
rcv_pid = rcv_pid_buf[0] << 0x08 | rcv_pid_buf[1]
if self._pid == rcv_pid:
if self.on_publish is not None:
self.on_publish(
self, self.user_data, topic, rcv_pid)
self.on_publish(self, self.user_data, topic, rcv_pid)
return

if op is None:
Expand Down Expand Up @@ -744,10 +736,8 @@ def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> N
self.logger.debug("Sending SUBSCRIBE to broker...")
fixed_header = bytearray([MQTT_SUB])
packet_length = 2 + (2 * len(topics)) + (1 * len(topics))
packet_length += sum(len(topic.encode("utf-8"))
for topic, qos in topics)
self._encode_remaining_length(
fixed_header, remaining_length=packet_length)
packet_length += sum(len(topic.encode("utf-8")) for topic, qos in topics)
self._encode_remaining_length(fixed_header, remaining_length=packet_length)
self.logger.debug(f"Fixed Header: {fixed_header}")
self._sock.send(fixed_header)
self._pid = self._pid + 1 if self._pid < 0xFFFF else 1
Expand Down Expand Up @@ -827,8 +817,7 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None:
fixed_header = bytearray([MQTT_UNSUB])
packet_length = 2 + (2 * len(topics))
packet_length += sum(len(topic.encode("utf-8")) for topic in topics)
self._encode_remaining_length(
fixed_header, remaining_length=packet_length)
self._encode_remaining_length(fixed_header, remaining_length=packet_length)
self.logger.debug(f"Fixed Header: {fixed_header}")
self._sock.send(fixed_header)
self._pid = self._pid + 1 if self._pid < 0xFFFF else 1
Expand Down Expand Up @@ -861,8 +850,7 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None:
assert rc[1] == packet_id_bytes[0] and rc[2] == packet_id_bytes[1]
for t in topics:
if self.on_unsubscribe is not None:
self.on_unsubscribe(
self, self.user_data, t, self._pid)
self.on_unsubscribe(self, self.user_data, t, self._pid)
self._subscribed_topics.remove(t)
return

Expand All @@ -880,8 +868,7 @@ def _recompute_reconnect_backoff(self) -> None:
self._reconnect_timeout = 2**self._reconnect_attempt
# pylint: disable=consider-using-f-string
self.logger.debug(
"Reconnect timeout computed to {:.2f}".format(
self._reconnect_timeout)
"Reconnect timeout computed to {:.2f}".format(self._reconnect_timeout)
)

if self._reconnect_timeout > self._reconnect_maximum_backoff:
Expand Down Expand Up @@ -955,10 +942,7 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
rcs = []

while True:
if (
self.diff_ns(self._last_msg_sent_timestamp)
>= self.keep_alive
):
if self.diff_ns(self._last_msg_sent_timestamp) >= 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..."
Expand All @@ -967,8 +951,7 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
# 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:
self.logger.debug(
f"Loop timed out after {timeout} seconds")
self.logger.debug(f"Loop timed out after {timeout} seconds")
break

rc = self._wait_for_msg()
Expand Down Expand Up @@ -1006,14 +989,12 @@ def _wait_for_msg(self, timeout: Optional[float] = None) -> Optional[int]:
# If we get here, it means that there is nothing to be received
return None
pkt_type = res[0] & MQTT_PKT_TYPE_MASK
self.logger.debug(
f"Got message type: {hex(pkt_type)} pkt: {hex(res[0])}")
self.logger.debug(f"Got message type: {hex(pkt_type)} pkt: {hex(res[0])}")
if pkt_type == MQTT_PINGRESP:
self.logger.debug("Got PINGRESP")
sz = self._sock_exact_recv(1)[0]
if sz != 0x00:
raise MMQTTException(
f"Unexpected PINGRESP returned from broker: {sz}.")
raise MMQTTException(f"Unexpected PINGRESP returned from broker: {sz}.")
return pkt_type

if pkt_type != MQTT_PUBLISH:
Expand Down Expand Up @@ -1042,8 +1023,7 @@ def _wait_for_msg(self, timeout: Optional[float] = None) -> Optional[int]:
# read message contents
raw_msg = self._sock_exact_recv(sz)
msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8")
self.logger.debug(
"Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg)
self.logger.debug("Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg)
self._handle_on_message(topic, msg)
if res[0] & 0x06 == 0x02:
pkt = bytearray(b"\x40\x02\0\0")
Expand Down Expand Up @@ -1091,8 +1071,7 @@ def _sock_exact_recv(
recv_len = self._sock.recv_into(rc, bufsize)
to_read = bufsize - recv_len
if to_read < 0:
raise MMQTTException(
f"negative number of bytes to read: {to_read}")
raise MMQTTException(f"negative number of bytes to read: {to_read}")
read_timeout = timeout if timeout is not None else self.keep_alive
mv = mv[recv_len:]
while to_read > 0:
Expand Down

0 comments on commit 89bf045

Please sign in to comment.