Debian Codegraph @

awscrt/mqtt5.py

raw symbols SCIP
1 """
2 MQTT5
3
4 """
5
6 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7 # SPDX-License-Identifier: Apache-2.0.
8 from typing import Any, Callable, Optional, Union
9 import _awscrt
10 from concurrent.futures import Future
11 from enum import IntEnum
12 from awscrt import NativeResource, exceptions
13 from awscrt.http import HttpProxyOptions, HttpRequest
14 from awscrt.io import ClientBootstrap, SocketOptions, ClientTlsContext
15 from dataclasses import dataclass
16 from collections.abc import Sequence
17 from inspect import signature
18 from awscrt.aws_iot_metrics import AWSIoTMetrics, _create_metrics_mqtt5
19
20
21 class QoS(IntEnum):
22 """MQTT message delivery quality of service.
23
24 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901234>`__ encoding values.
25 """
26
27 AT_MOST_ONCE = 0
28 """
29 The message is delivered according to the capabilities of the underlying network. No response is sent by the
30 receiver and no retry is performed by the sender. The message arrives at the receiver either once or not at all.
31 """
32
33 AT_LEAST_ONCE = 1
34 """
35 A level of service that ensures that the message arrives at the receiver at least once.
36 """
37
38 EXACTLY_ONCE = 2
39 """
40 A level of service that ensures that the message arrives at the receiver exactly once.
41
42 Note that this client does not currently support QoS 2 as of (August 2022)
43 """
44
45 def to_mqtt3(self):
46 from awscrt.mqtt import QoS as Mqtt3QoS
47 """Convert a Mqtt5 QoS to Mqtt3
48
49 """
50 return Mqtt3QoS(self.value)
51
52
53 def _try_qos(value):
54 try:
55 return QoS(value)
56 except Exception:
57 return None
58
59
60 class ConnectReasonCode(IntEnum):
61 """Server return code for connect attempts.
62
63 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901079>`__ encoding values.
64 """
65
66 SUCCESS = 0
67 """
68 Returned when the connection is accepted.
69 """
70
71 UNSPECIFIED_ERROR = 128
72 """
73 Returned when the server has a failure but does not want to specify a reason or none
74 of the other reason codes apply.
75 """
76
77 MALFORMED_PACKET = 129
78 """
79 Returned when data in the CONNECT packet could not be correctly parsed by the server.
80 """
81
82 PROTOCOL_ERROR = 130
83 """
84 Returned when data in the CONNECT packet does not conform to the MQTT5 specification requirements.
85 """
86
87 IMPLEMENTATION_SPECIFIC_ERROR = 131
88 """
89 Returned when the CONNECT packet is valid but was not accepted by the server.
90 """
91
92 UNSUPPORTED_PROTOCOL_VERSION = 132
93 """
94 Returned when the server does not support MQTT5 protocol version specified in the connection.
95 """
96
97 CLIENT_IDENTIFIER_NOT_VALID = 133
98 """
99 Returned when the client identifier in the CONNECT packet is a valid string but not one that
100 is allowed on the server.
101 """
102
103 BAD_USERNAME_OR_PASSWORD = 134
104 """
105 Returned when the server does not accept the username and/or password specified by the client
106 in the connection packet.
107 """
108
109 NOT_AUTHORIZED = 135
110 """
111 Returned when the client is not authorized to connect to the server.
112 """
113
114 SERVER_UNAVAILABLE = 136
115 """
116 Returned when the MQTT5 server is not available.
117 """
118
119 SERVER_BUSY = 137
120 """
121 Returned when the server is too busy to make a connection. It is recommended that the client try again later.
122 """
123
124 BANNED = 138
125 """
126 Returned when the client has been banned by the server.
127 """
128
129 BAD_AUTHENTICATION_METHOD = 140
130 """
131 Returned when the authentication method used in the connection is either not supported on the server or it does
132 not match the authentication method currently in use in the CONNECT packet.
133 """
134
135 TOPIC_NAME_INVALID = 144
136 """
137 Returned when the Will topic name sent in the CONNECT packet is correctly formed, but is not accepted by
138 the server.
139 """
140
141 PACKET_TOO_LARGE = 149
142 """
143 Returned when the CONNECT packet exceeded the maximum permissible size on the server.
144 """
145
146 QUOTA_EXCEEDED = 151
147 """
148 Returned when the quota limits set on the server have been met and/or exceeded.
149 """
150
151 PAYLOAD_FORMAT_INVALID = 153
152 """
153 Returned when the Will payload in the CONNECT packet does not match the specified payload format indicator.
154 """
155
156 RETAIN_NOT_SUPPORTED = 154
157 """
158 Returned when the server does not retain messages but the CONNECT packet on the client had Will retain enabled.
159 """
160
161 QOS_NOT_SUPPORTED = 155
162 """
163 Returned when the server does not support the QOS setting set in the Will QOS in the CONNECT packet.
164 """
165
166 USE_ANOTHER_SERVER = 156
167 """
168 Returned when the server is telling the client to temporarily use another server instead of the one they
169 are trying to connect to.
170 """
171
172 SERVER_MOVED = 157
173 """
174 Returned when the server is telling the client to permanently use another server instead of the one they
175 are trying to connect to.
176 """
177
178 CONNECTION_RATE_EXCEEDED = 159
179 """
180 Returned when the server connection rate limit has been exceeded.
181 """
182
183
184 def _try_connect_reason_code(value):
185 try:
186 return ConnectReasonCode(value)
187 except Exception:
188 return None
189
190
191 class DisconnectReasonCode(IntEnum):
192 """Reason code inside DISCONNECT packets. Helps determine why a connection was terminated.
193
194 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901208>`__ encoding values.
195 """
196
197 NORMAL_DISCONNECTION = 0
198 """
199 Returned when the remote endpoint wishes to disconnect normally. Will not trigger the publish of a Will message if a
200 Will message was configured on the connection.
201
202 May be sent by the client or server.
203 """
204
205 DISCONNECT_WITH_WILL_MESSAGE = 4
206 """
207 Returns when the client wants to disconnect but requires that the server publish the Will message configured
208 on the connection.
209
210 May only be sent by the client.
211 """
212
213 UNSPECIFIED_ERROR = 128
214 """
215 Returned when the connection was closed but the sender does not want to specify a reason or none
216 of the other reason codes apply.
217
218 May be sent by the client or the server.
219 """
220
221 MALFORMED_PACKET = 129
222 """
223 Indicates the remote endpoint received a packet that does not conform to the MQTT specification.
224
225 May be sent by the client or the server.
226 """
227
228 PROTOCOL_ERROR = 130
229 """
230 Returned when an unexpected or out-of-order packet was received by the remote endpoint.
231
232 May be sent by the client or the server.
233 """
234
235 IMPLEMENTATION_SPECIFIC_ERROR = 131
236 """
237 Returned when a valid packet was received by the remote endpoint, but could not be processed by the current implementation.
238
239 May be sent by the client or the server.
240 """
241
242 NOT_AUTHORIZED = 135
243 """
244 Returned when the remote endpoint received a packet that represented an operation that was not authorized within
245 the current connection.
246
247 May only be sent by the server.
248 """
249
250 SERVER_BUSY = 137
251 """
252 Returned when the server is busy and cannot continue processing packets from the client.
253
254 May only be sent by the server.
255 """
256
257 SERVER_SHUTTING_DOWN = 139
258 """
259 Returned when the server is shutting down.
260
261 May only be sent by the server.
262 """
263
264 KEEP_ALIVE_TIMEOUT = 141
265 """
266 Returned when the server closes the connection because no packet from the client has been received in
267 1.5 times the KeepAlive time set when the connection was established.
268
269 May only be sent by the server.
270 """
271
272 SESSION_TAKEN_OVER = 142
273 """
274 Returned when the server has established another connection with the same client ID as a client's current
275 connection, causing the current client to become disconnected.
276
277 May only be sent by the server.
278 """
279
280 TOPIC_FILTER_INVALID = 143
281 """
282 Returned when the topic filter name is correctly formed but not accepted by the server.
283
284 May only be sent by the server.
285 """
286
287 TOPIC_NAME_INVALID = 144
288 """
289 Returned when topic name is correctly formed, but is not accepted.
290
291 May be sent by the client or the server.
292 """
293
294 RECEIVE_MAXIMUM_EXCEEDED = 147
295 """
296 Returned when the remote endpoint reached a state where there were more in-progress QoS1+ publishes then the
297 limit it established for itself when the connection was opened.
298
299 May be sent by the client or the server.
300 """
301
302 TOPIC_ALIAS_INVALID = 148
303 """
304 Returned when the remote endpoint receives a PUBLISH packet that contained a topic alias greater than the
305 maximum topic alias limit that it established for itself when the connection was opened.
306
307 May be sent by the client or the server.
308 """
309
310 PACKET_TOO_LARGE = 149
311 """
312 Returned when the remote endpoint received a packet whose size was greater than the maximum packet size limit
313 it established for itself when the connection was opened.
314
315 May be sent by the client or the server.
316 """
317
318 MESSAGE_RATE_TOO_HIGH = 150
319 """
320 Returned when the remote endpoint's incoming data rate was too high.
321
322 May be sent by the client or the server.
323 """
324
325 QUOTA_EXCEEDED = 151
326 """
327 Returned when an internal quota of the remote endpoint was exceeded.
328
329 May be sent by the client or the server.
330 """
331
332 ADMINISTRATIVE_ACTION = 152
333 """
334 Returned when the connection was closed due to an administrative action.
335
336 May be sent by the client or the server.
337 """
338
339 PAYLOAD_FORMAT_INVALID = 153
340 """
341 Returned when the remote endpoint received a packet where payload format did not match the format specified
342 by the payload format indicator.
343
344 May be sent by the client or the server.
345 """
346
347 RETAIN_NOT_SUPPORTED = 154
348 """
349 Returned when the server does not support retained messages.
350
351 May only be sent by the server.
352 """
353
354 QOS_NOT_SUPPORTED = 155
355 """
356 Returned when the client sends a QoS that is greater than the maximum QoS established when the connection was
357 opened.
358
359 May only be sent by the server.
360 """
361
362 USE_ANOTHER_SERVER = 156
363 """
364 Returned by the server to tell the client to temporarily use a different server.
365
366 May only be sent by the server.
367 """
368
369 SERVER_MOVED = 157
370 """
371 Returned by the server to tell the client to permanently use a different server.
372
373 May only be sent by the server.
374 """
375
376 SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158
377 """
378 Returned by the server to tell the client that shared subscriptions are not supported on the server.
379
380 May only be sent by the server.
381 """
382
383 CONNECTION_RATE_EXCEEDED = 159
384 """
385 Returned when the server disconnects the client due to the connection rate being too high.
386
387 May only be sent by the server.
388 """
389
390 MAXIMUM_CONNECT_TIME = 160
391 """
392 Returned by the server when the maximum connection time authorized for the connection was exceeded.
393
394 May only be sent by the server.
395 """
396
397 SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161
398 """
399 Returned by the server when it received a SUBSCRIBE packet with a subscription identifier, but the server does
400 not support subscription identifiers.
401
402 May only be sent by the server.
403 """
404
405 WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
406 """
407 Returned by the server when it received a SUBSCRIBE packet with a wildcard topic filter, but the server does
408 not support wildcard topic filters.
409
410 May only be sent by the server.
411 """
412
413
414 def _try_disconnect_reason_code(value):
415 try:
416 return DisconnectReasonCode(value)
417 except Exception:
418 return None
419
420
421 class PubackReasonCode(IntEnum):
422 """Reason code inside PUBACK packets that indicates the result of the associated PUBLISH request.
423
424 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901124>`__ encoding values.
425 """
426
427 SUCCESS = 0
428 """
429 Returned when the (QoS 1) publish was accepted by the recipient.
430
431 May be sent by the client or the server.
432 """
433
434 NO_MATCHING_SUBSCRIBERS = 16
435 """
436 Returned when the (QoS 1) publish was accepted but there were no matching subscribers.
437
438 May only be sent by the server.
439 """
440
441 UNSPECIFIED_ERROR = 128
442 """
443 Returned when the (QoS 1) publish was not accepted and the receiver does not want to specify a reason or none
444 of the other reason codes apply.
445
446 May be sent by the client or the server.
447 """
448
449 IMPLEMENTATION_SPECIFIC_ERROR = 131
450 """
451 Returned when the (QoS 1) publish was valid but the receiver was not willing to accept it.
452
453 May be sent by the client or the server.
454 """
455
456 NOT_AUTHORIZED = 135
457 """
458 Returned when the (QoS 1) publish was not authorized by the receiver.
459
460 May be sent by the client or the server.
461 """
462
463 TOPIC_NAME_INVALID = 144
464 """
465 Returned when the topic name was valid but the receiver was not willing to accept it.
466
467 May be sent by the client or the server.
468 """
469
470 PACKET_IDENTIFIER_IN_USE = 145
471 """
472 Returned when the packet identifier used in the associated PUBLISH was already in use.
473 This can indicate a mismatch in the session state between client and server.
474
475 May be sent by the client or the server.
476 """
477
478 QUOTA_EXCEEDED = 151
479 """
480 Returned when the associated PUBLISH failed because an internal quota on the recipient was exceeded.
481
482 May be sent by the client or the server.
483 """
484
485 PAYLOAD_FORMAT_INVALID = 153
486 """
487 Returned when the PUBLISH packet's payload format did not match its payload format indicator property.
488
489 May be sent by the client or the server.
490 """
491
492
493 def _try_puback_reason_code(value):
494 try:
495 return PubackReasonCode(value)
496 except Exception:
497 return None
498
499
500 def _try_manual_puback_result(value):
501 try:
502 return ManualPubackResult(value)
503 except Exception:
504 return None
505
506
507 class SubackReasonCode(IntEnum):
508 """Reason code inside SUBACK packet payloads.
509
510 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901178>`__ encoding values.
511
512 This will only be sent by the server and not the client.
513 """
514
515 GRANTED_QOS_0 = 0
516 """
517 Returned when the subscription was accepted and the maximum QoS sent will be QoS 0.
518 """
519
520 GRANTED_QOS_1 = 1
521 """
522 Returned when the subscription was accepted and the maximum QoS sent will be QoS 1.
523 """
524
525 GRANTED_QOS_2 = 2
526 """
527 Returned when the subscription was accepted and the maximum QoS sent will be QoS 2.
528 """
529
530 UNSPECIFIED_ERROR = 128
531 """
532 Returned when the connection was closed but the sender does not want to specify a reason or none
533 of the other reason codes apply.
534 """
535
536 IMPLEMENTATION_SPECIFIC_ERROR = 131
537 """
538 Returned when the subscription was valid but the server did not accept it.
539 """
540
541 NOT_AUTHORIZED = 135
542 """
543 Returned when the client was not authorized to make the subscription on the server.
544 """
545
546 TOPIC_FILTER_INVALID = 143
547 """
548 Returned when the subscription topic filter was correctly formed but not allowed for the client.
549 """
550
551 PACKET_IDENTIFIER_IN_USE = 145
552 """
553 Returned when the packet identifier was already in use on the server.
554 """
555
556 QUOTA_EXCEEDED = 151
557 """
558 Returned when a subscribe-related quota set on the server was exceeded.
559 """
560
561 SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158
562 """
563 Returned when the subscription's topic filter was a shared subscription and the server does not support
564 shared subscriptions.
565 """
566
567 SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161
568 """
569 Returned when the SUBSCRIBE packet contained a subscription identifier and the server does not support
570 subscription identifiers.
571 """
572
573 WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
574 """
575 Returned when the subscription's topic filter contains a wildcard but the server does not support
576 wildcard subscriptions.
577 """
578
579
580 def _try_suback_reason_code(value):
581 try:
582 return SubackReasonCode(value)
583 except Exception:
584 return None
585
586
587 class UnsubackReasonCode(IntEnum):
588 """Reason codes inside UNSUBACK packet payloads that specify the results for each topic filter in the associated
589 UNSUBSCRIBE packet.
590
591 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194>`__ encoding values.
592 """
593
594 SUCCESS = 0
595 """
596 Returned when the unsubscribe was successful and the client is no longer subscribed to the topic filter on the server.
597 """
598
599 NO_SUBSCRIPTION_EXISTED = 17
600 """
601 Returned when the topic filter did not match one of the client's existing topic filters on the server.
602 """
603
604 UNSPECIFIED_ERROR = 128
605 """
606 Returned when the unsubscribe of the topic filter was not accepted and the server does not want to specify a
607 reason or none of the other reason codes apply.
608 """
609
610 IMPLEMENTATION_SPECIFIC_ERROR = 131
611 """
612 Returned when the topic filter was valid but the server does not accept an unsubscribe for it.
613 """
614
615 NOT_AUTHORIZED = 135
616 """
617 Returned when the client was not authorized to unsubscribe from that topic filter on the server.
618 """
619
620 TOPIC_FILTER_INVALID = 143
621 """
622 Returned when the topic filter was correctly formed but is not allowed for the client on the server.
623 """
624
625 PACKET_IDENTIFIER_IN_USE = 145
626 """
627 Returned when the packet identifier was already in use on the server.
628 """
629
630
631 def _try_unsuback_reason_code(value):
632 try:
633 return UnsubackReasonCode(value)
634 except Exception:
635 return None
636
637
638 class ClientSessionBehaviorType(IntEnum):
639 """Controls how the mqtt client should behave with respect to MQTT sessions.
640 """
641
642 DEFAULT = 0
643 """
644 Default client session behavior. Maps to CLEAN.
645 """
646
647 CLEAN = 1
648 """
649 Always ask for a clean session when connecting
650 """
651
652 REJOIN_POST_SUCCESS = 2
653 """
654 Always attempt to rejoin an existing session after an initial connection success.
655
656 Session rejoin requires an appropriate non-zero session expiry interval in the client's CONNECT options.
657 """
658
659 REJOIN_ALWAYS = 3
660 """
661 Always attempt to rejoin an existing session. Since the client does not support durable session persistence,
662 this option is not guaranteed to be spec compliant because any unacknowledged qos1 publishes (which are
663 part of the client session state) will not be present on the initial connection. Until we support
664 durable session resumption, this option is technically spec-breaking, but useful.
665
666 Always rejoin requires an appropriate non-zero session expiry interval in the client's CONNECT options.
667 """
668
669
670 class PayloadFormatIndicator(IntEnum):
671 """Optional property describing a PUBLISH payload's format.
672
673 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901111>`__ encoding values.
674 """
675
676 AWS_MQTT5_PFI_BYTES = 0
677 """
678 The payload is arbitrary binary data
679 """
680
681 AWS_MQTT5_PFI_UTF8 = 1
682 """
683 The payload is a well-formed utf-8 string value.
684 """
685
686
687 def _try_payload_format_indicator(value):
688 try:
689 return PayloadFormatIndicator(value)
690 except Exception:
691 return None
692
693
694 class RetainHandlingType(IntEnum):
695 """Configures how retained messages should be handled when subscribing with a topic filter that matches topics with
696 associated retained messages.
697
698 Enum values match `MQTT5 spec <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901169>`_ encoding values.
699 """
700
701 SEND_ON_SUBSCRIBE = 0
702 """
703 The server should always send all retained messages on topics that match a subscription's filter.
704 """
705
706 SEND_ON_SUBSCRIBE_IF_NEW = 1
707 """
708 The server should send retained messages on topics that match the subscription's filter, but only for the
709 first matching subscription, per session.
710 """
711
712 DONT_SEND = 2
713 """
714 Subscriptions must not trigger any retained message publishes from the server.
715 """
716
717
718 class RetainAndHandlingType(IntEnum):
719 """DEPRECATED.
720
721 `RetainAndHandlingType` is deprecated, please use `RetainHandlingType`
722 """
723 SEND_ON_SUBSCRIBE = 0
724 """
725 The server should always send all retained messages on topics that match a subscription's filter.
726 """
727
728 SEND_ON_SUBSCRIBE_IF_NEW = 1
729 """
730 The server should send retained messages on topics that match the subscription's filter, but only for the
731 first matching subscription, per session.
732 """
733
734 DONT_SEND = 2
735 """
736 Subscriptions must not trigger any retained message publishes from the server.
737 """
738
739
740 class ExtendedValidationAndFlowControlOptions(IntEnum):
741 """Additional controls for client behavior with respect to operation validation and flow control; these checks
742 go beyond the MQTT5 spec to respect limits of specific MQTT brokers.
743 """
744
745 NONE = 0
746 """
747 Do not do any additional validation or flow control
748 """
749
750 AWS_IOT_CORE_DEFAULTS = 1
751 """
752 Apply additional client-side validation and operational flow control that respects the
753 default AWS IoT Core limits.
754
755 Currently applies the following additional validation:
756
757 * No more than 8 subscriptions per SUBSCRIBE packet
758 * Topics and topic filters have a maximum of 7 slashes (8 segments), not counting any AWS rules prefix
759 * Topics must be 256 bytes or less in length
760 * Client id must be 128 or less bytes in length
761
762 Also applies the following flow control:
763
764 * Outbound throughput throttled to 512KB/s
765 * Outbound publish TPS throttled to 100
766
767 """
768
769
770 class ClientOperationQueueBehaviorType(IntEnum):
771 """Controls how disconnects affect the queued and in-progress operations tracked by the client. Also controls
772 how operations are handled while the client is not connected. In particular, if the client is not connected,
773 then any operation that would be failed on disconnect (according to these rules) will be rejected.
774 """
775
776 DEFAULT = 0
777 """
778 Default client operation queue behavior. Maps to FAIL_QOS0_PUBLISH_ON_DISCONNECT.
779 """
780
781 FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT = 1
782 """
783 Re-queues QoS 1+ publishes on disconnect; un-acked publishes go to the front while unprocessed publishes stay
784 in place. All other operations (QoS 0 publishes, subscribe, unsubscribe) are failed.
785 """
786
787 FAIL_QOS0_PUBLISH_ON_DISCONNECT = 2
788 """
789 QoS 0 publishes that are not complete at the time of disconnection are failed. Un-acked QoS 1+ publishes are
790 re-queued at the head of the line for immediate retransmission on a session resumption. All other operations
791 are requeued in original order behind any retransmissions.
792 """
793
794 FAIL_ALL_ON_DISCONNECT = 3
795 """
796 All operations that are not complete at the time of disconnection are failed, except operations that
797 the MQTT5 spec requires to be retransmitted (un-acked QoS1+ publishes).
798 """
799
800
801 class ExponentialBackoffJitterMode(IntEnum):
802 """Controls how the reconnect delay is modified in order to smooth out the distribution of reconnection attempt
803 timepoints for a large set of reconnecting clients.
804
805 See `Exponential Backoff and Jitter <https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/>`_
806 """
807
808 DEFAULT = 0
809 """
810 Maps to Full
811 """
812
813 NONE = 1
814 """
815 Do not perform any randomization on the reconnect delay
816 """
817
818 FULL = 2
819 """
820 Fully random between no delay and the current exponential backoff value.
821 """
822
823 DECORRELATED = 3
824 """
825 Backoff is taken randomly from the interval between the base backoff
826 interval and a scaling (greater than 1) of the current backoff value
827 """
828
829
830 @dataclass
831 class UserProperty:
832 """MQTT5 User Property
833
834 Args:
835 name (str): Property name
836 value (str): Property value
837 """
838
839 name: str = None
840 value: str = None
841
842
843 def _init_user_properties(user_properties_tuples):
844 if user_properties_tuples is None:
845 return None
846
847 return [UserProperty(name=name, value=value) for (name, value) in user_properties_tuples]
848
849
850 class OutboundTopicAliasBehaviorType(IntEnum):
851 """An enumeration that controls how the client applies topic aliasing to outbound publish packets.
852
853 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>`_
854 """
855
856 DEFAULT = 0,
857 """Maps to Disabled. This keeps the client from being broken (by default) if the broker
858 topic aliasing implementation has a problem.
859 """
860
861 MANUAL = 1,
862 """
863 Outbound aliasing is the user's responsibility. Client will cache and use
864 previously-established aliases if they fall within the negotiated limits of the connection.
865
866 The user must still always submit a full topic in their publishes because disconnections disrupt
867 topic alias mappings unpredictably. The client will properly use a requested alias when the most-recently-seen
868 binding for a topic alias value matches the alias and topic in the publish packet.
869 """
870
871 LRU = 2,
872 """ (Recommended) The client will ignore any user-specified topic aliasing and instead use an LRU cache to drive
873 alias usage.
874 """
875
876 DISABLED = 3,
877 """Completely disable outbound topic aliasing."""
878
879
880 class InboundTopicAliasBehaviorType(IntEnum):
881 """An enumeration that controls whether or not the client allows the broker to send publishes that use topic
882 aliasing.
883
884 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>`_
885 """
886
887 DEFAULT = 0,
888 """Maps to Disabled. This keeps the client from being broken (by default) if the broker
889 topic aliasing implementation has a problem.
890 """
891
892 ENABLED = 1,
893 """Allow the server to send PUBLISH packets to the client that use topic aliasing"""
894
895 DISABLED = 2,
896 """Forbid the server from sending PUBLISH packets to the client that use topic aliasing"""
897
898
899 @dataclass
900 class TopicAliasingOptions:
901 """
902 Configuration for all client topic aliasing behavior.
903
904 Args:
905 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.
906 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.
907 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.
908 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.
909 """
910 outbound_behavior: OutboundTopicAliasBehaviorType = None
911 outbound_cache_max_size: int = None
912 inbound_behavior: InboundTopicAliasBehaviorType = None
913 inbound_cache_max_size: int = None
914
915
916 @dataclass
917 class NegotiatedSettings:
918 """
919 Mqtt behavior settings that are dynamically negotiated as part of the CONNECT/CONNACK exchange.
920
921 While you can infer all of these values from a combination of:
922 - defaults as specified in the mqtt5 spec
923 - your CONNECT settings
924 - the CONNACK from the broker
925
926 the client instead does the combining for you and emits a NegotiatedSettings object with final, authoritative values.
927
928 Negotiated settings are communicated with every successful connection establishment.
929
930 Args:
931 maximum_qos (QoS): The maximum QoS allowed for publishes on this connection instance
932 session_expiry_interval_sec (int): The amount of time in seconds the server will retain the MQTT session after a disconnect.
933 receive_maximum_from_server (int): The number of in-flight QoS 1 and QoS 2 publications the server is willing to process concurrently.
934 maximum_packet_size_to_server (int): The maximum packet size the server is willing to accept.
935 topic_alias_maximum_to_server (int): the maximum allowed topic alias value on publishes sent from client to server
936 topic_alias_maximum_to_client (int): the maximum allowed topic alias value on publishes sent from server to client
937 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.
938 retain_available (bool): Whether the server supports retained messages.
939 wildcard_subscriptions_available (bool): Whether the server supports wildcard subscriptions.
940 subscription_identifiers_available (bool): Whether the server supports subscription identifiers
941 shared_subscriptions_available (bool): Whether the server supports shared subscriptions
942 rejoined_session (bool): Whether the client has rejoined an existing session.
943 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.
944 """
945 maximum_qos: QoS = None
946 session_expiry_interval_sec: int = None
947 receive_maximum_from_server: int = None
948 maximum_packet_size_to_server: int = None
949 topic_alias_maximum_to_server: int = None
950 topic_alias_maximum_to_client: int = None
951 server_keep_alive_sec: int = None
952 retain_available: bool = None
953 wildcard_subscriptions_available: bool = None
954 subscription_identifiers_available: bool = None
955 shared_subscriptions_available: bool = None
956 rejoined_session: bool = None
957 client_id: str = None
958
959
960 @dataclass
961 class ConnackPacket:
962 """Data model of an `MQTT5 CONNACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074>`_ packet.
963
964 Args:
965 session_present (bool): True if the client rejoined an existing session on the server, false otherwise.
966 reason_code (ConnectReasonCode): Indicates either success or the reason for failure for the connection attempt.
967 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.
968 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).
969 maximum_qos (QoS): The maximum message delivery quality of service that the server will allow on this connection.
970 retain_available (bool): Indicates whether the server supports retained messages. If None, retained messages are supported.
971 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.
972 assigned_client_identifier (str): Specifies a client identifier assigned to this connection by the server. Only valid when the client id of the preceding CONNECT packet was left empty.
973 topic_alias_maximum (int): The maximum allowed value for topic aliases in outbound publish packets. If 0 or None, then outbound topic aliasing is not allowed.
974 reason_string (str): Additional diagnostic information about the result of the connection attempt.
975 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
976 wildcard_subscriptions_available (bool): Indicates whether the server supports wildcard subscriptions. If None, wildcard subscriptions are supported.
977 subscription_identifiers_available (bool): Indicates whether the server supports subscription identifiers. If None, subscription identifiers are supported.
978 shared_subscription_available (bool): Indicates whether the server supports shared subscription topic filters. If None, shared subscriptions are supported.
979 server_keep_alive (int) : DEPRECATED. Please use `server_keep_alive_sec`.
980 server_keep_alive_sec (int): Server-requested override of the keep alive interval, in seconds. If None, the keep alive value sent by the client should be used.
981 response_information (str): A value that can be used in the creation of a response topic associated with this connection. MQTT5-based request/response is outside the purview of the MQTT5 spec and this client.
982 server_reference (str): Property indicating an alternate server that the client may temporarily or permanently attempt to connect to instead of the configured endpoint. Will only be set if the reason code indicates another server may be used (ServerMoved, UseAnotherServer).
983 """
984 session_present: bool = None
985 reason_code: ConnectReasonCode = None
986 session_expiry_interval_sec: int = None
987 receive_maximum: int = None
988 maximum_qos: QoS = None
989 retain_available: bool = None
990 maximum_packet_size: int = None
991 assigned_client_identifier: str = None
992 topic_alias_maximum: int = None
993 reason_string: str = None
994 user_properties: 'Sequence[UserProperty]' = None
995 wildcard_subscriptions_available: bool = None
996 subscription_identifiers_available: bool = None
997 shared_subscription_available: bool = None
998 server_keep_alive_sec: int = None
999 response_information: str = None
1000 server_reference: str = None
1001
1002 @property
1003 def server_keep_alive(self):
1004 return self.server_keep_alive_sec
1005
1006 @server_keep_alive.setter
1007 def server_keep_alive(self, value):
1008 self.server_keep_alive_sec = value
1009
1010
1011 @dataclass
1012 class DisconnectPacket:
1013 """Data model of an `MQTT5 DISCONNECT <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205>`_ packet.
1014
1015 Args:
1016 reason_code (DisconnectReasonCode): Value indicating the reason that the sender is closing the connection
1017 session_expiry_interval_sec (int): A change to the session expiry interval negotiated at connection time as part of the disconnect. Only valid for DISCONNECT packets sent from client to server. It is not valid to attempt to change session expiry from zero to a non-zero value.
1018 reason_string (str): Additional diagnostic information about the reason that the sender is closing the connection
1019 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1020 server_reference (str): Property indicating an alternate server that the client may temporarily or permanently attempt to connect to instead of the configured endpoint. Will only be set if the reason code indicates another server may be used (ServerMoved, UseAnotherServer).
1021
1022 """
1023 reason_code: DisconnectReasonCode = DisconnectReasonCode.NORMAL_DISCONNECTION
1024 session_expiry_interval_sec: int = None
1025 reason_string: str = None
1026 user_properties: 'Sequence[UserProperty]' = None
1027 server_reference: str = None
1028
1029
1030 @dataclass
1031 class Subscription:
1032 """Configures a single subscription within a Subscribe operation
1033
1034 Args:
1035 topic_filter (str): The topic filter to subscribe to
1036 qos (QoS): The maximum QoS on which the subscriber will accept publish messages
1037 no_local (bool): Whether the server will not send publishes to a client when that client was the one who sent the publish
1038 retain_as_published (bool): Whether messages sent due to this subscription keep the retain flag preserved on the message
1039 retain_handling_type (RetainHandlingType): Whether retained messages on matching topics be sent in reaction to this subscription
1040 """
1041 topic_filter: str
1042 qos: QoS = QoS.AT_MOST_ONCE
1043 no_local: bool = False
1044 retain_as_published: bool = False
1045 retain_handling_type: RetainHandlingType or RetainAndHandlingType = RetainHandlingType.SEND_ON_SUBSCRIBE
1046
1047
1048 @dataclass
1049 class SubscribePacket:
1050 """Data model of an `MQTT5 SUBSCRIBE <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901161>`_ packet.
1051
1052 Args:
1053 subscriptions (Sequence[Subscription]): The list of topic filters that the client wishes to listen to
1054 subscription_identifier (int): The positive int to associate with all topic filters in this request. Publish packets that match a subscription in this request should include this identifier in the resulting message.
1055 user_properties (Sequence[UserProperty]): The list of MQTT5 user properties included with the packet.
1056 """
1057 subscriptions: 'Sequence[Subscription]'
1058 subscription_identifier: int = None
1059 user_properties: 'Sequence[UserProperty]' = None
1060
1061
1062 @dataclass
1063 class SubackPacket:
1064 """Data model of an `MQTT5 SUBACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901171>`_ packet.
1065
1066 Args:
1067 reason_string (str): Additional diagnostic information about the result of the SUBSCRIBE attempt.
1068 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1069 reason_codes (Sequence[SubackReasonCode]): List of reason codes indicating the result of each individual subscription entry in the associated SUBSCRIBE packet.
1070 """
1071 reason_string: str = None
1072 user_properties: 'Sequence[UserProperty]' = None
1073 reason_codes: 'Sequence[SubackReasonCode]' = None
1074
1075
1076 @dataclass
1077 class UnsubscribePacket:
1078 """Data model of an `MQTT5 UNSUBSCRIBE <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc384800445>`_ packet.
1079
1080 Args:
1081 topic_filters (Sequence[str]): List of topic filters that the client wishes to unsubscribe from.
1082 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1083 """
1084 topic_filters: 'Sequence[str]'
1085 user_properties: 'Sequence[UserProperty]' = None
1086
1087
1088 @dataclass
1089 class UnsubackPacket:
1090 """Data model of an `MQTT5 UNSUBACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc471483687>`_ packet.
1091
1092 Args:
1093 reason_string (str): Additional diagnostic information about the result of the UNSUBSCRIBE attempt.
1094 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1095 reason_codes (Sequence[UnsubackReasonCode]): A list of reason codes indicating the result of unsubscribing from each individual topic filter entry in the associated UNSUBSCRIBE packet.
1096
1097 """
1098 reason_string: str = None
1099 user_properties: 'Sequence[UserProperty]' = None
1100 reason_codes: 'Sequence[UnsubackReasonCode]' = None
1101
1102
1103 @dataclass
1104 class PublishPacket:
1105 """Data model of an `MQTT5 PUBLISH <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901100>`_ packet
1106
1107 Args:
1108 payload (Any): The payload of the publish message.
1109 qos (QoS): The MQTT quality of service associated with this PUBLISH packet.
1110 retain (bool): True if this is a retained message, false otherwise.
1111 topic (str): The topic associated with this PUBLISH packet.
1112 payload_format_indicator (PayloadFormatIndicator): Property specifying the format of the payload data. The mqtt5 client does not enforce or use this value in a meaningful way.
1113 message_expiry_interval_sec (int): Sent publishes - indicates the maximum amount of time allowed to elapse for message delivery before the server should instead delete the message (relative to a recipient). Received publishes - indicates the remaining amount of time (from the server's perspective) before the message would have been deleted relative to the subscribing client. If left None, indicates no expiration timeout.
1114 topic_alias (int): An integer value that is used to identify the Topic instead of using the Topic Name. On outbound publishes, this will only be used if the outbound topic aliasing behavior has been set to Manual.
1115 response_topic (str): Opaque topic string intended to assist with request/response implementations. Not internally meaningful to MQTT5 or this client.
1116 correlation_data (Optional[Union[bytes, str]]): Deprecated, use `correlation_data_bytes` instead. Opaque binary data used to correlate between publish messages, as a potential method for request-response implementation. Not internally meaningful to MQTT5. For incoming publishes, this will be a utf8 string (if correlation data exists and it's convertible to utf-8) or None (either it didn't exist, or did but wasn't convertible)
1117 correlation_data_bytes (Optional[Union[bytes, str]]): Opaque binary data used to correlate between publish messages, as a potential method for request-response implementation. Not internally meaningful to MQTT5. For outbound publishes, this field takes priority over `correlation_data`. For incoming publishes, this will be binary data if correlation data is set, otherwise it will be None.
1118 subscription_identifiers (Sequence[int]): The subscription identifiers of all the subscriptions this message matched. This field is ignored on outbound publishes (setting it is a protocol error).
1119 content_type (str): Property specifying the content type of the payload. Not internally meaningful to MQTT5.
1120 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1121 """
1122 payload: Any = "" # Unicode objects are converted to C strings using 'utf-8' encoding
1123 qos: QoS = QoS.AT_MOST_ONCE
1124 retain: bool = False
1125 topic: str = ""
1126 payload_format_indicator: PayloadFormatIndicator = None
1127 message_expiry_interval_sec: int = None
1128 topic_alias: int = None
1129 response_topic: str = None
1130 correlation_data_bytes: 'Optional[Union[bytes, str]]' = None # binary data if correlation data exists on the packet
1131 # Deprecated. Incoming publishes: a string if correlation data exists on the packet and is convertible to utf-8
1132 correlation_data: 'Optional[Union[bytes, str]]' = None
1133 subscription_identifiers: 'Sequence[int]' = None # ignore attempts to set but provide in received packets
1134 content_type: str = None
1135 user_properties: 'Sequence[UserProperty]' = None
1136
1137
1138 @dataclass
1139 class PubackPacket:
1140 """Data model of an `MQTT5 PUBACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901121>`_ packet
1141
1142 Args:
1143 reason_code (PubackReasonCode): Success indicator or failure reason for the associated PUBLISH packet.
1144 reason_string (str): Additional diagnostic information about the result of the PUBLISH attempt.
1145 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1146 """
1147 reason_code: PubackReasonCode = None
1148 reason_string: str = None
1149 user_properties: 'Sequence[UserProperty]' = None
1150
1151
1152 @dataclass
1153 class ConnectPacket:
1154 """Data model of an `MQTT5 CONNECT <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901033>`_ packet.
1155
1156 Args:
1157 keep_alive_interval_sec (int): The maximum time interval, in seconds, that is permitted to elapse between the point at which the client finishes transmitting one MQTT packet and the point it starts sending the next. The client will use PINGREQ packets to maintain this property. If the responding CONNACK contains a keep alive property value, then that is the negotiated keep alive value. Otherwise, the keep alive sent by the client is the negotiated value.
1158 client_id (str): A unique string identifying the client to the server. Used to restore session state between connections. If left empty, the broker will auto-assign a unique client id. When reconnecting, the mqtt5 client will always use the auto-assigned client id.
1159 username (str): A string value that the server may use for client authentication and authorization.
1160 password (str): Opaque binary data that the server may use for client authentication and authorization.
1161 session_expiry_interval_sec (int): A time interval, in seconds, that the client requests the server to persist this connection's MQTT session state for. Has no meaning if the client has not been configured to rejoin sessions. Must be non-zero in order to successfully rejoin a session. If the responding CONNACK contains a session expiry property value, then that is the negotiated session expiry value. Otherwise, the session expiry sent by the client is the negotiated value.
1162 request_response_information (bool): If true, requests that the server send response information in the subsequent CONNACK. This response information may be used to set up request-response implementations over MQTT, but doing so is outside the scope of the MQTT5 spec and client.
1163 request_problem_information (bool): If true, requests that the server send additional diagnostic information (via response string or user properties) in DISCONNECT or CONNACK packets from the server.
1164 receive_maximum (int): Notifies the server of the maximum number of in-flight QoS 1 and 2 messages the client is willing to handle. If omitted or None, then no limit is requested.
1165 maximum_packet_size (int): Notifies the server of the maximum packet size the client is willing to handle. If omitted or None, then no limit beyond the natural limits of MQTT packet size is requested.
1166 will_delay_interval_sec (int): A time interval, in seconds, that the server should wait (for a session reconnection) before sending the will message associated with the connection's session. If omitted or None, the server will send the will when the associated session is destroyed. If the session is destroyed before a will delay interval has elapsed, then the will must be sent at the time of session destruction.
1167 will (PublishPacket): The definition of a message to be published when the connection's session is destroyed by the server or when the will delay interval has elapsed, whichever comes first. If None, then nothing will be sent.
1168 user_properties (Sequence[UserProperty]): List of MQTT5 user properties included with the packet.
1169
1170 """
1171 keep_alive_interval_sec: int = None
1172 client_id: str = None
1173 username: str = None
1174 password: str = None
1175 session_expiry_interval_sec: int = None
1176 request_response_information: bool = None
1177 request_problem_information: bool = None
1178 receive_maximum: int = None
1179 maximum_packet_size: int = None
1180 will_delay_interval_sec: int = None
1181 will: PublishPacket = None
1182 user_properties: 'Sequence[UserProperty]' = None
1183
1184
1185 class WebsocketHandshakeTransformArgs:
1186 """
1187 Argument to a "websocket_handshake_transform" function.
1188
1189 A websocket_handshake_transform function has signature:
1190 ``fn(transform_args: WebsocketHandshakeTransformArgs) -> None``
1191
1192 The function implementer may modify `transform_args.http_request` as desired.
1193 They MUST call `transform_args.set_done()` when complete, passing an
1194 exception if something went wrong. Failure to call `set_done()`
1195 will hang the application.
1196
1197 The implementer may do asynchronous work before calling `transform_args.set_done()`,
1198 they are not required to call `set_done()` within the scope of the transform function.
1199 An example of async work would be to fetch credentials from another service,
1200 sign the request headers, and finally call `set_done()` to mark the transform complete.
1201
1202 The default websocket handshake request uses path "/mqtt".
1203 All required headers are present,
1204 plus the optional header "Sec-WebSocket-Protocol: mqtt".
1205
1206 Args:
1207 client (Client): Client this handshake is for.
1208 http_request (awscrt.http.HttpRequest): HTTP request for this handshake.
1209 done_future (concurrent.futures.Future): Future to complete when the
1210 :meth:`set_done()` is called. It will contain None if successful,
1211 or an exception will be set.
1212
1213 Attributes:
1214 client (Client): Client this handshake is for.
1215 http_request (awscrt.http.HttpRequest): HTTP request for this handshake.
1216 """
1217
1218 def __init__(self, client, http_request, done_future):
1219 self.client = client
1220 self.http_request = http_request
1221 self._done_future = done_future
1222
1223 def set_done(self, exception=None):
1224 """
1225 Mark the transformation complete.
1226 If exception is passed in, the handshake is canceled.
1227 """
1228 if exception is None:
1229 self._done_future.set_result(None)
1230 else:
1231 self._done_future.set_exception(exception)
1232
1233
1234 class PublishAcknowledgementControlHandle:
1235 """Opaque handle for manually controlling the publish acknowledgement for a received QoS 1 PUBLISH.
1236
1237 Obtained by calling acquire_publish_acknowledgement_control() within the on_publish_callback_fn callback.
1238 Pass to Client.invoke_publish_acknowledgement() to send the publish acknowledgement to the broker.
1239 """
1240
1241 def __init__(self, control_id: int):
1242 self._control_id = control_id
1243
1244
1245 @dataclass
1246 class PublishReceivedData:
1247 """Dataclass containing data related to a Publish Received Callback
1248
1249 Args:
1250 publish_packet (PublishPacket): Data model of an `MQTT5 PUBLISH <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901100>`_ packet.
1251 acquire_publish_acknowledgement_control (Callable): For QoS 1 messages only: call this function within the
1252 on_publish_callback_fn callback to take manual control of the publish acknowledgement for this message,
1253 preventing the client from automatically sending a publish acknowledgement. Returns a
1254 :class:`PublishAcknowledgementControlHandle` that can be passed to
1255 Client.invoke_publish_acknowledgement() to send the publish acknowledgement to the broker.
1256
1257 Important: This function must be called within the on_publish_callback_fn callback. Calling it after the
1258 callback returns will raise a RuntimeError. This function may only be called once per received PUBLISH;
1259 calling it a second time will also raise a RuntimeError. If this function is not called, the client will
1260 automatically send a publish acknowledgement for QoS 1 messages when the callback returns.
1261
1262 For QoS 0 messages, this field is None.
1263 """
1264 publish_packet: PublishPacket = None
1265 acquire_publish_acknowledgement_control: Callable = None
1266
1267
1268 @dataclass
1269 class OperationStatisticsData:
1270 """Dataclass containing some simple statistics about the current state of the client's queue of operations
1271
1272 Args:
1273 incomplete_operation_count (int): Total number of operations submitted to the client that have not yet been completed. Unacked operations are a subset of this.
1274 incomplete_operation_size (int): Total packet size of operations submitted to the client that have not yet been completed. Unacked operations are a subset of this.
1275 unacked_operation_count (int): Total number of operations that have been sent to the server and are waiting for a corresponding ACK before they can be completed.
1276 unacked_operation_size (int): Total packet size of operations that have been sent to the server and are waiting for a corresponding ACK before they can be completed.
1277 """
1278 incomplete_operation_count: int = 0
1279 incomplete_operation_size: int = 0
1280 unacked_operation_count: int = 0
1281 unacked_operation_size: int = 0
1282
1283
1284 @dataclass
1285 class LifecycleStoppedData:
1286 """Dataclass containing results of an Stopped Lifecycle Event
1287 Currently Unused"""
1288 pass
1289
1290
1291 @dataclass
1292 class LifecycleAttemptingConnectData:
1293 """Dataclass containing results of an Attempting Connect Lifecycle Event
1294 Currently Unused"""
1295 pass
1296
1297
1298 @dataclass
1299 class LifecycleConnectSuccessData:
1300 """Dataclass containing results of a Connect Success Lifecycle Event
1301
1302 Args:
1303 connack_packet (ConnackPacket): Data model of an `MQTT5 CONNACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074>`_ packet.
1304 negotiated_settings: (NegotiatedSettings): Mqtt behavior settings that have been dynamically negotiated as part of the CONNECT/CONNACK exchange.
1305 """
1306 connack_packet: ConnackPacket = None
1307 negotiated_settings: NegotiatedSettings = None
1308
1309
1310 @dataclass
1311 class LifecycleConnectFailureData:
1312 """Dataclass containing results of a Connect Failure Lifecycle Event
1313
1314 Args:
1315 connack_packet (ConnackPacket): Data model of an `MQTT5 CONNACK <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074>`_ packet.
1316 error_code (int): (:class:`awscrt.exceptions.AwsCrtError`): Exception which caused connection failure.
1317 """
1318 connack_packet: ConnackPacket = None
1319 exception: Exception = None
1320
1321
1322 @dataclass
1323 class LifecycleDisconnectData:
1324 """Dataclass containing results of a Disconnect Lifecycle Event
1325
1326 Args:
1327 disconnect_packet (DisconnectPacket): Data model of an `MQTT5 DISCONNECT <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205>`_ packet.
1328 error_code (int): (:class:`awscrt.exceptions.AwsCrtError`): Exception which caused disconnection.
1329 """
1330 disconnect_packet: DisconnectPacket = None
1331 exception: Exception = None
1332
1333
1334 @dataclass
1335 class PublishCompletionData:
1336 """Dataclass containing results of a Publish
1337
1338 Args:
1339 puback (PubackPacket): On a successful completion of a QoS1 publish a PubackPacket will be included.
1340 """
1341 puback: PubackPacket = None # This will be None on a QoS0
1342
1343
1344 @dataclass
1345 class ClientOptions:
1346 """Configuration for the creation of MQTT5 clients
1347
1348 Args:
1349 host_name (str): Host name of the MQTT server to connect to.
1350 port (int): Network port of the MQTT server to connect to.
1351 bootstrap (ClientBootstrap): The Client bootstrap used
1352 socket_options (SocketOptions): The socket properties of the underlying MQTT connections made by the client or None if defaults are used.
1353 tls_ctx (ClientTlsContext): The TLS context for secure socket connections. If None, then a plaintext connection will be used.
1354 http_proxy_options (HttpProxyOptions): The (tunneling) HTTP proxy usage when establishing MQTT connections
1355 websocket_handshake_transform (Callable[[WebsocketHandshakeTransformArgs],]): This callback allows a custom transformation of the HTTP request that acts as the websocket handshake. Websockets will be used if this is set to a valid transformation callback. To use websockets but not perform a transformation, just set this as a trivial completion callback. If None, the connection will be made with direct MQTT.
1356 connect_options (ConnectPacket): All configurable options with respect to the CONNECT packet sent by the client, including the will. These connect properties will be used for every connection attempt made by the client.
1357 session_behavior (ClientSessionBehaviorType): How the MQTT5 client should behave with respect to MQTT sessions.
1358 extended_validation_and_flow_control_options (ExtendedValidationAndFlowControlOptions): The additional controls for client behavior with respect to operation validation and flow control; these checks go beyond the base MQTT5 spec to respect limits of specific MQTT brokers.
1359 offline_queue_behavior (ClientOperationQueueBehaviorType): Returns how disconnects affect the queued and in-progress operations tracked by the client. Also controls how new 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 also be rejected.
1360 retry_jitter_mode (ExponentialBackoffJitterMode): How the reconnect delay is modified in order to smooth out the distribution of reconnection attempt timepoints for a large set of reconnecting clients.
1361 min_reconnect_delay_ms (int): The minimum amount of time to wait to reconnect after a disconnect. Exponential backoff is performed with jitter after each connection failure.
1362 max_reconnect_delay_ms (int): The maximum amount of time to wait to reconnect after a disconnect. Exponential backoff is performed with jitter after each connection failure.
1363 min_connected_time_to_reset_reconnect_delay_ms (int): The amount of time that must elapse with an established connection before the reconnect delay is reset to the minimum. This helps alleviate bandwidth-waste in fast reconnect cycles due to permission failures on operations.
1364 ping_timeout_ms (int): The time interval to wait after sending a PINGREQ for a PINGRESP to arrive. If one does not arrive, the client will close the current connection.
1365 connack_timeout_ms (int): The time interval to wait after sending a CONNECT request for a CONNACK to arrive. If one does not arrive, the connection will be shut down.
1366 ack_timeout_sec (int): The time interval to wait for an ack after sending a QoS 1+ PUBLISH, SUBSCRIBE, or UNSUBSCRIBE before failing the operation.
1367 topic_aliasing_options (TopicAliasingOptions): All configurable options with respect to client topic aliasing behavior.
1368 on_publish_callback_fn (Callable[[PublishReceivedData],]): Callback for all publish packets received by client.
1369 on_lifecycle_event_stopped_fn (Callable[[LifecycleStoppedData],]): Callback for Lifecycle Event Stopped.
1370 on_lifecycle_event_attempting_connect_fn (Callable[[LifecycleAttemptingConnectData],]): Callback for Lifecycle Event Attempting Connect.
1371 on_lifecycle_event_connection_success_fn (Callable[[LifecycleConnectSuccessData],]): Callback for Lifecycle Event Connection Success.
1372 on_lifecycle_event_connection_failure_fn (Callable[[LifecycleConnectFailureData],]): Callback for Lifecycle Event Connection Failure.
1373 on_lifecycle_event_disconnection_fn (Callable[[LifecycleDisconnectData],]): Callback for Lifecycle Event Disconnection.
1374 disable_metrics (bool): Disable IoT SDK metrics in MQTT CONNECT packet username field, including SDK name, version, and platform. Default to False.
1375 metrics (Optional[AWSIoTMetrics]): Optional metrics configuration for IoT SDK metrics reporting. If provided, the CRT will use the given metrics. If None, a default AWSIoTMetrics will be created.
1376
1377 """
1378 host_name: str
1379 port: int = None
1380 bootstrap: ClientBootstrap = None
1381 socket_options: SocketOptions = None
1382 tls_ctx: ClientTlsContext = None
1383 http_proxy_options: HttpProxyOptions = None
1384 websocket_handshake_transform: Callable[[WebsocketHandshakeTransformArgs], None] = None
1385 connect_options: ConnectPacket = None
1386 session_behavior: ClientSessionBehaviorType = None
1387 extended_validation_and_flow_control_options: ExtendedValidationAndFlowControlOptions = None
1388 offline_queue_behavior: ClientOperationQueueBehaviorType = None
1389 retry_jitter_mode: ExponentialBackoffJitterMode = None
1390 min_reconnect_delay_ms: int = None
1391 max_reconnect_delay_ms: int = None
1392 min_connected_time_to_reset_reconnect_delay_ms: int = None
1393 ping_timeout_ms: int = None
1394 connack_timeout_ms: int = None
1395 ack_timeout_sec: int = None
1396 topic_aliasing_options: TopicAliasingOptions = None
1397 on_publish_callback_fn: Callable[[PublishReceivedData], None] = None
1398 on_lifecycle_event_stopped_fn: Callable[[LifecycleStoppedData], None] = None
1399 on_lifecycle_event_attempting_connect_fn: Callable[[LifecycleAttemptingConnectData], None] = None
1400 on_lifecycle_event_connection_success_fn: Callable[[LifecycleConnectSuccessData], None] = None
1401 on_lifecycle_event_connection_failure_fn: Callable[[LifecycleConnectFailureData], None] = None
1402 on_lifecycle_event_disconnection_fn: Callable[[LifecycleDisconnectData], None] = None
1403 disable_metrics: bool = False
1404 metrics: Optional[AWSIoTMetrics] = None
1405
1406
1407 def _check_callback(callback):
1408 if callback is not None:
1409 try:
1410 callback_sig = signature(callback)
1411 callback_sig.bind(None)
1412 return callback
1413 except BaseException:
1414 raise TypeError(
1415 "Callable should take one argument")
1416
1417 return None
1418
1419
1420 class _ClientCore:
1421
1422 def __init__(self, client_options: ClientOptions):
1423 self._ws_handshake_transform_cb = _check_callback(client_options.websocket_handshake_transform)
1424 self._on_publish_cb = _check_callback(client_options.on_publish_callback_fn)
1425 self._on_lifecycle_stopped_cb = _check_callback(client_options.on_lifecycle_event_stopped_fn)
1426 self._on_lifecycle_attempting_connect_cb = _check_callback(
1427 client_options.on_lifecycle_event_attempting_connect_fn)
1428 self._on_lifecycle_connection_success_cb = _check_callback(
1429 client_options.on_lifecycle_event_connection_success_fn)
1430 self._on_lifecycle_connection_failure_cb = _check_callback(
1431 client_options.on_lifecycle_event_connection_failure_fn)
1432 self._on_lifecycle_disconnection_cb = _check_callback(client_options.on_lifecycle_event_disconnection_fn)
1433 self._disable_metrics = client_options.disable_metrics
1434
1435 def _ws_handshake_transform(self, http_request_binding, http_headers_binding, native_userdata):
1436 if self._ws_handshake_transform_cb is None:
1437 _awscrt.mqtt5_ws_handshake_transform_complete(None, native_userdata, 0)
1438 return
1439
1440 def _on_complete(f):
1441 error_code = 0
1442 hs_exception = f.exception()
1443 if isinstance(hs_exception, exceptions.AwsCrtError):
1444 error_code = hs_exception.code
1445 _awscrt.mqtt5_ws_handshake_transform_complete(f.exception(), native_userdata, error_code)
1446
1447 future = Future()
1448 future.add_done_callback(_on_complete)
1449
1450 try:
1451 http_request = HttpRequest._from_bindings(http_request_binding, http_headers_binding)
1452 transform_args = WebsocketHandshakeTransformArgs(self, http_request, future)
1453 self._ws_handshake_transform_cb(transform_args=transform_args)
1454 except Exception as e:
1455 # Call set_done() if user failed to do so before uncaught exception was raised,
1456 # there's a chance the callback wasn't callable and user has no idea we tried to hand them the baton.
1457 if not future.done():
1458 transform_args.set_done(e)
1459
1460 def _on_publish(
1461 self,
1462 payload,
1463 qos,
1464 retain,
1465 topic,
1466 payload_format_indicator_exists,
1467 payload_format_indicator,
1468 message_expiry_interval_sec_exists,
1469 message_expiry_interval_sec,
1470 topic_alias_exists,
1471 topic_alias,
1472 response_topic,
1473 correlation_data,
1474 subscription_identifiers_tuples,
1475 content_type,
1476 user_properties_tuples,
1477 puback_control_id):
1478 if self._on_publish_cb is None:
1479 # Indicates that manual puback control was not taken and puback should be invoked automatically.
1480 return False
1481
1482 publish_packet = PublishPacket()
1483 publish_packet.topic = topic
1484 publish_packet.payload = payload
1485 publish_packet.qos = _try_qos(qos)
1486 publish_packet.retain = retain
1487
1488 if payload_format_indicator_exists:
1489 publish_packet.payload_format_indicator = _try_payload_format_indicator(payload_format_indicator)
1490 if message_expiry_interval_sec_exists:
1491 publish_packet.message_expiry_interval_sec = message_expiry_interval_sec
1492 if topic_alias_exists:
1493 publish_packet.topic_alias = topic_alias
1494 publish_packet.response_topic = response_topic
1495
1496 # hacky workaround to maintain behavioral backwards compatibility with deprecated parameter
1497 if correlation_data is not None:
1498 # `correlation_data_bytes` always has the correlation data, as binary data
1499 publish_packet.correlation_data_bytes = correlation_data
1500 try:
1501 # `correlation_data` contains the correlation data as a utf-8 string, if it can be converted
1502 publish_packet.correlation_data = correlation_data.decode("utf-8")
1503 except Exception:
1504 pass
1505
1506 if subscription_identifiers_tuples is not None:
1507 publish_packet.subscription_identifiers = [subscription_identifier
1508 for (subscription_identifier) in subscription_identifiers_tuples]
1509 publish_packet.content_type = content_type
1510 publish_packet.user_properties = _init_user_properties(user_properties_tuples)
1511
1512 # For QoS 1 messages, set up the acquire_publish_acknowledgement_control callable.
1513 # The native side has already called aws_mqtt5_client_acquire_publish_acknowledgement and passed us the
1514 # puback_control_id. We wrap it in an opaque capsule handle and provide a callable that
1515 # returns that handle. The callable may only be called once; calling it marks the publish
1516 # acknowledgement as "taken" so the native side will not auto-invoke it after this callback returns.
1517 puback_taken = False
1518 callback_active = True
1519 acquire_publish_acknowledgement_control = None
1520
1521 if puback_control_id != 0:
1522 def acquire_publish_acknowledgement_control():
1523 nonlocal puback_taken
1524 nonlocal callback_active
1525 if puback_taken:
1526 raise RuntimeError(
1527 "acquire_publish_acknowledgement_control() may only be called once per received PUBLISH.")
1528 if not callback_active:
1529 raise RuntimeError(
1530 "acquire_publish_acknowledgement_control() must be called within the on_publish_callback_fn callback.")
1531 puback_taken = True
1532 return PublishAcknowledgementControlHandle(puback_control_id)
1533
1534 # Create PublishReceivedData with the acquire_publish_acknowledgement_control callable (or None for QoS 0)
1535 publish_data = PublishReceivedData(
1536 publish_packet=publish_packet,
1537 acquire_publish_acknowledgement_control=acquire_publish_acknowledgement_control
1538 )
1539
1540 self._on_publish_cb(publish_data)
1541
1542 callback_active = False
1543 # Return True if the user called acquire_publish_acknowledgement_control(), signalling to the native side
1544 # that it should NOT auto-invoke the publish acknowledgement (the user is responsible for calling
1545 # invoke_publish_acknowledgement).
1546 return puback_taken
1547
1548 def _on_lifecycle_stopped(self):
1549 if self._on_lifecycle_stopped_cb:
1550 self._on_lifecycle_stopped_cb(LifecycleStoppedData())
1551
1552 def _on_lifecycle_attempting_connect(self):
1553 if self._on_lifecycle_attempting_connect_cb:
1554 self._on_lifecycle_attempting_connect_cb(LifecycleAttemptingConnectData())
1555
1556 def _on_lifecycle_connection_success(
1557 self,
1558 connack_session_present,
1559 connack_reason_code,
1560 connack_session_expiry_interval_sec_exists,
1561 connack_session_expiry_interval_sec,
1562 connack_receive_maximum_exists,
1563 connack_receive_maximum,
1564 connack_maximum_qos_exists,
1565 connack_maximum_qos,
1566 connack_retain_available_exists,
1567 connack_retain_available,
1568 connack_maximum_packet_size_exists,
1569 connack_maximum_packet_size,
1570 connack_assigned_client_identifier,
1571 connack_topic_alias_maximum_exists,
1572 connack_topic_alias_maximum,
1573 connack_reason_string,
1574 connack_user_properties_tuples,
1575 connack_wildcard_subscriptions_available_exist,
1576 connack_wildcard_subscriptions_available,
1577 connack_subscription_identifiers_available_exists,
1578 connack_subscription_identifiers_available,
1579 connack_shared_subscriptions_available_exists,
1580 connack_shared_subscriptions_available,
1581 connack_server_keep_alive_exists,
1582 connack_server_keep_alive,
1583 connack_response_information,
1584 connack_server_reference,
1585 settings_maximum_qos,
1586 settings_session_expiry_interval_sec,
1587 settings_receive_maximum_from_server,
1588 settings_maximum_packet_size_to_server,
1589 settings_topic_alias_maximum_to_server,
1590 settings_topic_alias_maximum_to_client,
1591 settings_server_keep_alive,
1592 settings_retain_available,
1593 settings_wildcard_subscriptions_available,
1594 settings_subscription_identifiers_available,
1595 settings_shared_subscriptions_available,
1596 settings_rejoined_session,
1597 settings_client_id):
1598 if self._on_lifecycle_connection_success_cb is None:
1599 return
1600
1601 connack_packet = ConnackPacket()
1602 connack_packet.session_present = connack_session_present
1603 connack_packet.reason_code = _try_connect_reason_code(connack_reason_code)
1604 if connack_session_expiry_interval_sec_exists:
1605 connack_packet.session_expiry_interval_sec = connack_session_expiry_interval_sec
1606 if connack_receive_maximum_exists:
1607 connack_packet.receive_maximum = connack_receive_maximum
1608 if connack_maximum_qos_exists:
1609 connack_packet.maximum_qos = _try_qos(connack_maximum_qos)
1610 if connack_retain_available_exists:
1611 connack_packet.retain_available = connack_retain_available
1612 if connack_maximum_packet_size_exists:
1613 connack_packet.maximum_packet_size = connack_maximum_packet_size
1614 connack_packet.assigned_client_identifier = connack_assigned_client_identifier
1615 if connack_topic_alias_maximum_exists:
1616 connack_packet.topic_alias_maximum = connack_topic_alias_maximum
1617 connack_packet.reason_string = connack_reason_string
1618 connack_packet.user_properties = _init_user_properties(connack_user_properties_tuples)
1619 if connack_wildcard_subscriptions_available_exist:
1620 connack_packet.wildcard_subscriptions_available = connack_wildcard_subscriptions_available
1621 if connack_subscription_identifiers_available_exists:
1622 connack_packet.subscription_identifiers_available = connack_subscription_identifiers_available
1623 if connack_shared_subscriptions_available_exists:
1624 connack_packet.shared_subscription_available = connack_shared_subscriptions_available
1625 if connack_server_keep_alive_exists:
1626 connack_packet.server_keep_alive_sec = connack_server_keep_alive
1627 connack_packet.response_information = connack_response_information
1628 connack_packet.server_reference = connack_server_reference
1629
1630 negotiated_settings = NegotiatedSettings()
1631 negotiated_settings.maximum_qos = _try_qos(settings_maximum_qos)
1632 negotiated_settings.session_expiry_interval_sec = settings_session_expiry_interval_sec
1633 negotiated_settings.receive_maximum_from_server = settings_receive_maximum_from_server
1634 negotiated_settings.maximum_packet_size_to_server = settings_maximum_packet_size_to_server
1635 negotiated_settings.topic_alias_maximum_to_server = settings_topic_alias_maximum_to_server
1636 negotiated_settings.topic_alias_maximum_to_client = settings_topic_alias_maximum_to_client
1637 negotiated_settings.server_keep_alive_sec = settings_server_keep_alive
1638 negotiated_settings.retain_available = settings_retain_available
1639 negotiated_settings.wildcard_subscriptions_available = settings_wildcard_subscriptions_available
1640 negotiated_settings.subscription_identifiers_available = settings_subscription_identifiers_available
1641 negotiated_settings.shared_subscriptions_available = settings_shared_subscriptions_available
1642 negotiated_settings.rejoined_session = settings_rejoined_session
1643 negotiated_settings.client_id = settings_client_id
1644
1645 self._on_lifecycle_connection_success_cb(
1646 LifecycleConnectSuccessData(
1647 connack_packet=connack_packet,
1648 negotiated_settings=negotiated_settings))
1649
1650 def _on_lifecycle_connection_failure(
1651 self,
1652 error_code,
1653 connack_packet_exists,
1654 connack_session_present,
1655 connack_reason_code,
1656 connack_session_expiry_interval_exists,
1657 connack_session_expiry_interval_sec,
1658 connack_receive_maximum_exists,
1659 connack_receive_maximum,
1660 connack_maximum_qos_exists,
1661 connack_maximum_qos,
1662 connack_retain_available_exists,
1663 connack_retain_available,
1664 connack_maximum_packet_size_exists,
1665 connack_maximum_packet_size,
1666 connack_assigned_client_identifier,
1667 connack_reason_string,
1668 connack_user_properties_tuples,
1669 connack_wildcard_subscriptions_available_exist,
1670 connack_wildcard_subscriptions_available,
1671 connack_subscription_identifiers_available_exists,
1672 connack_subscription_identifiers_available,
1673 connack_shared_subscriptions_available_exists,
1674 connack_shared_subscriptions_available,
1675 connack_server_keep_alive_exists,
1676 connack_server_keep_alive,
1677 connack_response_information,
1678 connack_server_reference):
1679 if self._on_lifecycle_connection_failure_cb is None:
1680 return
1681
1682 if connack_packet_exists:
1683 connack_packet = ConnackPacket()
1684 connack_packet.session_present = connack_session_present
1685 connack_packet.reason_code = _try_connect_reason_code(connack_reason_code)
1686 if connack_session_expiry_interval_exists:
1687 connack_packet.session_expiry_interval_sec = connack_session_expiry_interval_sec
1688 if connack_receive_maximum_exists:
1689 connack_packet.receive_maximum = connack_receive_maximum
1690 if connack_maximum_qos_exists:
1691 connack_packet.maximum_qos = _try_qos(connack_maximum_qos)
1692 if connack_retain_available_exists:
1693 connack_packet.retain_available = connack_retain_available
1694 if connack_maximum_packet_size_exists:
1695 connack_packet.maximum_packet_size = connack_maximum_packet_size
1696 connack_packet.assigned_client_identifier = connack_assigned_client_identifier
1697 connack_packet.reason_string = connack_reason_string
1698 connack_packet.user_properties = _init_user_properties(connack_user_properties_tuples)
1699 if connack_wildcard_subscriptions_available_exist:
1700 connack_packet.wildcard_subscriptions_available = connack_wildcard_subscriptions_available
1701 if connack_subscription_identifiers_available_exists:
1702 connack_packet.subscription_identifiers_available = connack_subscription_identifiers_available
1703 if connack_shared_subscriptions_available_exists:
1704 connack_packet.shared_subscription_available = connack_shared_subscriptions_available
1705 if connack_server_keep_alive_exists:
1706 connack_packet.server_keep_alive_sec = connack_server_keep_alive
1707 connack_packet.response_information = connack_response_information
1708 connack_packet.server_reference = connack_server_reference
1709
1710 self._on_lifecycle_connection_failure_cb(
1711 LifecycleConnectFailureData(
1712 connack_packet=connack_packet,
1713 exception=exceptions.from_code(error_code)))
1714 else:
1715 self._on_lifecycle_connection_failure_cb(
1716 LifecycleConnectFailureData(
1717 connack_packet=None, exception=exceptions.from_code(error_code)))
1718
1719 def _on_lifecycle_disconnection(
1720 self,
1721 error_code,
1722 disconnect_packet_exists,
1723 reason_code,
1724 session_expiry_interval_sec_exists,
1725 session_expiry_interval_sec,
1726 reason_string,
1727 user_properties_tuples,
1728 server_reference):
1729 if self._on_lifecycle_disconnection_cb is None:
1730 return
1731
1732 if disconnect_packet_exists:
1733 disconnect_packet = DisconnectPacket()
1734 disconnect_packet.reason_code = _try_disconnect_reason_code(reason_code)
1735 if session_expiry_interval_sec_exists:
1736 disconnect_packet.session_expiry_interval_sec = session_expiry_interval_sec
1737 disconnect_packet.reason_string = reason_string
1738 disconnect_packet.user_properties = _init_user_properties(user_properties_tuples)
1739 disconnect_packet.server_reference = server_reference
1740 self._on_lifecycle_disconnection_cb(
1741 LifecycleDisconnectData(
1742 disconnect_packet=disconnect_packet,
1743 exception=exceptions.from_code(error_code)))
1744 else:
1745 self._on_lifecycle_disconnection_cb(
1746 LifecycleDisconnectData(
1747 disconnect_packet=None,
1748 exception=exceptions.from_code(error_code)))
1749
1750
1751 @dataclass
1752 class _Mqtt5to3AdapterOptions:
1753 """This internal class stores the options that required for creating a new Mqtt3 connection from the mqtt5 client
1754 Args:
1755 host_name (str): Host name of the MQTT server to connect to.
1756 port (int): Network port of the MQTT server to connect to.
1757 client_id (str): A unique string identifying the client to the server. Used to restore session state between connections. If left empty, the broker will auto-assign a unique client id. When reconnecting, the mqtt5 client will always use the auto-assigned client id.
1758 socket_options (SocketOptions): The socket properties of the underlying MQTT connections made by the client or None if defaults are used.
1759 min_reconnect_delay_ms (int): The minimum amount of time to wait to reconnect after a disconnect. Exponential backoff is performed with jitter after each connection failure.
1760 max_reconnect_delay_ms (int): The maximum amount of time to wait to reconnect after a disconnect. Exponential backoff is performed with jitter after each connection failure.
1761 ping_timeout_ms (int): The time interval to wait after sending a PINGREQ for a PINGRESP to arrive. If one does not arrive, the client will close the current connection.
1762 keep_alive_secs (int): The keep alive value, in seconds, A PING will automatically be sent at this interval.
1763 ack_timeout_secs (int): The time interval to wait for an ack after sending a QoS 1+ PUBLISH, SUBSCRIBE, or UNSUBSCRIBE before failing the operation.
1764 clean_session (bool): Whether or not to start a clean session with each reconnect.
1765
1766 The default values are referred from awscrt.mqtt.Connection
1767 """
1768
1769 def __init__(
1770 self,
1771 host_name: str,
1772 port: int,
1773 client_id: str,
1774 socket_options: SocketOptions,
1775 min_reconnect_delay_ms: int,
1776 max_reconnect_delay_ms: int,
1777 ping_timeout_ms: int,
1778 keep_alive_secs: int,
1779 ack_timeout_secs: int,
1780 clean_session: int,
1781 disable_metrics: bool):
1782 self.host_name = host_name
1783 self.port = port
1784 self.client_id = "" if client_id is None else client_id
1785 self.socket_options = socket_options
1786 self.min_reconnect_delay_ms = 5 if min_reconnect_delay_ms is None else min_reconnect_delay_ms
1787 self.max_reconnect_delay_ms: int = 60 if max_reconnect_delay_ms is None else max_reconnect_delay_ms
1788 self.ping_timeout_ms: int = 3000 if ping_timeout_ms is None else ping_timeout_ms
1789 self.keep_alive_secs: int = 1200 if keep_alive_secs is None else keep_alive_secs
1790 self.ack_timeout_secs: int = 0 if ack_timeout_secs is None else ack_timeout_secs
1791 self.clean_session: bool = True if clean_session is None else clean_session
1792 self.disable_metrics: bool = False if disable_metrics is None else disable_metrics
1793
1794
1795 class Client(NativeResource):
1796 """This class wraps the aws-c-mqtt MQTT5 client to provide the basic MQTT5 pub/sub functionalities via the AWS Common Runtime
1797
1798 One Client class creates one connection.
1799
1800 Args:
1801 client_options (ClientOptions): The ClientOptions dataclass to used to configure the new Client.
1802
1803 """
1804
1805 def __init__(self, client_options: ClientOptions):
1806 super().__init__()
1807
1808 core = _ClientCore(client_options)
1809
1810 bootstrap = client_options.bootstrap
1811
1812 if not bootstrap:
1813 bootstrap = ClientBootstrap.get_or_create_static_default()
1814
1815 connect_options = client_options.connect_options
1816 if not connect_options:
1817 connect_options = ConnectPacket()
1818
1819 socket_options = client_options.socket_options
1820 if not socket_options:
1821 socket_options = SocketOptions()
1822
1823 # Handle metrics configuration
1824 if client_options.disable_metrics:
1825 self._metrics = None
1826 else:
1827 self._metrics = _create_metrics_mqtt5(client_options)
1828
1829 if not connect_options.will:
1830 is_will_none = True
1831 will = PublishPacket()
1832 else:
1833 is_will_none = False
1834 will = connect_options.will
1835
1836 websocket_is_none = client_options.websocket_handshake_transform is None
1837 self.tls_ctx = client_options.tls_ctx
1838 self._binding = _awscrt.mqtt5_client_new(self,
1839 client_options.host_name,
1840 client_options.port,
1841 bootstrap,
1842 socket_options,
1843 client_options.tls_ctx,
1844 client_options.http_proxy_options,
1845 connect_options.client_id,
1846 connect_options.keep_alive_interval_sec,
1847 connect_options.username,
1848 connect_options.password,
1849 connect_options.session_expiry_interval_sec,
1850 connect_options.request_response_information,
1851 connect_options.request_problem_information,
1852 connect_options.receive_maximum,
1853 connect_options.maximum_packet_size,
1854 connect_options.will_delay_interval_sec,
1855 connect_options.user_properties,
1856 is_will_none,
1857 will.qos,
1858 will.payload,
1859 will.retain,
1860 will.topic,
1861 will.payload_format_indicator,
1862 will.message_expiry_interval_sec,
1863 will.topic_alias,
1864 will.response_topic,
1865 will.correlation_data_bytes or will.correlation_data,
1866 will.content_type,
1867 will.user_properties,
1868 client_options.session_behavior,
1869 client_options.extended_validation_and_flow_control_options,
1870 client_options.offline_queue_behavior,
1871 client_options.retry_jitter_mode,
1872 client_options.min_reconnect_delay_ms,
1873 client_options.max_reconnect_delay_ms,
1874 client_options.min_connected_time_to_reset_reconnect_delay_ms,
1875 client_options.ping_timeout_ms,
1876 client_options.connack_timeout_ms,
1877 client_options.ack_timeout_sec,
1878 client_options.topic_aliasing_options,
1879 websocket_is_none,
1880 not client_options.disable_metrics,
1881 self._metrics,
1882 core)
1883
1884 # Store the options for adapter
1885 self.adapter_options = _Mqtt5to3AdapterOptions(
1886 host_name=client_options.host_name,
1887 port=client_options.port,
1888 client_id=connect_options.client_id,
1889 socket_options=socket_options,
1890 min_reconnect_delay_ms=client_options.min_reconnect_delay_ms,
1891 max_reconnect_delay_ms=client_options.max_reconnect_delay_ms,
1892 ping_timeout_ms=client_options.ping_timeout_ms,
1893 keep_alive_secs=connect_options.keep_alive_interval_sec,
1894 ack_timeout_secs=client_options.ack_timeout_sec,
1895 clean_session=(
1896 client_options.session_behavior < ClientSessionBehaviorType.REJOIN_ALWAYS if client_options.session_behavior else True),
1897 disable_metrics=client_options.disable_metrics)
1898
1899 def start(self):
1900 """Notifies the MQTT5 client that you want it maintain connectivity to the configured endpoint.
1901 The client will attempt to stay connected using the properties of the reconnect-related parameters in the mqtt5 client configuration.
1902
1903 This is an asynchronous operation."""
1904 _awscrt.mqtt5_client_start(self._binding)
1905
1906 def stop(self, disconnect_packet: DisconnectPacket = None):
1907 """Notifies the MQTT5 client that you want it to end connectivity to the configured endpoint, disconnecting any existing connection and halting any reconnect attempts.
1908
1909 This is an asynchronous operation.
1910
1911 Args:
1912 disconnect_packet (DisconnectPacket): (optional) Properties of a DISCONNECT packet to send as part of the shutdown process
1913 """
1914 is_disconnect_packet_none = disconnect_packet is None
1915
1916 if is_disconnect_packet_none:
1917 disconnect_packet = DisconnectPacket()
1918
1919 _awscrt.mqtt5_client_stop(self._binding,
1920 is_disconnect_packet_none,
1921 disconnect_packet.reason_code,
1922 disconnect_packet.session_expiry_interval_sec,
1923 disconnect_packet.reason_string,
1924 disconnect_packet.user_properties,
1925 disconnect_packet.server_reference)
1926
1927 def publish(self, publish_packet: PublishPacket):
1928 """Tells the client to attempt to send a PUBLISH packet.
1929
1930 Will return a future containing a PubAckResult if the publish is successful. The data in the PubAckResult varies depending on the QoS of the Publish. For QoS 0, the PubAckResult will not contain data. For QoS 1, the PubAckResult will contain a PubAckPacket. See PubAckResult class documentation for more info.
1931
1932 Args:
1933 publish_packet (PublishPacket): PUBLISH packet to send to the server
1934
1935 Returns:
1936 A future with a (:class:`PublishCompletionData`)
1937 """
1938
1939 future = Future()
1940
1941 # TODO QoS 2 Pubcomp will be handled through the same callback in the future
1942 def puback(error_code, qos, reason_code, reason_string, user_properties_tuples):
1943 publish_completion_data = PublishCompletionData()
1944 puback_packet = PubackPacket()
1945 publish_completion_data.puback = puback_packet
1946
1947 if error_code != 0:
1948 future.set_exception(exceptions.from_code(error_code))
1949 else:
1950 if qos == 1:
1951 puback_packet.reason_code = _try_puback_reason_code(reason_code)
1952 puback_packet.reason_string = reason_string
1953 puback_packet.user_properties = _init_user_properties(user_properties_tuples)
1954
1955 future.set_result(publish_completion_data)
1956
1957 _awscrt.mqtt5_client_publish(self._binding,
1958 publish_packet.qos,
1959 publish_packet.payload,
1960 publish_packet.retain,
1961 publish_packet.topic,
1962 publish_packet.payload_format_indicator,
1963 publish_packet.message_expiry_interval_sec,
1964 publish_packet.topic_alias,
1965 publish_packet.response_topic,
1966 publish_packet.correlation_data_bytes or publish_packet.correlation_data,
1967 publish_packet.content_type,
1968 publish_packet.user_properties,
1969 puback)
1970
1971 return future
1972
1973 def subscribe(self, subscribe_packet: SubscribePacket):
1974 """Tells the client to attempt to subscribe to one or more topic filters.
1975
1976 Args:
1977 subscribe_packet (SubscribePacket): SUBSCRIBE packet to send to the server
1978
1979 Returns:
1980 A future with a (:class:`SubackPacket`)
1981 """
1982
1983 future = Future()
1984
1985 def suback(error_code, reason_codes, reason_string, user_properties_tuples):
1986 suback_packet = SubackPacket()
1987 if error_code != 0:
1988 future.set_exception(exceptions.from_code(error_code))
1989 else:
1990 suback_packet.reason_codes = [_try_suback_reason_code(reason_code) for (reason_code) in reason_codes]
1991 suback_packet.reason_string = reason_string
1992 suback_packet.user_properties = _init_user_properties(user_properties_tuples)
1993 future.set_result(suback_packet)
1994
1995 _awscrt.mqtt5_client_subscribe(self._binding,
1996 subscribe_packet.subscriptions,
1997 subscribe_packet.subscription_identifier,
1998 subscribe_packet.user_properties,
1999 suback)
2000
2001 return future
2002
2003 def unsubscribe(self, unsubscribe_packet: UnsubscribePacket):
2004 """Tells the client to attempt to unsubscribe from one or more topic filters.
2005
2006 Args:
2007 unsubscribe_packet (UnsubscribePacket): UNSUBSCRIBE packet to send to the server
2008
2009 Returns:
2010 A future with a (:class:`UnsubackPacket`)
2011 """
2012
2013 future = Future()
2014
2015 def unsuback(error_code, reason_codes, reason_string, user_properties_tuples):
2016 unsuback_packet = UnsubackPacket()
2017 if error_code != 0:
2018 future.set_exception(exceptions.from_code(error_code))
2019 else:
2020 unsuback_packet.reason_codes = [_try_unsuback_reason_code(
2021 reason_code) for (reason_code) in reason_codes]
2022 unsuback_packet.reason_string = reason_string
2023 unsuback_packet.user_properties = _init_user_properties(user_properties_tuples)
2024 future.set_result(unsuback_packet)
2025
2026 _awscrt.mqtt5_client_unsubscribe(self._binding,
2027 unsubscribe_packet.topic_filters,
2028 unsubscribe_packet.user_properties,
2029 unsuback)
2030
2031 return future
2032
2033 def get_stats(self):
2034 """Queries the client's internal statistics for incomplete operations.
2035
2036 Returns:
2037 The (:class:`OperationStatisticsData`) containing the statistics
2038 """
2039
2040 result = _awscrt.mqtt5_client_get_stats(self._binding)
2041 return OperationStatisticsData(result[0], result[1], result[2], result[3])
2042
2043 def invoke_publish_acknowledgement(
2044 self, publish_acknowledgement_control_handle: 'PublishAcknowledgementControlHandle'):
2045 """Sends a publish acknowledgement for a QoS 1 PUBLISH that was previously acquired for manual control.
2046
2047 To use manual publish acknowledgement control, call acquire_publish_acknowledgement_control() within
2048 the on_publish_callback_fn callback to obtain a :class:`PublishAcknowledgementControlHandle`. Then call
2049 this method to send the publish acknowledgement.
2050
2051 Args:
2052 publish_acknowledgement_control_handle (PublishAcknowledgementControlHandle): An opaque handle obtained
2053 from acquire_publish_acknowledgement_control() within PublishReceivedData.
2054
2055 Raises:
2056 Exception: If the native client returns an error when invoking the publish acknowledgement.
2057 """
2058
2059 _awscrt.mqtt5_client_invoke_publish_acknowledgement(
2060 self._binding,
2061 publish_acknowledgement_control_handle._control_id
2062 )
2063
2064 def new_connection(self, on_connection_interrupted=None, on_connection_resumed=None,
2065 on_connection_success=None, on_connection_failure=None, on_connection_closed=None):
2066 from awscrt.mqtt import Connection
2067 """ Returns a new Mqtt3 Connection Object wraps the Mqtt5 client.
2068
2069 Args:
2070 on_connection_interrupted: Optional callback invoked whenever the MQTT connection is lost.
2071 The MQTT client will automatically attempt to reconnect.
2072 The function should take the following arguments return nothing:
2073
2074 * `connection` (:class:`Connection`): This MQTT Connection.
2075
2076 * `error` (:class:`awscrt.exceptions.AwsCrtError`): Exception which caused connection loss.
2077
2078 * `**kwargs` (dict): Forward-compatibility kwargs.
2079
2080 on_connection_resumed: Optional callback invoked whenever the MQTT connection
2081 is automatically resumed. Function should take the following arguments and return nothing:
2082
2083 * `connection` (:class:`Connection`): This MQTT Connection
2084
2085 * `return_code` (:class:`ConnectReturnCode`): Connect return
2086 code received from the server.
2087
2088 * `session_present` (bool): True if resuming existing session. False if new session.
2089 Note that the server has forgotten all previous subscriptions if this is False.
2090 Subscriptions can be re-established via resubscribe_existing_topics().
2091
2092 * `**kwargs` (dict): Forward-compatibility kwargs.
2093
2094 on_connection_success: Optional callback invoked whenever the connection successfully connects.
2095 This callback is invoked for every successful connect and every successful reconnect.
2096
2097 Function should take the following arguments and return nothing:
2098
2099 * `connection` (:class:`Connection`): This MQTT Connection
2100
2101 * `callback_data` (:class:`OnConnectionSuccessData`): The data returned from the connection success.
2102
2103 on_connection_failure: Optional callback invoked whenever the connection fails to connect.
2104 This callback is invoked for every failed connect and every failed reconnect.
2105
2106 Function should take the following arguments and return nothing:
2107
2108 * `connection` (:class:`Connection`): This MQTT Connection
2109
2110 * `callback_data` (:class:`OnConnectionFailureData`): The data returned from the connection failure.
2111
2112 on_connection_closed: Optional callback invoked whenever the connection has been disconnected and shutdown successfully.
2113 Function should take the following arguments and return nothing:
2114
2115 * `connection` (:class:`Connection`): This MQTT Connection
2116
2117 * `callback_data` (:class:`OnConnectionClosedData`): The data returned from the connection close.
2118
2119
2120 Returns:
2121 The (:class:`Connection`) wrapper for the mqtt5 client
2122 """
2123 return Connection(
2124 self,
2125 self.adapter_options.host_name,
2126 self.adapter_options.port,
2127 self.adapter_options.client_id,
2128 clean_session=self.adapter_options.clean_session,
2129 on_connection_interrupted=on_connection_interrupted,
2130 on_connection_resumed=on_connection_resumed,
2131 on_connection_success=on_connection_success,
2132 on_connection_failure=on_connection_failure,
2133 on_connection_closed=on_connection_closed,
2134 reconnect_min_timeout_secs=self.adapter_options.min_reconnect_delay_ms,
2135 reconnect_max_timeout_secs=self.adapter_options.max_reconnect_delay_ms,
2136 keep_alive_secs=self.adapter_options.keep_alive_secs,
2137 ping_timeout_ms=self.adapter_options.ping_timeout_ms,
2138 protocol_operation_timeout_ms=self.adapter_options.ack_timeout_secs * 1000,
2139 socket_options=self.adapter_options.socket_options,
2140
2141 # For the arguments below, set it to `None` will directly use the options from mqtt5 client underlying.
2142 will=None,
2143 username=None,
2144 password=None,
2145 # Similar to previous options, set it False will use mqtt5 setup for
2146 # websockets. It is not necessary means the websocket is disabled.
2147 use_websockets=False,
2148 websocket_proxy_options=None,
2149 websocket_handshake_transform=None,
2150 proxy_options=None,
2151 disable_metrics=self.adapter_options.disable_metrics
2152 )