-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathmqtt5.py
More file actions
2092 lines (1676 loc) · 93.3 KB
/
mqtt5.py
File metadata and controls
2092 lines (1676 loc) · 93.3 KB
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
"""
MQTT5
"""
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
from typing import Any, Callable, Union
import _awscrt
from concurrent.futures import Future
from enum import IntEnum
from awscrt import NativeResource, exceptions
from awscrt.http import HttpProxyOptions, HttpRequest
from awscrt.io import ClientBootstrap, SocketOptions, ClientTlsContext
from dataclasses import dataclass
from collections.abc import Sequence
from inspect import signature
# Global variable to cache metrics string
_sdk_str = None
_platform_str = None
def _get_awsiot_metrics_str(current_username=""):
global _sdk_str
global _platform_str
_metrics_str = ""
if _sdk_str is None:
try:
import importlib.metadata
try:
version = importlib.metadata.version("awscrt")
_sdk_str = "SDK=CRTPython&Version={}".format(version)
except importlib.metadata.PackageNotFoundError:
_sdk_str = "SDK=CRTPython&Version=dev"
except BaseException:
_sdk_str = ""
if _platform_str is None:
_platform_str = "Platform={}".format(_awscrt.get_platform_build_os_string())
if current_username.find("SDK=") == -1:
_metrics_str += _sdk_str
if current_username.find("Platform=") == -1:
_metrics_str += ("&" if len(_metrics_str) > 0 else "") + _platform_str
if not _metrics_str == "":
if current_username.find("?") != -1:
return "&" + _metrics_str
else:
return "?" + _metrics_str
else:
return ""
class QoS(IntEnum):
"""MQTT message delivery quality of service.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901234>`__ encoding values.
"""
AT_MOST_ONCE = 0
"""
The message is delivered according to the capabilities of the underlying network. No response is sent by the
receiver and no retry is performed by the sender. The message arrives at the receiver either once or not at all.
"""
AT_LEAST_ONCE = 1
"""
A level of service that ensures that the message arrives at the receiver at least once.
"""
EXACTLY_ONCE = 2
"""
A level of service that ensures that the message arrives at the receiver exactly once.
Note that this client does not currently support QoS 2 as of (August 2022)
"""
def to_mqtt3(self):
from awscrt.mqtt import QoS as Mqtt3QoS
"""Convert a Mqtt5 QoS to Mqtt3
"""
return Mqtt3QoS(self.value)
def _try_qos(value):
try:
return QoS(value)
except Exception:
return None
class ConnectReasonCode(IntEnum):
"""Server return code for connect attempts.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901079>`__ encoding values.
"""
SUCCESS = 0
"""
Returned when the connection is accepted.
"""
UNSPECIFIED_ERROR = 128
"""
Returned when the server has a failure but does not want to specify a reason or none
of the other reason codes apply.
"""
MALFORMED_PACKET = 129
"""
Returned when data in the CONNECT packet could not be correctly parsed by the server.
"""
PROTOCOL_ERROR = 130
"""
Returned when data in the CONNECT packet does not conform to the MQTT5 specification requirements.
"""
IMPLEMENTATION_SPECIFIC_ERROR = 131
"""
Returned when the CONNECT packet is valid but was not accepted by the server.
"""
UNSUPPORTED_PROTOCOL_VERSION = 132
"""
Returned when the server does not support MQTT5 protocol version specified in the connection.
"""
CLIENT_IDENTIFIER_NOT_VALID = 133
"""
Returned when the client identifier in the CONNECT packet is a valid string but not one that
is allowed on the server.
"""
BAD_USERNAME_OR_PASSWORD = 134
"""
Returned when the server does not accept the username and/or password specified by the client
in the connection packet.
"""
NOT_AUTHORIZED = 135
"""
Returned when the client is not authorized to connect to the server.
"""
SERVER_UNAVAILABLE = 136
"""
Returned when the MQTT5 server is not available.
"""
SERVER_BUSY = 137
"""
Returned when the server is too busy to make a connection. It is recommended that the client try again later.
"""
BANNED = 138
"""
Returned when the client has been banned by the server.
"""
BAD_AUTHENTICATION_METHOD = 140
"""
Returned when the authentication method used in the connection is either not supported on the server or it does
not match the authentication method currently in use in the CONNECT packet.
"""
TOPIC_NAME_INVALID = 144
"""
Returned when the Will topic name sent in the CONNECT packet is correctly formed, but is not accepted by
the server.
"""
PACKET_TOO_LARGE = 149
"""
Returned when the CONNECT packet exceeded the maximum permissible size on the server.
"""
QUOTA_EXCEEDED = 151
"""
Returned when the quota limits set on the server have been met and/or exceeded.
"""
PAYLOAD_FORMAT_INVALID = 153
"""
Returned when the Will payload in the CONNECT packet does not match the specified payload format indicator.
"""
RETAIN_NOT_SUPPORTED = 154
"""
Returned when the server does not retain messages but the CONNECT packet on the client had Will retain enabled.
"""
QOS_NOT_SUPPORTED = 155
"""
Returned when the server does not support the QOS setting set in the Will QOS in the CONNECT packet.
"""
USE_ANOTHER_SERVER = 156
"""
Returned when the server is telling the client to temporarily use another server instead of the one they
are trying to connect to.
"""
SERVER_MOVED = 157
"""
Returned when the server is telling the client to permanently use another server instead of the one they
are trying to connect to.
"""
CONNECTION_RATE_EXCEEDED = 159
"""
Returned when the server connection rate limit has been exceeded.
"""
def _try_connect_reason_code(value):
try:
return ConnectReasonCode(value)
except Exception:
return None
class DisconnectReasonCode(IntEnum):
"""Reason code inside DISCONNECT packets. Helps determine why a connection was terminated.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901208>`__ encoding values.
"""
NORMAL_DISCONNECTION = 0
"""
Returned when the remote endpoint wishes to disconnect normally. Will not trigger the publish of a Will message if a
Will message was configured on the connection.
May be sent by the client or server.
"""
DISCONNECT_WITH_WILL_MESSAGE = 4
"""
Returns when the client wants to disconnect but requires that the server publish the Will message configured
on the connection.
May only be sent by the client.
"""
UNSPECIFIED_ERROR = 128
"""
Returned when the connection was closed but the sender does not want to specify a reason or none
of the other reason codes apply.
May be sent by the client or the server.
"""
MALFORMED_PACKET = 129
"""
Indicates the remote endpoint received a packet that does not conform to the MQTT specification.
May be sent by the client or the server.
"""
PROTOCOL_ERROR = 130
"""
Returned when an unexpected or out-of-order packet was received by the remote endpoint.
May be sent by the client or the server.
"""
IMPLEMENTATION_SPECIFIC_ERROR = 131
"""
Returned when a valid packet was received by the remote endpoint, but could not be processed by the current implementation.
May be sent by the client or the server.
"""
NOT_AUTHORIZED = 135
"""
Returned when the remote endpoint received a packet that represented an operation that was not authorized within
the current connection.
May only be sent by the server.
"""
SERVER_BUSY = 137
"""
Returned when the server is busy and cannot continue processing packets from the client.
May only be sent by the server.
"""
SERVER_SHUTTING_DOWN = 139
"""
Returned when the server is shutting down.
May only be sent by the server.
"""
KEEP_ALIVE_TIMEOUT = 141
"""
Returned when the server closes the connection because no packet from the client has been received in
1.5 times the KeepAlive time set when the connection was established.
May only be sent by the server.
"""
SESSION_TAKEN_OVER = 142
"""
Returned when the server has established another connection with the same client ID as a client's current
connection, causing the current client to become disconnected.
May only be sent by the server.
"""
TOPIC_FILTER_INVALID = 143
"""
Returned when the topic filter name is correctly formed but not accepted by the server.
May only be sent by the server.
"""
TOPIC_NAME_INVALID = 144
"""
Returned when topic name is correctly formed, but is not accepted.
May be sent by the client or the server.
"""
RECEIVE_MAXIMUM_EXCEEDED = 147
"""
Returned when the remote endpoint reached a state where there were more in-progress QoS1+ publishes then the
limit it established for itself when the connection was opened.
May be sent by the client or the server.
"""
TOPIC_ALIAS_INVALID = 148
"""
Returned when the remote endpoint receives a PUBLISH packet that contained a topic alias greater than the
maximum topic alias limit that it established for itself when the connection was opened.
May be sent by the client or the server.
"""
PACKET_TOO_LARGE = 149
"""
Returned when the remote endpoint received a packet whose size was greater than the maximum packet size limit
it established for itself when the connection was opened.
May be sent by the client or the server.
"""
MESSAGE_RATE_TOO_HIGH = 150
"""
Returned when the remote endpoint's incoming data rate was too high.
May be sent by the client or the server.
"""
QUOTA_EXCEEDED = 151
"""
Returned when an internal quota of the remote endpoint was exceeded.
May be sent by the client or the server.
"""
ADMINISTRATIVE_ACTION = 152
"""
Returned when the connection was closed due to an administrative action.
May be sent by the client or the server.
"""
PAYLOAD_FORMAT_INVALID = 153
"""
Returned when the remote endpoint received a packet where payload format did not match the format specified
by the payload format indicator.
May be sent by the client or the server.
"""
RETAIN_NOT_SUPPORTED = 154
"""
Returned when the server does not support retained messages.
May only be sent by the server.
"""
QOS_NOT_SUPPORTED = 155
"""
Returned when the client sends a QoS that is greater than the maximum QoS established when the connection was
opened.
May only be sent by the server.
"""
USE_ANOTHER_SERVER = 156
"""
Returned by the server to tell the client to temporarily use a different server.
May only be sent by the server.
"""
SERVER_MOVED = 157
"""
Returned by the server to tell the client to permanently use a different server.
May only be sent by the server.
"""
SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158
"""
Returned by the server to tell the client that shared subscriptions are not supported on the server.
May only be sent by the server.
"""
CONNECTION_RATE_EXCEEDED = 159
"""
Returned when the server disconnects the client due to the connection rate being too high.
May only be sent by the server.
"""
MAXIMUM_CONNECT_TIME = 160
"""
Returned by the server when the maximum connection time authorized for the connection was exceeded.
May only be sent by the server.
"""
SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161
"""
Returned by the server when it received a SUBSCRIBE packet with a subscription identifier, but the server does
not support subscription identifiers.
May only be sent by the server.
"""
WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
"""
Returned by the server when it received a SUBSCRIBE packet with a wildcard topic filter, but the server does
not support wildcard topic filters.
May only be sent by the server.
"""
def _try_disconnect_reason_code(value):
try:
return DisconnectReasonCode(value)
except Exception:
return None
class PubackReasonCode(IntEnum):
"""Reason code inside PUBACK packets that indicates the result of the associated PUBLISH request.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901124>`__ encoding values.
"""
SUCCESS = 0
"""
Returned when the (QoS 1) publish was accepted by the recipient.
May be sent by the client or the server.
"""
NO_MATCHING_SUBSCRIBERS = 16
"""
Returned when the (QoS 1) publish was accepted but there were no matching subscribers.
May only be sent by the server.
"""
UNSPECIFIED_ERROR = 128
"""
Returned when the (QoS 1) publish was not accepted and the receiver does not want to specify a reason or none
of the other reason codes apply.
May be sent by the client or the server.
"""
IMPLEMENTATION_SPECIFIC_ERROR = 131
"""
Returned when the (QoS 1) publish was valid but the receiver was not willing to accept it.
May be sent by the client or the server.
"""
NOT_AUTHORIZED = 135
"""
Returned when the (QoS 1) publish was not authorized by the receiver.
May be sent by the client or the server.
"""
TOPIC_NAME_INVALID = 144
"""
Returned when the topic name was valid but the receiver was not willing to accept it.
May be sent by the client or the server.
"""
PACKET_IDENTIFIER_IN_USE = 145
"""
Returned when the packet identifier used in the associated PUBLISH was already in use.
This can indicate a mismatch in the session state between client and server.
May be sent by the client or the server.
"""
QUOTA_EXCEEDED = 151
"""
Returned when the associated PUBLISH failed because an internal quota on the recipient was exceeded.
May be sent by the client or the server.
"""
PAYLOAD_FORMAT_INVALID = 153
"""
Returned when the PUBLISH packet's payload format did not match its payload format indicator property.
May be sent by the client or the server.
"""
def _try_puback_reason_code(value):
try:
return PubackReasonCode(value)
except Exception:
return None
class SubackReasonCode(IntEnum):
"""Reason code inside SUBACK packet payloads.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901178>`__ encoding values.
This will only be sent by the server and not the client.
"""
GRANTED_QOS_0 = 0
"""
Returned when the subscription was accepted and the maximum QoS sent will be QoS 0.
"""
GRANTED_QOS_1 = 1
"""
Returned when the subscription was accepted and the maximum QoS sent will be QoS 1.
"""
GRANTED_QOS_2 = 2
"""
Returned when the subscription was accepted and the maximum QoS sent will be QoS 2.
"""
UNSPECIFIED_ERROR = 128
"""
Returned when the connection was closed but the sender does not want to specify a reason or none
of the other reason codes apply.
"""
IMPLEMENTATION_SPECIFIC_ERROR = 131
"""
Returned when the subscription was valid but the server did not accept it.
"""
NOT_AUTHORIZED = 135
"""
Returned when the client was not authorized to make the subscription on the server.
"""
TOPIC_FILTER_INVALID = 143
"""
Returned when the subscription topic filter was correctly formed but not allowed for the client.
"""
PACKET_IDENTIFIER_IN_USE = 145
"""
Returned when the packet identifier was already in use on the server.
"""
QUOTA_EXCEEDED = 151
"""
Returned when a subscribe-related quota set on the server was exceeded.
"""
SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158
"""
Returned when the subscription's topic filter was a shared subscription and the server does not support
shared subscriptions.
"""
SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161
"""
Returned when the SUBSCRIBE packet contained a subscription identifier and the server does not support
subscription identifiers.
"""
WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
"""
Returned when the subscription's topic filter contains a wildcard but the server does not support
wildcard subscriptions.
"""
def _try_suback_reason_code(value):
try:
return SubackReasonCode(value)
except Exception:
return None
class UnsubackReasonCode(IntEnum):
"""Reason codes inside UNSUBACK packet payloads that specify the results for each topic filter in the associated
UNSUBSCRIBE packet.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194>`__ encoding values.
"""
SUCCESS = 0
"""
Returned when the unsubscribe was successful and the client is no longer subscribed to the topic filter on the server.
"""
NO_SUBSCRIPTION_EXISTED = 17
"""
Returned when the topic filter did not match one of the client's existing topic filters on the server.
"""
UNSPECIFIED_ERROR = 128
"""
Returned when the unsubscribe of the topic filter was not accepted and the server does not want to specify a
reason or none of the other reason codes apply.
"""
IMPLEMENTATION_SPECIFIC_ERROR = 131
"""
Returned when the topic filter was valid but the server does not accept an unsubscribe for it.
"""
NOT_AUTHORIZED = 135
"""
Returned when the client was not authorized to unsubscribe from that topic filter on the server.
"""
TOPIC_FILTER_INVALID = 143
"""
Returned when the topic filter was correctly formed but is not allowed for the client on the server.
"""
PACKET_IDENTIFIER_IN_USE = 145
"""
Returned when the packet identifier was already in use on the server.
"""
def _try_unsuback_reason_code(value):
try:
return UnsubackReasonCode(value)
except Exception:
return None
class ClientSessionBehaviorType(IntEnum):
"""Controls how the mqtt client should behave with respect to MQTT sessions.
"""
DEFAULT = 0
"""
Default client session behavior. Maps to CLEAN.
"""
CLEAN = 1
"""
Always ask for a clean session when connecting
"""
REJOIN_POST_SUCCESS = 2
"""
Always attempt to rejoin an existing session after an initial connection success.
Session rejoin requires an appropriate non-zero session expiry interval in the client's CONNECT options.
"""
REJOIN_ALWAYS = 3
"""
Always attempt to rejoin an existing session. Since the client does not support durable session persistence,
this option is not guaranteed to be spec compliant because any unacknowledged qos1 publishes (which are
part of the client session state) will not be present on the initial connection. Until we support
durable session resumption, this option is technically spec-breaking, but useful.
Always rejoin requires an appropriate non-zero session expiry interval in the client's CONNECT options.
"""
class PayloadFormatIndicator(IntEnum):
"""Optional property describing a PUBLISH payload's format.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901111>`__ encoding values.
"""
AWS_MQTT5_PFI_BYTES = 0
"""
The payload is arbitrary binary data
"""
AWS_MQTT5_PFI_UTF8 = 1
"""
The payload is a well-formed utf-8 string value.
"""
def _try_payload_format_indicator(value):
try:
return PayloadFormatIndicator(value)
except Exception:
return None
class RetainHandlingType(IntEnum):
"""Configures how retained messages should be handled when subscribing with a topic filter that matches topics with
associated retained messages.
Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901169>`_ encoding values.
"""
SEND_ON_SUBSCRIBE = 0
"""
The server should always send all retained messages on topics that match a subscription's filter.
"""
SEND_ON_SUBSCRIBE_IF_NEW = 1
"""
The server should send retained messages on topics that match the subscription's filter, but only for the
first matching subscription, per session.
"""
DONT_SEND = 2
"""
Subscriptions must not trigger any retained message publishes from the server.
"""
class RetainAndHandlingType(IntEnum):
"""DEPRECATED.
`RetainAndHandlingType` is deprecated, please use `RetainHandlingType`
"""
SEND_ON_SUBSCRIBE = 0
"""
The server should always send all retained messages on topics that match a subscription's filter.
"""
SEND_ON_SUBSCRIBE_IF_NEW = 1
"""
The server should send retained messages on topics that match the subscription's filter, but only for the
first matching subscription, per session.
"""
DONT_SEND = 2
"""
Subscriptions must not trigger any retained message publishes from the server.
"""
class ExtendedValidationAndFlowControlOptions(IntEnum):
"""Additional controls for client behavior with respect to operation validation and flow control; these checks
go beyond the MQTT5 spec to respect limits of specific MQTT brokers.
"""
NONE = 0
"""
Do not do any additional validation or flow control
"""
AWS_IOT_CORE_DEFAULTS = 1
"""
Apply additional client-side validation and operational flow control that respects the
default AWS IoT Core limits.
Currently applies the following additional validation:
* No more than 8 subscriptions per SUBSCRIBE packet
* Topics and topic filters have a maximum of 7 slashes (8 segments), not counting any AWS rules prefix
* Topics must be 256 bytes or less in length
* Client id must be 128 or less bytes in length
Also applies the following flow control:
* Outbound throughput throttled to 512KB/s
* Outbound publish TPS throttled to 100
"""
class ClientOperationQueueBehaviorType(IntEnum):
"""Controls how disconnects affect the queued and in-progress operations tracked by the client. Also controls
how operations are handled while the client is not connected. In particular, if the client is not connected,
then any operation that would be failed on disconnect (according to these rules) will be rejected.
"""
DEFAULT = 0
"""
Default client operation queue behavior. Maps to FAIL_QOS0_PUBLISH_ON_DISCONNECT.
"""
FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT = 1
"""
Re-queues QoS 1+ publishes on disconnect; un-acked publishes go to the front while unprocessed publishes stay
in place. All other operations (QoS 0 publishes, subscribe, unsubscribe) are failed.
"""
FAIL_QOS0_PUBLISH_ON_DISCONNECT = 2
"""
QoS 0 publishes that are not complete at the time of disconnection are failed. Un-acked QoS 1+ publishes are
re-queued at the head of the line for immediate retransmission on a session resumption. All other operations
are requeued in original order behind any retransmissions.
"""
FAIL_ALL_ON_DISCONNECT = 3
"""
All operations that are not complete at the time of disconnection are failed, except operations that
the MQTT5 spec requires to be retransmitted (un-acked QoS1+ publishes).
"""
class ExponentialBackoffJitterMode(IntEnum):
"""Controls how the reconnect delay is modified in order to smooth out the distribution of reconnection attempt
timepoints for a large set of reconnecting clients.
See `Exponential Backoff and Jitter <https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/>`_
"""
DEFAULT = 0
"""
Maps to Full
"""
NONE = 1
"""
Do not perform any randomization on the reconnect delay
"""
FULL = 2
"""
Fully random between no delay and the current exponential backoff value.
"""
DECORRELATED = 3
"""
Backoff is taken randomly from the interval between the base backoff
interval and a scaling (greater than 1) of the current backoff value
"""
@dataclass
class UserProperty:
"""MQTT5 User Property
Args:
name (str): Property name
value (str): Property value
"""
name: str = None
value: str = None
def _init_user_properties(user_properties_tuples):
if user_properties_tuples is None:
return None
return [UserProperty(name=name, value=value) for (name, value) in user_properties_tuples]
class OutboundTopicAliasBehaviorType(IntEnum):
"""An enumeration that controls how the client applies topic aliasing to outbound publish packets.
Topic alias behavior is described in `MQTT5 Topic Aliasing <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901113>`_
"""
DEFAULT = 0,
"""Maps to Disabled. This keeps the client from being broken (by default) if the broker
topic aliasing implementation has a problem.
"""
MANUAL = 1,
"""
Outbound aliasing is the user's responsibility. Client will cache and use
previously-established aliases if they fall within the negotiated limits of the connection.
The user must still always submit a full topic in their publishes because disconnections disrupt
topic alias mappings unpredictably. The client will properly use a requested alias when the most-recently-seen
binding for a topic alias value matches the alias and topic in the publish packet.
"""
LRU = 2,
""" (Recommended) The client will ignore any user-specified topic aliasing and instead use an LRU cache to drive
alias usage.
"""
DISABLED = 3,
"""Completely disable outbound topic aliasing."""
class InboundTopicAliasBehaviorType(IntEnum):
"""An enumeration that controls whether or not the client allows the broker to send publishes that use topic
aliasing.
Topic alias behavior is described in `MQTT5 Topic Aliasing <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901113>`_
"""
DEFAULT = 0,
"""Maps to Disabled. This keeps the client from being broken (by default) if the broker
topic aliasing implementation has a problem.
"""
ENABLED = 1,
"""Allow the server to send PUBLISH packets to the client that use topic aliasing"""
DISABLED = 2,
"""Forbid the server from sending PUBLISH packets to the client that use topic aliasing"""
@dataclass
class TopicAliasingOptions:
"""
Configuration for all client topic aliasing behavior.
Args:
outbound_behavior (OutboundTopicAliasBehaviorType): Controls what kind of outbound topic aliasing behavior the client should attempt to use. If topic aliasing is not supported by the server, this setting has no effect and any attempts to directly manipulate the topic alias id in outbound publishes will be ignored. If left undefined, then outbound topic aliasing is disabled.
outbound_cache_max_size (int): If outbound topic aliasing is set to LRU, this controls the maximum size of the cache. If outbound topic aliasing is set to LRU and this is zero or undefined, a sensible default is used (25). If outbound topic aliasing is not set to LRU, then this setting has no effect.
inbound_behavior (InboundTopicAliasBehaviorType): Controls whether or not the client allows the broker to use topic aliasing when sending publishes. Even if inbound topic aliasing is enabled, it is up to the server to choose whether or not to use it. If left undefined, then inbound topic aliasing is disabled.
inbound_cache_max_size (int): If inbound topic aliasing is enabled, this will control the size of the inbound alias cache. If inbound aliases are enabled and this is zero or undefined, then a sensible default will be used (25). If inbound aliases are disabled, this setting has no effect. Behaviorally, this value overrides anything present in the topic_alias_maximum field of the CONNECT packet options.
"""
outbound_behavior: OutboundTopicAliasBehaviorType = None
outbound_cache_max_size: int = None
inbound_behavior: InboundTopicAliasBehaviorType = None
inbound_cache_max_size: int = None
@dataclass
class NegotiatedSettings:
"""
Mqtt behavior settings that are dynamically negotiated as part of the CONNECT/CONNACK exchange.
While you can infer all of these values from a combination of:
- defaults as specified in the mqtt5 spec
- your CONNECT settings
- the CONNACK from the broker
the client instead does the combining for you and emits a NegotiatedSettings object with final, authoritative values.
Negotiated settings are communicated with every successful connection establishment.
Args:
maximum_qos (QoS): The maximum QoS allowed for publishes on this connection instance
session_expiry_interval_sec (int): The amount of time in seconds the server will retain the MQTT session after a disconnect.
receive_maximum_from_server (int): The number of in-flight QoS 1 and QoS 2 publications the server is willing to process concurrently.
maximum_packet_size_to_server (int): The maximum packet size the server is willing to accept.
topic_alias_maximum_to_server (int): the maximum allowed topic alias value on publishes sent from client to server
topic_alias_maximum_to_client (int): the maximum allowed topic alias value on publishes sent from server to client
server_keep_alive_sec (int): The maximum amount of time in seconds between client packets. The client will use PINGREQs to ensure this limit is not breached. The server will disconnect the client for inactivity if no MQTT packet is received in a time interval equal to 1.5 x this value.
retain_available (bool): Whether the server supports retained messages.
wildcard_subscriptions_available (bool): Whether the server supports wildcard subscriptions.
subscription_identifiers_available (bool): Whether the server supports subscription identifiers
shared_subscriptions_available (bool): Whether the server supports shared subscriptions
rejoined_session (bool): Whether the client has rejoined an existing session.
client_id (str): The final client id in use by the newly-established connection. This will be the configured client id if one was given in the configuration, otherwise, if no client id was specified, this will be the client id assigned by the server. Reconnection attempts will always use the auto-assigned client id, allowing for auto-assigned session resumption.
"""
maximum_qos: QoS = None
session_expiry_interval_sec: int = None
receive_maximum_from_server: int = None
maximum_packet_size_to_server: int = None
topic_alias_maximum_to_server: int = None
topic_alias_maximum_to_client: int = None
server_keep_alive_sec: int = None
retain_available: bool = None
wildcard_subscriptions_available: bool = None
subscription_identifiers_available: bool = None
shared_subscriptions_available: bool = None
rejoined_session: bool = None
client_id: str = None
@dataclass
class ConnackPacket:
"""Data model of an `MQTT5 CONNACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074>`_ packet.
Args:
session_present (bool): True if the client rejoined an existing session on the server, false otherwise.
reason_code (ConnectReasonCode): Indicates either success or the reason for failure for the connection attempt.
session_expiry_interval_sec (int): A time interval, in seconds, that the server will persist this connection's MQTT session state for. If present, this value overrides any session expiry specified in the preceding CONNECT packet.
receive_maximum (int): The maximum amount of in-flight QoS 1 or 2 messages that the server is willing to handle at once. If omitted or None, the limit is based on the valid MQTT packet id space (65535).
maximum_qos (QoS): The maximum message delivery quality of service that the server will allow on this connection.
retain_available (bool): Indicates whether the server supports retained messages. If None, retained messages are supported.
maximum_packet_size (int): Specifies the maximum packet size, in bytes, that the server is willing to accept. If None, there is no limit beyond what is imposed by the MQTT spec itself.