forked from luxonis/depthai-experiments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaho-mqtt.py
5142 lines (4349 loc) · 186 KB
/
paho-mqtt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
*******************************************************************
Copyright (c) 2017, 2019 IBM Corp.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v2.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Ian Craggs - initial implementation and/or documentation
*******************************************************************
"""
import socket
import select
import os
import errno
import collections
import time
import threading
import string
import logging
import hashlib
import base64
import struct
class MQTTException(Exception):
pass
class MalformedPacket(MQTTException):
pass
def writeInt16(length):
# serialize a 16 bit integer to network format
return bytearray(struct.pack("!H", length))
def readInt16(buf):
# deserialize a 16 bit integer from network format
return struct.unpack("!H", buf[:2])[0]
def writeInt32(length):
# serialize a 32 bit integer to network format
return bytearray(struct.pack("!L", length))
def readInt32(buf):
# deserialize a 32 bit integer from network format
return struct.unpack("!L", buf[:4])[0]
def writeUTF(data):
# data could be a string, or bytes. If string, encode into bytes with utf-8
data = data if type(data) == type(b"") else bytes(data, "utf-8")
return writeInt16(len(data)) + data
def readUTF(buffer, maxlen):
if maxlen >= 2:
length = readInt16(buffer)
else:
raise MalformedPacket("Not enough data to read string length")
maxlen -= 2
if length > maxlen:
raise MalformedPacket("Length delimited string too long")
buf = buffer[2 : 2 + length].decode("utf-8")
# look for chars which are invalid for MQTT
for c in buf: # look for D800-DFFF in the UTF string
ord_c = ord(c)
if ord_c >= 0xD800 and ord_c <= 0xDFFF:
raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data")
if ord_c == 0x00: # look for null in the UTF string
raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data")
if ord_c == 0xFEFF:
raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data")
return buf, length + 2
def writeBytes(buffer):
return writeInt16(len(buffer)) + buffer
def readBytes(buffer):
length = readInt16(buffer)
return buffer[2 : 2 + length], length + 2
class VariableByteIntegers: # Variable Byte Integer
"""
MQTT variable byte integer helper class. Used
in several places in MQTT v5.0 properties.
"""
@staticmethod
def encode(x):
"""
Convert an integer 0 <= x <= 268435455 into multi-byte format.
Returns the buffer convered from the integer.
"""
assert 0 <= x <= 268435455
buffer = b""
while 1:
digit = x % 128
x //= 128
if x > 0:
digit |= 0x80
buffer += bytes([digit])
if x == 0:
break
return buffer
@staticmethod
def decode(buffer):
"""
Get the value of a multi-byte integer from a buffer
Return the value, and the number of bytes used.
[MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value
"""
multiplier = 1
value = 0
bytes = 0
while 1:
bytes += 1
digit = buffer[0]
buffer = buffer[1:]
value += (digit & 127) * multiplier
if digit & 128 == 0:
break
multiplier *= 128
return (value, bytes)
class Properties(object):
"""MQTT v5.0 properties class.
See Properties.names for a list of accepted property names along with their numeric values.
See Properties.properties for the data type of each property.
Example of use:
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.UserProperty = ("a", "2")
publish_properties.UserProperty = ("c", "3")
First the object is created with packet type as argument, no properties will be present at
this point. Then properties are added as attributes, the name of which is the string property
name without the spaces.
"""
def __init__(self, packetType):
self.packetType = packetType
self.types = [
"Byte",
"Two Byte Integer",
"Four Byte Integer",
"Variable Byte Integer",
"Binary Data",
"UTF-8 Encoded String",
"UTF-8 String Pair",
]
self.names = {
"Payload Format Indicator": 1,
"Message Expiry Interval": 2,
"Content Type": 3,
"Response Topic": 8,
"Correlation Data": 9,
"Subscription Identifier": 11,
"Session Expiry Interval": 17,
"Assigned Client Identifier": 18,
"Server Keep Alive": 19,
"Authentication Method": 21,
"Authentication Data": 22,
"Request Problem Information": 23,
"Will Delay Interval": 24,
"Request Response Information": 25,
"Response Information": 26,
"Server Reference": 28,
"Reason String": 31,
"Receive Maximum": 33,
"Topic Alias Maximum": 34,
"Topic Alias": 35,
"Maximum QoS": 36,
"Retain Available": 37,
"User Property": 38,
"Maximum Packet Size": 39,
"Wildcard Subscription Available": 40,
"Subscription Identifier Available": 41,
"Shared Subscription Available": 42,
}
self.properties = {
# id: type, packets
# payload format indicator
1: (
self.types.index("Byte"),
[PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE],
),
2: (
self.types.index("Four Byte Integer"),
[PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE],
),
3: (
self.types.index("UTF-8 Encoded String"),
[PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE],
),
8: (
self.types.index("UTF-8 Encoded String"),
[PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE],
),
9: (
self.types.index("Binary Data"),
[PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE],
),
11: (
self.types.index("Variable Byte Integer"),
[PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE],
),
17: (
self.types.index("Four Byte Integer"),
[PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT],
),
18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]),
19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]),
21: (
self.types.index("UTF-8 Encoded String"),
[PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH],
),
22: (
self.types.index("Binary Data"),
[PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH],
),
23: (self.types.index("Byte"), [PacketTypes.CONNECT]),
24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]),
25: (self.types.index("Byte"), [PacketTypes.CONNECT]),
26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]),
28: (
self.types.index("UTF-8 Encoded String"),
[PacketTypes.CONNACK, PacketTypes.DISCONNECT],
),
31: (
self.types.index("UTF-8 Encoded String"),
[
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.PUBREL,
PacketTypes.PUBCOMP,
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
PacketTypes.AUTH,
],
),
33: (
self.types.index("Two Byte Integer"),
[PacketTypes.CONNECT, PacketTypes.CONNACK],
),
34: (
self.types.index("Two Byte Integer"),
[PacketTypes.CONNECT, PacketTypes.CONNACK],
),
35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]),
36: (self.types.index("Byte"), [PacketTypes.CONNACK]),
37: (self.types.index("Byte"), [PacketTypes.CONNACK]),
38: (
self.types.index("UTF-8 String Pair"),
[
PacketTypes.CONNECT,
PacketTypes.CONNACK,
PacketTypes.PUBLISH,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.PUBREL,
PacketTypes.PUBCOMP,
PacketTypes.SUBSCRIBE,
PacketTypes.SUBACK,
PacketTypes.UNSUBSCRIBE,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
PacketTypes.AUTH,
PacketTypes.WILLMESSAGE,
],
),
39: (
self.types.index("Four Byte Integer"),
[PacketTypes.CONNECT, PacketTypes.CONNACK],
),
40: (self.types.index("Byte"), [PacketTypes.CONNACK]),
41: (self.types.index("Byte"), [PacketTypes.CONNACK]),
42: (self.types.index("Byte"), [PacketTypes.CONNACK]),
}
def allowsMultiple(self, compressedName):
return self.getIdentFromName(compressedName) in [11, 38]
def getIdentFromName(self, compressedName):
# return the identifier corresponding to the property name
result = -1
for name in self.names.keys():
if compressedName == name.replace(" ", ""):
result = self.names[name]
break
return result
def __setattr__(self, name, value):
name = name.replace(" ", "")
privateVars = ["packetType", "types", "names", "properties"]
if name in privateVars:
object.__setattr__(self, name, value)
else:
# the name could have spaces in, or not. Remove spaces before assignment
if name not in [aname.replace(" ", "") for aname in self.names.keys()]:
raise MQTTException(
"Property name must be one of " + str(self.names.keys())
)
# check that this attribute applies to the packet type
if self.packetType not in self.properties[self.getIdentFromName(name)][1]:
raise MQTTException(
"Property %s does not apply to packet type %s"
% (name, PacketTypes.Names[self.packetType])
)
# Check for forbidden values
if type(value) != type([]):
if name in ["ReceiveMaximum", "TopicAlias"] and (
value < 1 or value > 65535
):
raise MQTTException(
"%s property value must be in the range 1-65535" % (name)
)
elif name in ["TopicAliasMaximum"] and (value < 0 or value > 65535):
raise MQTTException(
"%s property value must be in the range 0-65535" % (name)
)
elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] and (
value < 1 or value > 268435455
):
raise MQTTException(
"%s property value must be in the range 1-268435455" % (name)
)
elif name in [
"RequestResponseInformation",
"RequestProblemInformation",
"PayloadFormatIndicator",
] and (value != 0 and value != 1):
raise MQTTException("%s property value must be 0 or 1" % (name))
if self.allowsMultiple(name):
if type(value) != type([]):
value = [value]
if hasattr(self, name):
value = object.__getattribute__(self, name) + value
object.__setattr__(self, name, value)
def __str__(self):
buffer = "["
first = True
for name in self.names.keys():
compressedName = name.replace(" ", "")
if hasattr(self, compressedName):
if not first:
buffer += ", "
buffer += compressedName + " : " + str(getattr(self, compressedName))
first = False
buffer += "]"
return buffer
def json(self):
data = {}
for name in self.names.keys():
compressedName = name.replace(" ", "")
if hasattr(self, compressedName):
val = getattr(self, compressedName)
if compressedName == "CorrelationData" and isinstance(val, bytes):
data[compressedName] = val.hex()
else:
data[compressedName] = val
return data
def isEmpty(self):
rc = True
for name in self.names.keys():
compressedName = name.replace(" ", "")
if hasattr(self, compressedName):
rc = False
break
return rc
def clear(self):
for name in self.names.keys():
compressedName = name.replace(" ", "")
if hasattr(self, compressedName):
delattr(self, compressedName)
def writeProperty(self, identifier, type, value):
buffer = b""
buffer += VariableByteIntegers.encode(identifier) # identifier
if type == self.types.index("Byte"): # value
buffer += bytes([value])
elif type == self.types.index("Two Byte Integer"):
buffer += writeInt16(value)
elif type == self.types.index("Four Byte Integer"):
buffer += writeInt32(value)
elif type == self.types.index("Variable Byte Integer"):
buffer += VariableByteIntegers.encode(value)
elif type == self.types.index("Binary Data"):
buffer += writeBytes(value)
elif type == self.types.index("UTF-8 Encoded String"):
buffer += writeUTF(value)
elif type == self.types.index("UTF-8 String Pair"):
buffer += writeUTF(value[0]) + writeUTF(value[1])
return buffer
def pack(self):
# serialize properties into buffer for sending over network
buffer = b""
for name in self.names.keys():
compressedName = name.replace(" ", "")
if hasattr(self, compressedName):
identifier = self.getIdentFromName(compressedName)
attr_type = self.properties[identifier][0]
if self.allowsMultiple(compressedName):
for prop in getattr(self, compressedName):
buffer += self.writeProperty(identifier, attr_type, prop)
else:
buffer += self.writeProperty(
identifier, attr_type, getattr(self, compressedName)
)
return VariableByteIntegers.encode(len(buffer)) + buffer
def readProperty(self, buffer, type, propslen):
if type == self.types.index("Byte"):
value = buffer[0]
valuelen = 1
elif type == self.types.index("Two Byte Integer"):
value = readInt16(buffer)
valuelen = 2
elif type == self.types.index("Four Byte Integer"):
value = readInt32(buffer)
valuelen = 4
elif type == self.types.index("Variable Byte Integer"):
value, valuelen = VariableByteIntegers.decode(buffer)
elif type == self.types.index("Binary Data"):
value, valuelen = readBytes(buffer)
elif type == self.types.index("UTF-8 Encoded String"):
value, valuelen = readUTF(buffer, propslen)
elif type == self.types.index("UTF-8 String Pair"):
value, valuelen = readUTF(buffer, propslen)
buffer = buffer[valuelen:] # strip the bytes used by the value
value1, valuelen1 = readUTF(buffer, propslen - valuelen)
value = (value, value1)
valuelen += valuelen1
return value, valuelen
def getNameFromIdent(self, identifier):
rc = None
for name in self.names:
if self.names[name] == identifier:
rc = name
return rc
def unpack(self, buffer):
self.clear()
# deserialize properties into attributes from buffer received from network
propslen, VBIlen = VariableByteIntegers.decode(buffer)
buffer = buffer[VBIlen:] # strip the bytes used by the VBI
propslenleft = propslen
while propslenleft > 0: # properties length is 0 if there are none
identifier, VBIlen2 = VariableByteIntegers.decode(
buffer
) # property identifier
buffer = buffer[VBIlen2:] # strip the bytes used by the VBI
propslenleft -= VBIlen2
attr_type = self.properties[identifier][0]
value, valuelen = self.readProperty(buffer, attr_type, propslenleft)
buffer = buffer[valuelen:] # strip the bytes used by the value
propslenleft -= valuelen
propname = self.getNameFromIdent(identifier)
compressedName = propname.replace(" ", "")
if not self.allowsMultiple(compressedName) and hasattr(
self, compressedName
):
raise MQTTException(
"Property '%s' must not exist more than once" % property
)
setattr(self, propname, value)
return self, propslen + VBIlen
class PacketTypes:
"""
Packet types class. Includes the AUTH packet for MQTT v5.0.
Holds constants for each packet type such as PacketTypes.PUBLISH
and packet name strings: PacketTypes.Names[PacketTypes.PUBLISH].
"""
indexes = range(1, 16)
# Packet types
(
CONNECT,
CONNACK,
PUBLISH,
PUBACK,
PUBREC,
PUBREL,
PUBCOMP,
SUBSCRIBE,
SUBACK,
UNSUBSCRIBE,
UNSUBACK,
PINGREQ,
PINGRESP,
DISCONNECT,
AUTH,
) = indexes
# Dummy packet type for properties use - will delay only applies to will
WILLMESSAGE = 99
Names = [
"reserved",
"Connect",
"Connack",
"Publish",
"Puback",
"Pubrec",
"Pubrel",
"Pubcomp",
"Subscribe",
"Suback",
"Unsubscribe",
"Unsuback",
"Pingreq",
"Pingresp",
"Disconnect",
"Auth",
]
class MQTTMatcher(object):
"""Intended to manage topic filters including wildcards.
Internally, MQTTMatcher use a prefix tree (trie) to store
values associated with filters, and has an iter_match()
method to iterate efficiently over all filters that match
some topic name."""
class Node(object):
__slots__ = "_children", "_content"
def __init__(self):
self._children = {}
self._content = None
def __init__(self):
self._root = self.Node()
def __setitem__(self, key, value):
"""Add a topic filter :key to the prefix tree
and associate it to :value"""
node = self._root
for sym in key.split("/"):
node = node._children.setdefault(sym, self.Node())
node._content = value
def __getitem__(self, key):
"""Retrieve the value associated with some topic filter :key"""
try:
node = self._root
for sym in key.split("/"):
node = node._children[sym]
if node._content is None:
raise KeyError(key)
return node._content
except KeyError:
raise KeyError(key)
def __delitem__(self, key):
"""Delete the value associated with some topic filter :key"""
lst = []
try:
parent, node = None, self._root
for k in key.split("/"):
parent, node = node, node._children[k]
lst.append((parent, k, node))
# TODO
node._content = None
except KeyError:
raise KeyError(key)
else: # cleanup
for parent, k, node in reversed(lst):
if node._children or node._content is not None:
break
del parent._children[k]
def iter_match(self, topic):
"""Return an iterator on all values associated with filters
that match the :topic"""
lst = topic.split("/")
normal = not topic.startswith("$")
def rec(node, i=0):
if i == len(lst):
if node._content is not None:
yield node._content
else:
part = lst[i]
if part in node._children:
for content in rec(node._children[part], i + 1):
yield content
if "+" in node._children and (normal or i > 0):
for content in rec(node._children["+"], i + 1):
yield content
if "#" in node._children and (normal or i > 0):
content = node._children["#"]._content
if content is not None:
yield content
return rec(self._root)
class ReasonCodes:
"""MQTT version 5.0 reason codes class.
See ReasonCodes.names for a list of possible numeric values along with their
names and the packets to which they apply.
"""
def __init__(self, packetType, aName="Success", identifier=-1):
"""
packetType: the type of the packet, such as PacketTypes.CONNECT that
this reason code will be used with. Some reason codes have different
names for the same identifier when used a different packet type.
aName: the String name of the reason code to be created. Ignored
if the identifier is set.
identifier: an integer value of the reason code to be created.
"""
self.packetType = packetType
self.names = {
0: {
"Success": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.PUBREL,
PacketTypes.PUBCOMP,
PacketTypes.UNSUBACK,
PacketTypes.AUTH,
],
"Normal disconnection": [PacketTypes.DISCONNECT],
"Granted QoS 0": [PacketTypes.SUBACK],
},
1: {"Granted QoS 1": [PacketTypes.SUBACK]},
2: {"Granted QoS 2": [PacketTypes.SUBACK]},
4: {"Disconnect with will message": [PacketTypes.DISCONNECT]},
16: {"No matching subscribers": [PacketTypes.PUBACK, PacketTypes.PUBREC]},
17: {"No subscription found": [PacketTypes.UNSUBACK]},
24: {"Continue authentication": [PacketTypes.AUTH]},
25: {"Re-authenticate": [PacketTypes.AUTH]},
128: {
"Unspecified error": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
],
},
129: {"Malformed packet": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
130: {"Protocol error": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
131: {
"Implementation specific error": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
],
},
132: {"Unsupported protocol version": [PacketTypes.CONNACK]},
133: {"Client identifier not valid": [PacketTypes.CONNACK]},
134: {"Bad user name or password": [PacketTypes.CONNACK]},
135: {
"Not authorized": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
],
},
136: {"Server unavailable": [PacketTypes.CONNACK]},
137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
138: {"Banned": [PacketTypes.CONNACK]},
139: {"Server shutting down": [PacketTypes.DISCONNECT]},
140: {
"Bad authentication method": [
PacketTypes.CONNACK,
PacketTypes.DISCONNECT,
]
},
141: {"Keep alive timeout": [PacketTypes.DISCONNECT]},
142: {"Session taken over": [PacketTypes.DISCONNECT]},
143: {
"Topic filter invalid": [
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
PacketTypes.DISCONNECT,
]
},
144: {
"Topic name invalid": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.DISCONNECT,
]
},
145: {
"Packet identifier in use": [
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.SUBACK,
PacketTypes.UNSUBACK,
]
},
146: {
"Packet identifier not found": [PacketTypes.PUBREL, PacketTypes.PUBCOMP]
},
147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]},
148: {"Topic alias invalid": [PacketTypes.DISCONNECT]},
149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
150: {"Message rate too high": [PacketTypes.DISCONNECT]},
151: {
"Quota exceeded": [
PacketTypes.CONNACK,
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.SUBACK,
PacketTypes.DISCONNECT,
],
},
152: {"Administrative action": [PacketTypes.DISCONNECT]},
153: {
"Payload format invalid": [
PacketTypes.PUBACK,
PacketTypes.PUBREC,
PacketTypes.DISCONNECT,
]
},
154: {
"Retain not supported": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]
},
155: {"QoS not supported": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
156: {"Use another server": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
157: {"Server moved": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
158: {
"Shared subscription not supported": [
PacketTypes.SUBACK,
PacketTypes.DISCONNECT,
]
},
159: {
"Connection rate exceeded": [
PacketTypes.CONNACK,
PacketTypes.DISCONNECT,
]
},
160: {"Maximum connect time": [PacketTypes.DISCONNECT]},
161: {
"Subscription identifiers not supported": [
PacketTypes.SUBACK,
PacketTypes.DISCONNECT,
]
},
162: {
"Wildcard subscription not supported": [
PacketTypes.SUBACK,
PacketTypes.DISCONNECT,
]
},
}
if identifier == -1:
if packetType == PacketTypes.DISCONNECT and aName == "Success":
aName = "Normal disconnection"
self.set(aName)
else:
self.value = identifier
self.getName() # check it's good
def __getName__(self, packetType, identifier):
"""
Get the reason code string name for a specific identifier.
The name can vary by packet type for the same identifier, which
is why the packet type is also required.
Used when displaying the reason code.
"""
assert identifier in self.names.keys(), identifier
names = self.names[identifier]
namelist = [name for name in names.keys() if packetType in names[name]]
assert len(namelist) == 1
return namelist[0]
def getId(self, name):
"""
Get the numeric id corresponding to a reason code name.
Used when setting the reason code for a packetType
check that only valid codes for the packet are set.
"""
identifier = None
for code in self.names.keys():
if name in self.names[code].keys():
if self.packetType in self.names[code][name]:
identifier = code
break
assert identifier is not None, name
return identifier
def set(self, name):
self.value = self.getId(name)
def unpack(self, buffer):
c = buffer[0]
name = self.__getName__(self.packetType, c)
self.value = self.getId(name)
return 1
def getName(self):
"""Returns the reason code name corresponding to the numeric value which is set."""
return self.__getName__(self.packetType, self.value)
def __eq__(self, other):
if isinstance(other, int):
return self.value == other
if isinstance(other, str):
return self.value == str(self)
if isinstance(other, ReasonCodes):
return self.value == other.value
return False
def __str__(self):
return self.getName()
def json(self):
return self.getName()
def pack(self):
return bytearray([self.value])
class MQTTException(Exception):
pass
class SubscribeOptions(object):
"""The MQTT v5.0 subscribe options class.
The options are:
qos: As in MQTT v3.1.1.
noLocal: True or False. If set to True, the subscriber will not receive its own publications.
retainAsPublished: True or False. If set to True, the retain flag on received publications will be as set
by the publisher.
retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND
Controls when the broker should send retained messages:
- RETAIN_SEND_ON_SUBSCRIBE: on any successful subscribe request
- RETAIN_SEND_IF_NEW_SUB: only if the subscribe request is new
- RETAIN_DO_NOT_SEND: never send retained messages
"""
# retain handling options
RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB, RETAIN_DO_NOT_SEND = range(0, 3)
def __init__(
self,
qos=0,
noLocal=False,
retainAsPublished=False,
retainHandling=RETAIN_SEND_ON_SUBSCRIBE,
):
"""
qos: 0, 1 or 2. 0 is the default.
noLocal: True or False. False is the default and corresponds to MQTT v3.1.1 behavior.
retainAsPublished: True or False. False is the default and corresponds to MQTT v3.1.1 behavior.
retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND
RETAIN_SEND_ON_SUBSCRIBE is the default and corresponds to MQTT v3.1.1 behavior.
"""
object.__setattr__(
self, "names", ["QoS", "noLocal", "retainAsPublished", "retainHandling"]
)
self.QoS = qos # bits 0,1
self.noLocal = noLocal # bit 2
self.retainAsPublished = retainAsPublished # bit 3
self.retainHandling = retainHandling # bits 4 and 5: 0, 1 or 2
assert self.QoS in [0, 1, 2]
assert self.retainHandling in [0, 1, 2], "Retain handling should be 0, 1 or 2"
def __setattr__(self, name, value):
if name not in self.names:
raise MQTTException(
name + " Attribute name must be one of " + str(self.names)
)
object.__setattr__(self, name, value)
def pack(self):
assert self.QoS in [0, 1, 2]
assert self.retainHandling in [0, 1, 2], "Retain handling should be 0, 1 or 2"
noLocal = 1 if self.noLocal else 0
retainAsPublished = 1 if self.retainAsPublished else 0
data = [
(self.retainHandling << 4)
| (retainAsPublished << 3)
| (noLocal << 2)
| self.QoS
]
buffer = bytes(data)
return buffer
def unpack(self, buffer):
b0 = buffer[0]
self.retainHandling = (b0 >> 4) & 0x03
self.retainAsPublished = True if ((b0 >> 3) & 0x01) == 1 else False
self.noLocal = True if ((b0 >> 2) & 0x01) == 1 else False
self.QoS = b0 & 0x03
assert self.retainHandling in [0, 1, 2], (
"Retain handling should be 0, 1 or 2, not %d" % self.retainHandling
)
assert self.QoS in [0, 1, 2], "QoS should be 0, 1 or 2, not %d" % self.QoS
return 1
def __repr__(self):
return str(self)
def __str__(self):
return (
"{QoS="
+ str(self.QoS)
+ ", noLocal="
+ str(self.noLocal)
+ ", retainAsPublished="
+ str(self.retainAsPublished)
+ ", retainHandling="
+ str(self.retainHandling)
+ "}"
)
def json(self):
data = {
"QoS": self.QoS,
"noLocal": self.noLocal,
"retainAsPublished": self.retainAsPublished,
"retainHandling": self.retainHandling,
}
return data
# Copyright (c) 2012-2019 Roger Light and others
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# http://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Roger Light - initial API and implementation
# Ian Craggs - MQTT V5 support
"""
This is an MQTT client module. MQTT is a lightweight pub/sub messaging
protocol that is easy to implement and suitable for low powered devices.
"""
ssl = None
try:
import ssl