Skip to content

Commit fcec7f7

Browse files
ngrazianopfalcon
authored andcommitted
umqtt.simple: Add MQTT user/password authentication.
Limitation the total length of client id, user name and password must be under 111 characters.
1 parent 1aaaf0d commit fcec7f7

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

umqtt.simple/umqtt/simple.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class MQTTException(Exception):
77

88
class MQTTClient:
99

10-
def __init__(self, client_id, server, port=0, ssl=False):
10+
def __init__(self, client_id, server, port=0, user=None, password=None, ssl=False):
1111
if port == 0:
1212
port = 8883 if ssl else 1883
1313
self.client_id = client_id
@@ -16,6 +16,8 @@ def __init__(self, client_id, server, port=0, ssl=False):
1616
self.ssl = ssl
1717
self.pid = 0
1818
self.cb = None
19+
self.user = user
20+
self.pswd = password
1921

2022
def _send_str(self, s):
2123
self.sock.write(struct.pack("!H", len(s)))
@@ -43,9 +45,15 @@ def connect(self, clean_session=True):
4345
msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
4446
msg[1] = 10 + 2 + len(self.client_id)
4547
msg[9] = clean_session << 1
48+
if self.user is not None:
49+
msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
50+
msg[9] |= 0xC0
4651
self.sock.write(msg)
4752
#print(hex(len(msg)), hexlify(msg, ":"))
4853
self._send_str(self.client_id)
54+
if self.user is not None:
55+
self._send_str(self.user)
56+
self._send_str(self.pswd)
4957
resp = self.sock.read(4)
5058
assert resp[0] == 0x20 and resp[1] == 0x02
5159
if resp[3] != 0:

0 commit comments

Comments
 (0)