Debian Codegraph @

awscrt/mqtt.py

raw symbols SCIP
1 """
2 MQTT
3
4 All network operations in `awscrt.mqtt` are asynchronous.
5 """
6
7 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8 # SPDX-License-Identifier: Apache-2.0.
9 import _awscrt
10 from concurrent.futures import Future
11 from enum import IntEnum
12 from inspect import signature
13 from awscrt import NativeResource
14 import awscrt.exceptions
15 from awscrt.http import HttpProxyOptions, HttpRequest
16 from awscrt.io import ClientBootstrap, ClientTlsContext, SocketOptions
17 from dataclasses import dataclass
18 from awscrt.mqtt5 import Client as Mqtt5Client
19 from awscrt.aws_iot_metrics import AWSIoTMetrics, _create_metrics_mqtt3
20
21
22 class QoS(IntEnum):
23 """Quality of Service enumeration
24
25 [MQTT-4.3]
26 """
27
28 AT_MOST_ONCE = 0
29 """QoS 0 - At most once delivery
30
31 The message is delivered according to the capabilities of the underlying network.
32 No response is sent by the receiver and no retry is performed by the sender.
33 The message arrives at the receiver either once or not at all.
34 """
35
36 AT_LEAST_ONCE = 1
37 """QoS 1 - At least once delivery
38
39 This quality of service ensures that the message arrives at the receiver at least once.
40 """
41
42 EXACTLY_ONCE = 2
43 """QoS 2 - Exactly once delivery
44
45 This is the highest quality of service, for use when neither loss nor
46 duplication of messages are acceptable. There is an increased overhead
47 associated with this quality of service.
48
49 Note that, while this client supports QoS 2, the AWS IoT Core server
50 does not support QoS 2 at time of writing (May 2020).
51 """
52
53 def to_mqtt5(self):
54 from awscrt.mqtt5 import QoS as Mqtt5QoS
55 """Convert a Mqtt3 QoS to Mqtt5 QoS
56
57 """
58 return Mqtt5QoS(self.value)
59
60
61 def _try_qos(qos_value):
62 """Return None if the value cannot be converted to Qos (ex: 0x80 subscribe failure)"""
63 try:
64 return QoS(qos_value)
65 except Exception:
66 return None
67
68
69 class ConnectReturnCode(IntEnum):
70 """Connect return code enumeration.
71
72 [MQTT-3.2.2.3]
73 """
74
75 ACCEPTED = 0
76 """Connection Accepted."""
77
78 UNACCEPTABLE_PROTOCOL_VERSION = 1
79 """Connection Refused, unacceptable protocol version.
80
81 The Server does not support the level of the MQTT protocol requested by the Client.
82 """
83
84 IDENTIFIER_REJECTED = 2
85 """Connection Refused, identifier rejected.
86
87 The Client identifier is correct UTF-8 but not allowed by the Server.
88 """
89
90 SERVER_UNAVAILABLE = 3
91 """Connection Refused, Server unavailable.
92
93 The Network Connection has been made but the MQTT service is unavailable.
94 """
95
96 BAD_USERNAME_OR_PASSWORD = 4
97 """Connection Refused, bad user name or password.
98
99 The data in the user name or password is malformed.
100 """
101
102 NOT_AUTHORIZED = 5
103 """Connection Refused, not authorized.
104
105 The Client is not authorized to connect.
106 """
107
108
109 class Will:
110 """A Will message is published by the server if a client is lost unexpectedly.
111
112 The Will message is stored on the server when a client connects.
113 It is published if the client connection is lost without the server
114 receiving a DISCONNECT packet.
115
116 [MQTT-3.1.2-8]
117
118 Args:
119 topic (str): Topic to publish Will message on.
120 qos (QoS): QoS used when publishing the Will message.
121 payload (bytes): Content of Will message.
122 retain (bool): Whether the Will message is to be retained when it is published.
123
124 Attributes:
125 topic (str): Topic to publish Will message on.
126 qos (QoS): QoS used when publishing the Will message.
127 payload (bytes): Content of Will message.
128 retain (bool): Whether the Will message is to be retained when it is published.
129 """
130 __slots__ = ('topic', 'qos', 'payload', 'retain')
131
132 def __init__(self, topic, qos, payload, retain):
133 self.topic = topic
134 self.qos = qos
135 self.payload = payload
136 self.retain = retain
137
138
139 @dataclass
140 class OnConnectionSuccessData:
141 """Dataclass containing data related to a on_connection_success Callback
142
143 Args:
144 return_code (ConnectReturnCode): Connect return. code received from the server.
145 session_present (bool): True if the connection resumes an existing session.
146 False if new session. Note that the server has forgotten all previous subscriptions
147 if this is False.
148 Subscriptions can be re-established via resubscribe_existing_topics() if the connection was a reconnection.
149 """
150 return_code: ConnectReturnCode = None
151 session_present: bool = False
152
153
154 @dataclass
155 class OnConnectionFailureData:
156 """Dataclass containing data related to a on_connection_failure Callback
157
158 Args:
159 error (ConnectReturnCode): Error code with reason for connection failure
160 """
161 error: awscrt.exceptions.AwsCrtError = None
162
163
164 @dataclass
165 class OnConnectionClosedData:
166 """Dataclass containing data related to a on_connection_closed Callback.
167 Currently unused.
168 """
169 pass
170
171
172 class Client(NativeResource):
173 """MQTT client.
174
175 Args:
176 bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating new socket connections.
177 If None is provided, the default singleton is used.
178
179 tls_ctx (Optional[ClientTlsContext]): TLS context for secure socket connections.
180 If None is provided, then an unencrypted connection is used.
181 """
182
183 __slots__ = ('tls_ctx')
184
185 def __init__(self, bootstrap=None, tls_ctx=None):
186 assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None
187 assert tls_ctx is None or isinstance(tls_ctx, ClientTlsContext)
188
189 super().__init__()
190 self.tls_ctx = tls_ctx
191 if not bootstrap:
192 bootstrap = ClientBootstrap.get_or_create_static_default()
193 self._binding = _awscrt.mqtt_client_new(bootstrap, tls_ctx)
194
195
196 @dataclass
197 class OperationStatisticsData:
198 """Dataclass containing some simple statistics about the current state of the connection's queue of operations
199
200 Args:
201 incomplete_operation_count (int): total number of operations submitted to the connection that have not yet been completed. Unacked operations are a subset of this.
202 incomplete_operation_size (int): total packet size of operations submitted to the connection that have not yet been completed. Unacked operations are a subset of this.
203 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.
204 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.
205 """
206 incomplete_operation_count: int = 0
207 incomplete_operation_size: int = 0
208 unacked_operation_count: int = 0
209 unacked_operation_size: int = 0
210
211
212 class Connection(NativeResource):
213 """MQTT client connection.
214
215 Args:
216 client (Client): MQTT client to spawn connection from.
217
218 host_name (str): Server name to connect to.
219
220 port (int): Server port to connect to.
221
222 client_id (str): ID to place in CONNECT packet. Must be unique across all devices/clients.
223 If an ID is already in use, the other client will be disconnected.
224
225 clean_session (bool): Whether or not to start a clean session with each reconnect.
226 If True, the server will forget all subscriptions with each reconnect.
227 Set False to request that the server resume an existing session
228 or start a new session that may be resumed after a connection loss.
229 The `session_present` bool in the connection callback informs
230 whether an existing session was successfully resumed.
231 If an existing session is resumed, the server remembers previous subscriptions
232 and sends messages (with QoS1 or higher) that were published while the client was offline.
233
234 on_connection_interrupted: Optional callback invoked whenever the MQTT connection is lost.
235 The MQTT client will automatically attempt to reconnect.
236 The function should take the following arguments return nothing:
237
238 * `connection` (:class:`Connection`): This MQTT Connection.
239
240 * `error` (:class:`awscrt.exceptions.AwsCrtError`): Exception which caused connection loss.
241
242 * `**kwargs` (dict): Forward-compatibility kwargs.
243
244 on_connection_resumed: Optional callback invoked whenever the MQTT connection
245 is automatically resumed. Function should take the following arguments and return nothing:
246
247 * `connection` (:class:`Connection`): This MQTT Connection
248
249 * `return_code` (:class:`ConnectReturnCode`): Connect return
250 code received from the server.
251
252 * `session_present` (bool): True if resuming existing session. False if new session.
253 Note that the server has forgotten all previous subscriptions if this is False.
254 Subscriptions can be re-established via resubscribe_existing_topics().
255
256 * `**kwargs` (dict): Forward-compatibility kwargs.
257
258 on_connection_success: Optional callback invoked whenever the connection successfully connects.
259 This callback is invoked for every successful connect and every successful reconnect.
260
261 Function should take the following arguments and return nothing:
262
263 * `connection` (:class:`Connection`): This MQTT Connection
264
265 * `callback_data` (:class:`OnConnectionSuccessData`): The data returned from the connection success.
266
267 on_connection_failure: Optional callback invoked whenever the connection fails to connect.
268 This callback is invoked for every failed connect and every failed reconnect.
269
270 Function should take the following arguments and return nothing:
271
272 * `connection` (:class:`Connection`): This MQTT Connection
273
274 * `callback_data` (:class:`OnConnectionFailureData`): The data returned from the connection failure.
275
276 on_connection_closed: Optional callback invoked whenever the connection has been disconnected and shutdown successfully.
277 Function should take the following arguments and return nothing:
278
279 * `connection` (:class:`Connection`): This MQTT Connection
280
281 * `callback_data` (:class:`OnConnectionClosedData`): The data returned from the connection close.
282
283 reconnect_min_timeout_secs (int): Minimum time to wait between reconnect attempts.
284 Must be <= `reconnect_max_timeout_secs`.
285 Wait starts at min and doubles with each attempt until max is reached.
286
287 reconnect_max_timeout_secs (int): Maximum time to wait between reconnect attempts.
288 Must be >= `reconnect_min_timeout_secs`.
289 Wait starts at min and doubles with each attempt until max is reached.
290
291 keep_alive_secs (int): The keep alive value, in seconds, to send in CONNECT packet.
292 A PING will automatically be sent at this interval.
293 The server will assume the connection is lost if no PING is received after 1.5X this value.
294 This duration must be longer than ping_timeout_ms.
295
296 ping_timeout_ms (int): Milliseconds to wait for ping response before client assumes
297 the connection is invalid and attempts to reconnect.
298 This duration must be shorter than `keep_alive_secs`.
299
300 protocol_operation_timeout_ms (int): Milliseconds to wait for the response to the operation
301 requires response by protocol. Set to zero to disable timeout. Otherwise,
302 the operation will fail if no response is received within this amount of time after
303 the packet is written to the socket
304 It applied to PUBLISH (QoS>0) and UNSUBSCRIBE now.
305
306 will (Will): Will to send with CONNECT packet. The will is
307 published by the server when its connection to the client is unexpectedly lost.
308
309 username (str): Username to connect with.
310
311 password (str): Password to connect with.
312
313 socket_options (Optional[awscrt.io.SocketOptions]): Optional socket options.
314
315 use_websocket (bool): If true, connect to MQTT over websockets.
316
317 websocket_proxy_options (Optional[awscrt.http.HttpProxyOptions]):
318 Optional proxy options for websocket connections. Deprecated, use `proxy_options` instead.
319
320 websocket_handshake_transform: Optional function to transform websocket handshake request.
321 If provided, function is called each time a websocket connection is attempted.
322 The function may modify the HTTP request before it is sent to the server.
323 See :class:`WebsocketHandshakeTransformArgs` for more info.
324 Function should take the following arguments and return nothing:
325
326 * `transform_args` (:class:`WebsocketHandshakeTransformArgs`):
327 Contains HTTP request to be transformed. Function must call
328 `transform_args.done()` when complete.
329
330 * `**kwargs` (dict): Forward-compatibility kwargs.
331
332 proxy_options (Optional[awscrt.http.HttpProxyOptions]):
333 Optional proxy options for all connections.
334
335 disable_metrics (bool): Disable IoT SDK metrics in MQTT CONNECT packet username field, including SDK name, version, and platform. Default to False.
336
337 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.
338 """
339
340 def __init__(self,
341 client,
342 host_name,
343 port,
344 client_id,
345 clean_session=True,
346 on_connection_interrupted=None,
347 on_connection_resumed=None,
348 reconnect_min_timeout_secs=5,
349 reconnect_max_timeout_secs=60,
350 keep_alive_secs=1200,
351 ping_timeout_ms=3000,
352 protocol_operation_timeout_ms=0,
353 will=None,
354 username=None,
355 password=None,
356 socket_options=None,
357 use_websockets=False,
358 websocket_proxy_options=None,
359 websocket_handshake_transform=None,
360 proxy_options=None,
361 on_connection_success=None,
362 on_connection_failure=None,
363 on_connection_closed=None,
364 disable_metrics=False,
365 metrics=None,
366 ):
367
368 assert isinstance(client, Client) or isinstance(client, Mqtt5Client)
369 assert callable(on_connection_interrupted) or on_connection_interrupted is None
370 assert callable(on_connection_resumed) or on_connection_resumed is None
371 assert isinstance(will, Will) or will is None
372 assert isinstance(socket_options, SocketOptions) or socket_options is None
373 assert isinstance(websocket_proxy_options, HttpProxyOptions) or websocket_proxy_options is None
374 assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None
375 assert callable(websocket_handshake_transform) or websocket_handshake_transform is None
376 assert callable(on_connection_success) or on_connection_success is None
377 assert callable(on_connection_failure) or on_connection_failure is None
378 assert callable(on_connection_closed) or on_connection_closed is None
379
380 if reconnect_min_timeout_secs > reconnect_max_timeout_secs:
381 raise ValueError("'reconnect_min_timeout_secs' cannot exceed 'reconnect_max_timeout_secs'")
382
383 if keep_alive_secs * 1000 <= ping_timeout_ms:
384 raise ValueError("'keep_alive_secs' duration must be longer than 'ping_timeout_ms'")
385
386 if proxy_options and websocket_proxy_options:
387 raise ValueError("'websocket_proxy_options' has been deprecated in favor of 'proxy_options'. "
388 "Both parameters may not be set.")
389
390 super().__init__()
391
392 # init-only
393 self.client = client
394 self._client_version = 5 if isinstance(client, Mqtt5Client) else 3
395 self._on_connection_interrupted_cb = on_connection_interrupted
396 self._on_connection_resumed_cb = on_connection_resumed
397 self._use_websockets = use_websockets
398 self._ws_handshake_transform_cb = websocket_handshake_transform
399 self._on_connection_success_cb = on_connection_success
400 self._on_connection_failure_cb = on_connection_failure
401 self._on_connection_closed_cb = on_connection_closed
402
403 # may be changed at runtime, take effect the the next time connect/reconnect occurs
404 self.client_id = client_id
405 self.host_name = host_name
406 self.port = port
407 self.clean_session = clean_session
408 self.reconnect_min_timeout_secs = reconnect_min_timeout_secs
409 self.reconnect_max_timeout_secs = reconnect_max_timeout_secs
410 self.keep_alive_secs = keep_alive_secs
411 self.ping_timeout_ms = ping_timeout_ms
412 self.protocol_operation_timeout_ms = protocol_operation_timeout_ms
413 self.will = will
414 self.username = username
415 self.password = password
416 self.socket_options = socket_options if socket_options else SocketOptions()
417 self.proxy_options = proxy_options if proxy_options else websocket_proxy_options
418 if disable_metrics:
419 self._metrics = None
420 else:
421 self._metrics = _create_metrics_mqtt3(metrics, self.proxy_options, self.client.tls_ctx)
422
423 self._binding = _awscrt.mqtt_client_connection_new(
424 self,
425 client,
426 use_websockets,
427 self._client_version
428 )
429
430 def _check_uses_old_message_callback_signature(self, callback):
431 # The callback used to have fewer args. Passing only those args, if it
432 # only has two args and no forward-compatibility to cover case where
433 # user function failed to take forward-compatibility **kwargs.
434
435 callback_sig = signature(callback)
436 try:
437 # try new signature
438 callback_sig.bind(topic='topic', payload='payload', dup=True, qos=QoS(1), retain=True)
439 return False
440 except TypeError:
441 # try old signature
442 callback_sig.bind(topic='topic', payload='payload')
443 return True
444
445 def _on_connection_interrupted(self, error_code):
446 if self._on_connection_interrupted_cb:
447 self._on_connection_interrupted_cb(connection=self, error=awscrt.exceptions.from_code(error_code))
448
449 def _on_connection_resumed(self, return_code, session_present):
450 if self._on_connection_resumed_cb:
451 self._on_connection_resumed_cb(
452 connection=self,
453 return_code=ConnectReturnCode(return_code),
454 session_present=session_present)
455
456 def _ws_handshake_transform(self, http_request_binding, http_headers_binding, native_userdata):
457 if self._ws_handshake_transform_cb is None:
458 _awscrt.mqtt_ws_handshake_transform_complete(None, native_userdata, 0)
459 return
460
461 def _on_complete(f):
462 error_code = 0
463 hs_exception = f.exception()
464 if isinstance(hs_exception, awscrt.exceptions.AwsCrtError):
465 error_code = hs_exception.code
466 _awscrt.mqtt_ws_handshake_transform_complete(f.exception(), native_userdata, error_code)
467
468 future = Future()
469 future.add_done_callback(_on_complete)
470 http_request = HttpRequest._from_bindings(http_request_binding, http_headers_binding)
471 transform_args = WebsocketHandshakeTransformArgs(self, http_request, future)
472 try:
473 self._ws_handshake_transform_cb(transform_args=transform_args)
474 except Exception as e:
475 # Call set_done() if user failed to do so before uncaught exception was raised,
476 # there's a chance the callback wasn't callable and user has no idea we tried to hand them the baton.
477 if not future.done():
478 transform_args.set_done(e)
479
480 def _on_connection_closed(self):
481 if self:
482 if self._on_connection_closed_cb:
483 data = OnConnectionClosedData()
484 self._on_connection_closed_cb(connection=self, callback_data=data)
485
486 def _on_connection_success(self, return_code, session_present):
487 if self:
488 if self._on_connection_success_cb:
489 data = OnConnectionSuccessData(
490 return_code=ConnectReturnCode(return_code),
491 session_present=session_present)
492 self._on_connection_success_cb(connection=self, callback_data=data)
493
494 def _on_connection_failure(self, error_code):
495 if self:
496 if self._on_connection_failure_cb:
497 data = OnConnectionFailureData(error=awscrt.exceptions.from_code(error_code))
498 self._on_connection_failure_cb(connection=self, callback_data=data)
499
500 def connect(self):
501 """Open the actual connection to the server (async).
502
503 Returns:
504 concurrent.futures.Future: Future which completes when connection succeeds or fails.
505 If connection fails, Future will contain an exception.
506 If connection succeeds, Future will contain a dict with the following members:
507
508 * ['session_present'] (bool): is True if resuming existing session and False if new session.
509 """
510 future = Future()
511
512 def on_connect(error_code, return_code, session_present):
513 if return_code:
514 future.set_exception(Exception(ConnectReturnCode(return_code)))
515 elif error_code:
516 future.set_exception(awscrt.exceptions.from_code(error_code))
517 else:
518 future.set_result(dict(session_present=session_present))
519
520 try:
521 _awscrt.mqtt_client_connection_connect(
522 self._binding,
523 self.client_id,
524 self.host_name,
525 self.port,
526 self.socket_options,
527 self.client.tls_ctx,
528 self.reconnect_min_timeout_secs,
529 self.reconnect_max_timeout_secs,
530 self.keep_alive_secs,
531 self.ping_timeout_ms,
532 self.protocol_operation_timeout_ms,
533 self.will,
534 self.username,
535 self.password,
536 self.clean_session,
537 on_connect,
538 self.proxy_options,
539 self._metrics
540 )
541
542 except Exception as e:
543 future.set_exception(e)
544
545 return future
546
547 def reconnect(self):
548 """DEPRECATED.
549
550 awscrt.mqtt.ClientConnection automatically reconnects.
551 To cease reconnect attempts, call disconnect().
552 To resume the connection, call connect().
553 """
554 future = Future()
555
556 def on_connect(error_code, return_code, session_present):
557 if return_code:
558 future.set_exception(Exception(ConnectReturnCode(return_code)))
559 elif error_code:
560 future.set_exception(awscrt.exceptions.from_code(error_code))
561 else:
562 future.set_result(dict(session_present=session_present))
563
564 try:
565 _awscrt.mqtt_client_connection_reconnect(self._binding, on_connect)
566 except Exception as e:
567 future.set_exception(e)
568
569 return future
570
571 def disconnect(self):
572 """Close the connection (async).
573
574 Returns:
575 concurrent.futures.Future: Future which completes when the connection is closed.
576 The future will contain an empty dict.
577 """
578
579 future = Future()
580
581 def on_disconnect():
582 future.set_result(dict())
583
584 try:
585 _awscrt.mqtt_client_connection_disconnect(self._binding, on_disconnect)
586
587 except Exception as e:
588 future.set_exception(e)
589
590 return future
591
592 def subscribe(self, topic, qos, callback=None):
593 """Subscribe to a topic filter (async).
594
595 The client sends a SUBSCRIBE packet and the server responds with a SUBACK.
596
597 subscribe() may be called while the device is offline, though the async
598 operation cannot complete successfully until the connection resumes.
599
600 Once subscribed, `callback` is invoked each time a message matching
601 the `topic` is received. It is possible for such messages to arrive before
602 the SUBACK is received.
603
604 Args:
605 topic (str): Subscribe to this topic filter, which may include wildcards.
606 qos (QoS): Maximum requested QoS that server may use when sending messages to the client.
607 The server may grant a lower QoS in the SUBACK (see returned Future)
608 callback: Optional callback invoked when message received.
609 Function should take the following arguments and return nothing:
610
611 * `topic` (str): Topic receiving message.
612
613 * `payload` (bytes): Payload of message.
614
615 * `dup` (bool): DUP flag. If True, this might be re-delivery
616 of an earlier attempt to send the message.
617
618 * `qos` (:class:`QoS`): Quality of Service used to deliver the message.
619
620 * `retain` (bool): Retain flag. If True, the message was sent
621 as a result of a new subscription being made by the client.
622
623 * `**kwargs` (dict): Forward-compatibility kwargs.
624
625 Returns:
626 Tuple[concurrent.futures.Future, int]: Tuple containing a Future and
627 the ID of the SUBSCRIBE packet. The Future completes when a
628 SUBACK is received from the server. If successful, the Future will
629 contain a dict with the following members:
630
631 * ['packet_id'] (int): ID of the SUBSCRIBE packet being acknowledged.
632
633 * ['topic'] (str): Topic filter of the SUBSCRIBE packet being acknowledged.
634
635 * ['qos'] (:class:`QoS`): Maximum QoS that was granted by the server.
636 This may be lower than the requested QoS.
637
638 If unsuccessful, the Future contains an exception. The exception
639 will be a :class:`SubscribeError` if a SUBACK was received
640 in which the server rejected the subscription. Other exception
641 types indicate other errors with the operation.
642 """
643
644 future = Future()
645 packet_id = 0
646
647 if callback:
648 uses_old_signature = self._check_uses_old_message_callback_signature(callback)
649
650 def callback_wrapper(topic, payload, dup, qos, retain):
651 if uses_old_signature:
652 callback(topic=topic, payload=payload)
653 else:
654 callback(topic=topic, payload=payload, dup=dup, qos=QoS(qos), retain=retain)
655
656 else:
657 callback_wrapper = None
658
659 def suback(packet_id, topic, qos, error_code):
660 if error_code:
661 future.set_exception(awscrt.exceptions.from_code(error_code))
662 else:
663 qos = _try_qos(qos)
664 if qos is None:
665 future.set_exception(SubscribeError(topic))
666 else:
667 future.set_result(dict(
668 packet_id=packet_id,
669 topic=topic,
670 qos=qos,
671 ))
672
673 try:
674 assert callable(callback) or callback is None
675 from awscrt.mqtt5 import QoS as Mqtt5QoS
676 if (isinstance(qos, Mqtt5QoS)):
677 qos = qos.to_mqtt3()
678 assert isinstance(qos, QoS)
679 packet_id = _awscrt.mqtt_client_connection_subscribe(
680 self._binding, topic, qos.value, callback_wrapper, suback)
681 except Exception as e:
682 future.set_exception(e)
683
684 return future, packet_id
685
686 def on_message(self, callback):
687 """Set callback to be invoked when ANY message is received.
688
689 callback: Callback to invoke when message received, or None to disable.
690 Function should take the following arguments and return nothing:
691
692 * `topic` (str): Topic receiving message.
693
694 * `payload` (bytes): Payload of message.
695
696 * `dup` (bool): DUP flag. If True, this might be re-delivery
697 of an earlier attempt to send the message.
698
699 * `qos` (:class:`QoS`): Quality of Service used to deliver the message.
700
701 * `retain` (bool): Retain flag. If True, the message was sent
702 as a result of a new subscription being made by the client.
703
704 * `**kwargs` (dict): Forward-compatibility kwargs.
705 """
706 assert callable(callback) or callback is None
707
708 if callback:
709
710 uses_old_signature = self._check_uses_old_message_callback_signature(callback)
711
712 def callback_wrapper(topic, payload, dup, qos, retain):
713 if uses_old_signature:
714 callback(topic=topic, payload=payload)
715 else:
716 callback(topic=topic, payload=payload, dup=dup, qos=QoS(qos), retain=retain)
717
718 else:
719 callback_wrapper = None
720
721 _awscrt.mqtt_client_connection_on_message(self._binding, callback_wrapper)
722
723 def unsubscribe(self, topic):
724 """Unsubscribe from a topic filter (async).
725
726 The client sends an UNSUBSCRIBE packet, and the server responds with an UNSUBACK.
727
728 Args:
729 topic (str): Unsubscribe from this topic filter.
730
731 Returns:
732 Tuple[concurrent.futures.Future, int]: Tuple containing a Future and
733 the ID of the UNSUBSCRIBE packet. The Future completes when an
734 UNSUBACK is received from the server. If successful, the Future
735 will contain a dict with the following members:
736
737 * ['packet_id'] (int): ID of the UNSUBSCRIBE packet being acknowledged.
738 """
739 future = Future()
740 packet_id = 0
741
742 def unsuback(packet_id, error_code):
743 if error_code != 0:
744 future.set_exception(awscrt.exceptions.from_code(error_code))
745 else:
746 future.set_result(dict(packet_id=packet_id))
747
748 try:
749 packet_id = _awscrt.mqtt_client_connection_unsubscribe(self._binding, topic, unsuback)
750
751 except Exception as e:
752 future.set_exception(e)
753
754 return future, packet_id
755
756 def resubscribe_existing_topics(self):
757 """
758 Subscribe again to all current topics.
759
760 This is to help when resuming a connection with a clean session.
761
762 **Important**: Currently the resubscribe function does not take the AWS IoT Core maximum subscriptions
763 per subscribe request quota into account. If the client has more subscriptions than the maximum,
764 resubscribing must be done manually using the `subscribe()` function for each desired topic
765 filter. The client will be disconnected by AWS IoT Core if the resubscribe exceeds the subscriptions
766 per subscribe request quota.
767
768 The AWS IoT Core maximum subscriptions per subscribe request quota is listed at the following URL:
769 https://docs.aws.amazon.com/general/latest/gr/iot-core.html#genref_max_subscriptions_per_subscribe_request
770
771 Returns:
772 Tuple[concurrent.futures.Future, int]: Tuple containing a Future and
773 the ID of the SUBSCRIBE packet. The Future completes when a SUBACK
774 is received from the server. If successful, the Future will contain
775 a dict with the following members:
776
777 * ['packet_id']: ID of the SUBSCRIBE packet being acknowledged,
778 or None if there were no topics to resubscribe to.
779
780 * ['topics']: A list of (topic, qos) tuples, where qos will be
781 None if the topic failed to resubscribe. If there were no topics
782 to resubscribe to, then the list will be empty.
783 """
784 packet_id = 0
785 future = Future()
786
787 def on_suback(packet_id, topic_qos_tuples, error_code):
788 if error_code:
789 future.set_exception(awscrt.exceptions.from_code(error_code))
790 else:
791 future.set_result(dict(
792 packet_id=packet_id,
793 topics=[(topic, _try_qos(qos)) for (topic, qos) in topic_qos_tuples],
794 ))
795
796 try:
797 packet_id = _awscrt.mqtt_client_connection_resubscribe_existing_topics(self._binding, on_suback)
798 if packet_id is None:
799 # There were no topics to resubscribe to.
800 future.set_result(dict(packet_id=None, topics=[]))
801
802 except Exception as e:
803 future.set_exception(e)
804
805 return future, packet_id
806
807 def publish(self, topic, payload, qos, retain=False):
808 """Publish message (async).
809
810 If the device is offline, the PUBLISH packet will be sent once the connection resumes.
811
812 Args:
813 topic (str): Topic name.
814 payload (Union[str, bytes, bytearray]): Contents of message.
815 qos (QoS): Quality of Service for delivering this message.
816 retain (bool): If True, the server will store the message and its QoS
817 so that it can be delivered to future subscribers whose subscriptions
818 match its topic name.
819
820 Returns:
821 Tuple[concurrent.futures.Future, int]: Tuple containing a Future and
822 the ID of the PUBLISH packet. The QoS determines when the Future completes:
823
824 * For QoS 0, completes as soon as the packet is sent.
825 * For QoS 1, completes when PUBACK is received.
826 * For QoS 2, completes when PUBCOMP is received.
827
828 If successful, the Future will contain a dict with the following members:
829
830 * ['packet_id'] (int): ID of the PUBLISH packet that is complete.
831 """
832 future = Future()
833 packet_id = 0
834
835 def puback(packet_id, error_code):
836 if error_code != 0:
837 future.set_exception(awscrt.exceptions.from_code(error_code))
838 else:
839 future.set_result(dict(packet_id=packet_id))
840
841 try:
842 from awscrt.mqtt5 import QoS as Mqtt5QoS
843 if (isinstance(qos, Mqtt5QoS)):
844 qos = qos.to_mqtt3()
845 assert isinstance(qos, QoS)
846 packet_id = _awscrt.mqtt_client_connection_publish(self._binding, topic, payload, qos.value, retain, puback)
847 except Exception as e:
848 future.set_exception(e)
849
850 return future, packet_id
851
852 def get_stats(self):
853 """Queries the connection's internal statistics for incomplete operations.
854
855 Returns:
856 The (:class:`OperationStatisticsData`) containing the statistics
857 """
858
859 result = _awscrt.mqtt_client_connection_get_stats(self._binding)
860 return OperationStatisticsData(result[0], result[1], result[2], result[3])
861
862
863 class WebsocketHandshakeTransformArgs:
864 """
865 Argument to a "websocket_handshake_transform" function.
866
867 A websocket_handshake_transform function has signature:
868 ``fn(transform_args: WebsocketHandshakeTransformArgs, **kwargs) -> None``
869
870 The function implementer may modify `transform_args.http_request` as desired.
871 They MUST call `transform_args.set_done()` when complete, passing an
872 exception if something went wrong. Failure to call `set_done()`
873 will hang the application.
874
875 The implementer may do asynchronous work before calling `transform_args.set_done()`,
876 they are not required to call `set_done()` within the scope of the transform function.
877 An example of async work would be to fetch credentials from another service,
878 sign the request headers, and finally call `set_done()` to mark the transform complete.
879
880 The default websocket handshake request uses path "/mqtt".
881 All required headers are present,
882 plus the optional header "Sec-WebSocket-Protocol: mqtt".
883
884 Args:
885 mqtt_connection (Connection): Connection this handshake is for.
886 http_request (awscrt.http.HttpRequest): HTTP request for this handshake.
887 done_future (concurrent.futures.Future): Future to complete when the
888 :meth:`set_done()` is called. It will contain None if successful,
889 or an exception will be set.
890
891 Attributes:
892 mqtt_connection (Connection): Connection this handshake is for.
893 http_request (awscrt.http.HttpRequest): HTTP request for this handshake.
894 """
895
896 def __init__(self, mqtt_connection, http_request, done_future):
897 self.mqtt_connection = mqtt_connection
898 self.http_request = http_request
899 self._done_future = done_future
900
901 def set_done(self, exception=None):
902 """
903 Mark the transformation complete.
904 If exception is passed in, the handshake is canceled.
905 """
906 if exception is None:
907 self._done_future.set_result(None)
908 else:
909 self._done_future.set_exception(exception)
910
911
912 class SubscribeError(Exception):
913 """
914 Subscription rejected by server.
915 """
916 pass