From 53277e999a3ab5315bdd3ac1c2d979823734a01a Mon Sep 17 00:00:00 2001 From: Alvaro Viebrantz Date: Fri, 7 Jan 2022 17:46:57 -0400 Subject: [PATCH] feat: add support for binary messages --- adafruit_minimqtt/adafruit_minimqtt.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index 876f09d..db2b46a 100755 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -126,6 +126,7 @@ class MQTT: :param int keep_alive: KeepAlive interval between the broker and the MiniMQTT client. :param socket socket_pool: A pool of socket resources available for the given radio. :param ssl_context: SSL context for long-lived SSL connections. + :param bool use_binary_mode: Messages are passed as bytearray instead of string to callbacks. """ @@ -141,12 +142,14 @@ def __init__( keep_alive=60, socket_pool=None, ssl_context=None, + use_binary_mode=False, ): self._socket_pool = socket_pool self._ssl_context = ssl_context self._sock = None self._backwards_compatible_sock = False + self._use_binary_mode = use_binary_mode self.keep_alive = keep_alive self._user_data = None @@ -839,8 +842,9 @@ def _wait_for_msg(self, timeout=0.1): pid = pid[0] << 0x08 | pid[1] sz -= 0x02 # read message contents - msg = self._sock_exact_recv(sz) - self._handle_on_message(self, topic, str(msg, "utf-8")) + raw_msg = self._sock_exact_recv(sz) + msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8") + self._handle_on_message(self, topic, msg) if res[0] & 0x06 == 0x02: pkt = bytearray(b"\x40\x02\0\0") struct.pack_into("!H", pkt, 2, pid)