Skip to content

Commit 62f66f2

Browse files
committed
UNSUBSCRIBE needs to encode remaining length correctly too
1 parent 163c730 commit 62f66f2

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
MQTT_PINGRESP = const(0xD0)
6262
MQTT_PUBLISH = const(0x30)
6363
MQTT_SUB = const(0x82)
64-
MQTT_UNSUB = b"\xA2"
64+
MQTT_UNSUB = const(0xA2)
6565
MQTT_DISCONNECT = b"\xe0\0"
6666

6767
MQTT_PKT_TYPE_MASK = const(0xF0)
@@ -911,18 +911,25 @@ def unsubscribe(self, topic: str) -> None:
911911
"Topic must be subscribed to before attempting unsubscribe."
912912
)
913913
# Assemble packet
914+
self.logger.debug("Sending UNSUBSCRIBE to broker...")
915+
fixed_header = bytearray([MQTT_UNSUB])
914916
packet_length = 2 + (2 * len(topics))
915917
packet_length += sum(len(topic.encode("utf-8")) for topic in topics)
916-
packet_length_byte = packet_length.to_bytes(1, "big")
918+
self.encode_remaining_length(fixed_header, remaining_length=packet_length)
919+
self.logger.debug(f"Fixed Header: {fixed_header}")
920+
self._sock.send(fixed_header)
917921
self._pid = self._pid + 1 if self._pid < 0xFFFF else 1
918922
packet_id_bytes = self._pid.to_bytes(2, "big")
919-
packet = MQTT_UNSUB + packet_length_byte + packet_id_bytes
923+
var_header = packet_id_bytes
924+
self.logger.debug(f"Variable Header: {var_header}")
925+
self._sock.send(var_header)
926+
payload = bytes()
920927
for t in topics:
921928
topic_size = len(t.encode("utf-8")).to_bytes(2, "big")
922-
packet += topic_size + t.encode()
929+
payload += topic_size + t.encode()
923930
for t in topics:
924-
self.logger.debug("UNSUBSCRIBING from topic %s", t)
925-
self._sock.send(packet)
931+
self.logger.debug(f"UNSUBSCRIBING from topic {t}")
932+
self._sock.send(payload)
926933
self.logger.debug("Waiting for UNSUBACK...")
927934
while True:
928935
stamp = self.get_monotonic_time()

0 commit comments

Comments
 (0)