@@ -7,7 +7,7 @@ class MQTTException(Exception):
7
7
8
8
class MQTTClient :
9
9
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 ):
11
11
if port == 0 :
12
12
port = 8883 if ssl else 1883
13
13
self .client_id = client_id
@@ -16,6 +16,8 @@ def __init__(self, client_id, server, port=0, ssl=False):
16
16
self .ssl = ssl
17
17
self .pid = 0
18
18
self .cb = None
19
+ self .user = user
20
+ self .pswd = password
19
21
20
22
def _send_str (self , s ):
21
23
self .sock .write (struct .pack ("!H" , len (s )))
@@ -43,9 +45,15 @@ def connect(self, clean_session=True):
43
45
msg = bytearray (b"\x10 \0 \0 \x04 MQTT\x04 \x02 \0 \0 " )
44
46
msg [1 ] = 10 + 2 + len (self .client_id )
45
47
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
46
51
self .sock .write (msg )
47
52
#print(hex(len(msg)), hexlify(msg, ":"))
48
53
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 )
49
57
resp = self .sock .read (4 )
50
58
assert resp [0 ] == 0x20 and resp [1 ] == 0x02
51
59
if resp [3 ] != 0 :
0 commit comments