From fcec7f7c1d3485474596a0db38a83e7b9ce5870b Mon Sep 17 00:00:00 2001 From: Nicolas Graziano Date: Wed, 10 Aug 2016 20:39:51 +0200 Subject: [PATCH] umqtt.simple: Add MQTT user/password authentication. Limitation the total length of client id, user name and password must be under 111 characters. --- umqtt.simple/umqtt/simple.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/umqtt.simple/umqtt/simple.py b/umqtt.simple/umqtt/simple.py index 654da7a1..41dab2e5 100644 --- a/umqtt.simple/umqtt/simple.py +++ b/umqtt.simple/umqtt/simple.py @@ -7,7 +7,7 @@ class MQTTException(Exception): class MQTTClient: - def __init__(self, client_id, server, port=0, ssl=False): + def __init__(self, client_id, server, port=0, user=None, password=None, ssl=False): if port == 0: port = 8883 if ssl else 1883 self.client_id = client_id @@ -16,6 +16,8 @@ class MQTTClient: self.ssl = ssl self.pid = 0 self.cb = None + self.user = user + self.pswd = password def _send_str(self, s): self.sock.write(struct.pack("!H", len(s))) @@ -43,9 +45,15 @@ class MQTTClient: msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0") msg[1] = 10 + 2 + len(self.client_id) msg[9] = clean_session << 1 + if self.user is not None: + msg[1] += 2 + len(self.user) + 2 + len(self.pswd) + msg[9] |= 0xC0 self.sock.write(msg) #print(hex(len(msg)), hexlify(msg, ":")) self._send_str(self.client_id) + if self.user is not None: + self._send_str(self.user) + self._send_str(self.pswd) resp = self.sock.read(4) assert resp[0] == 0x20 and resp[1] == 0x02 if resp[3] != 0: