0
# MQTT Connection Management
1
2
Comprehensive MQTT connection management supporting both MQTT3 and MQTT5 protocols with multiple authentication methods, extensive configuration options, and platform-specific certificate store integration.
3
4
## Capabilities
5
6
### MQTT3 Connection Builders
7
8
#### mTLS from File Paths
9
10
Creates MQTT3 connection using certificate and private key files from the filesystem.
11
12
```python { .api }
13
def mtls_from_path(cert_filepath, pri_key_filepath, **kwargs):
14
"""
15
Create MQTT connection using mTLS certificates from file paths.
16
17
Parameters:
18
- cert_filepath (str): Path to certificate file
19
- pri_key_filepath (str): Path to private key file
20
- endpoint (str): AWS IoT endpoint hostname
21
- client_id (str): Unique MQTT client identifier
22
- client_bootstrap: Client bootstrap for networking
23
- port (int): Connection port (default: 8883)
24
- clean_session (bool): Start with clean session
25
- keep_alive_secs (int): Keep alive interval in seconds
26
- will: Last will and testament message
27
- username (str): MQTT username
28
- password (str): MQTT password
29
- ca_filepath (str): CA certificate file path
30
- ca_dirpath (str): CA certificate directory path
31
- ca_bytes (bytes): CA certificate as bytes
32
- enable_metrics_collection (bool): Enable SDK metrics
33
- on_connection_interrupted: Callback for connection interruption
34
- on_connection_resumed: Callback for connection resumption
35
- on_connection_success: Callback for successful connection
36
- on_connection_failure: Callback for connection failure
37
- on_connection_closed: Callback for connection closure
38
39
Returns:
40
awscrt.mqtt.Connection: Configured MQTT connection
41
"""
42
```
43
44
Usage example:
45
46
```python
47
from awsiot import mqtt_connection_builder
48
49
connection = mqtt_connection_builder.mtls_from_path(
50
endpoint="your-endpoint.iot.us-east-1.amazonaws.com",
51
cert_filepath="/path/to/certificate.pem.crt",
52
pri_key_filepath="/path/to/private.pem.key",
53
client_id="my-device-001",
54
clean_session=False,
55
keep_alive_secs=30,
56
on_connection_interrupted=lambda connection, error, **kwargs: print(f"Connection interrupted: {error}"),
57
on_connection_resumed=lambda connection, return_code, session_present, **kwargs: print("Connection resumed")
58
)
59
60
# Connect and wait for completion
61
connect_future = connection.connect()
62
connect_future.result()
63
```
64
65
#### mTLS from Memory
66
67
Creates MQTT3 connection using certificate and private key data loaded in memory.
68
69
```python { .api }
70
def mtls_from_bytes(cert_bytes, pri_key_bytes, **kwargs):
71
"""
72
Create MQTT connection using mTLS certificates from in-memory bytes.
73
74
Parameters:
75
- cert_bytes (bytes): Certificate data as bytes
76
- pri_key_bytes (bytes): Private key data as bytes
77
- **kwargs: Same parameters as mtls_from_path
78
79
Returns:
80
awscrt.mqtt.Connection: Configured MQTT connection
81
"""
82
```
83
84
#### PKCS#11 Integration (Unix Only)
85
86
Uses PKCS#11 hardware security modules or software tokens for private key operations.
87
88
```python { .api }
89
def mtls_with_pkcs11(**kwargs):
90
"""
91
Create MQTT connection using PKCS#11 for private key operations (Unix only).
92
93
Parameters:
94
- pkcs11_lib (str): Path to PKCS#11 library
95
- user_pin (str): User PIN for PKCS#11 token
96
- slot_id (int): PKCS#11 slot ID (optional)
97
- token_label (str): PKCS#11 token label (optional)
98
- private_key_label (str): Private key label in PKCS#11 token
99
- cert_filepath (str): Certificate file path (optional)
100
- cert_bytes (bytes): Certificate as bytes (optional)
101
- **kwargs: Same parameters as mtls_from_path
102
103
Returns:
104
awscrt.mqtt.Connection: Configured MQTT connection
105
"""
106
```
107
108
#### PKCS#12 Integration (macOS Only)
109
110
Uses PKCS#12 certificate bundles, typically from macOS Keychain.
111
112
```python { .api }
113
def mtls_with_pkcs12(pkcs12_filepath, pkcs12_password, **kwargs):
114
"""
115
Create MQTT connection using PKCS#12 certificate bundle (macOS only).
116
117
Parameters:
118
- pkcs12_filepath (str): Path to PKCS#12 file
119
- pkcs12_password (str): Password for PKCS#12 file
120
- **kwargs: Same parameters as mtls_from_path
121
122
Returns:
123
awscrt.mqtt.Connection: Configured MQTT connection
124
"""
125
```
126
127
#### Windows Certificate Store (Windows Only)
128
129
Uses certificates from Windows certificate store.
130
131
```python { .api }
132
def mtls_with_windows_cert_store_path(cert_store_path, **kwargs):
133
"""
134
Create MQTT connection using Windows certificate store (Windows only).
135
136
Parameters:
137
- cert_store_path (str): Certificate store path
138
- **kwargs: Same parameters as mtls_from_path
139
140
Returns:
141
awscrt.mqtt.Connection: Configured MQTT connection
142
"""
143
```
144
145
#### WebSocket with AWS Signing
146
147
Creates WebSocket connection with automatic AWS request signing using credentials.
148
149
```python { .api }
150
def websockets_with_default_aws_signing(region, credentials_provider, **kwargs):
151
"""
152
Create WebSocket MQTT connection with AWS request signing.
153
154
Parameters:
155
- region (str): AWS region
156
- credentials_provider: AWS credentials provider
157
- **kwargs: Same parameters as mtls_from_path (port defaults to 443)
158
159
Returns:
160
awscrt.mqtt.Connection: Configured MQTT connection
161
"""
162
```
163
164
Usage example:
165
166
```python
167
from awsiot import mqtt_connection_builder
168
from awscrt import auth
169
170
# Create credentials provider
171
credentials_provider = auth.AwsCredentialsProvider.new_default_chain()
172
173
connection = mqtt_connection_builder.websockets_with_default_aws_signing(
174
endpoint="your-endpoint.iot.us-east-1.amazonaws.com",
175
region="us-east-1",
176
credentials_provider=credentials_provider,
177
client_id="my-device-websocket"
178
)
179
```
180
181
#### WebSocket with Custom Handshake
182
183
Creates WebSocket connection with custom handshake transformation function.
184
185
```python { .api }
186
def websockets_with_custom_handshake(websocket_handshake_transform, **kwargs):
187
"""
188
Create WebSocket MQTT connection with custom handshake.
189
190
Parameters:
191
- websocket_handshake_transform: Function to transform WebSocket handshake request
192
- **kwargs: Same parameters as mtls_from_path (port defaults to 443)
193
194
Returns:
195
awscrt.mqtt.Connection: Configured MQTT connection
196
"""
197
```
198
199
#### Custom Authorizer Authentication
200
201
Uses AWS IoT custom authorizers for device authentication without certificates.
202
203
```python { .api }
204
def direct_with_custom_authorizer(**kwargs):
205
"""
206
Create direct MQTT connection using custom authorizer.
207
208
Parameters:
209
- auth_username (str): Username for custom authorizer
210
- auth_authorizer_name (str): Name of the custom authorizer
211
- auth_authorizer_signature (str): Signature for authorizer
212
- auth_password (str): Password for custom authorizer
213
- auth_token_key_name (str): Token key name for authorizer
214
- auth_token_value (str): Token value for authorizer
215
- **kwargs: Same parameters as mtls_from_path
216
217
Returns:
218
awscrt.mqtt.Connection: Configured MQTT connection
219
"""
220
```
221
222
```python { .api }
223
def websockets_with_custom_authorizer(**kwargs):
224
"""
225
Create WebSocket MQTT connection using custom authorizer.
226
227
Parameters:
228
- Same as direct_with_custom_authorizer
229
- **kwargs: Same parameters as mtls_from_path (port defaults to 443)
230
231
Returns:
232
awscrt.mqtt.Connection: Configured MQTT connection
233
"""
234
```
235
236
#### Default TLS Builder
237
238
Creates connection with default TLS context and options.
239
240
```python { .api }
241
def new_default_builder(**kwargs):
242
"""
243
Create MQTT connection with default TLS options.
244
245
Parameters:
246
- **kwargs: Same parameters as mtls_from_path
247
248
Returns:
249
awscrt.mqtt.Connection: Configured MQTT connection
250
"""
251
```
252
253
### MQTT5 Client Builders
254
255
MQTT5 client builders provide the same authentication methods as MQTT3 but return MQTT5 clients with enhanced features.
256
257
#### Basic MQTT5 Client Creation
258
259
```python { .api }
260
def mtls_from_path(cert_filepath, pri_key_filepath, **kwargs):
261
"""
262
Create MQTT5 client using mTLS certificates from file paths.
263
264
Parameters:
265
- cert_filepath (str): Path to certificate file
266
- pri_key_filepath (str): Path to private key file
267
- endpoint (str): AWS IoT endpoint hostname
268
- client_id (str): Unique MQTT client identifier
269
- client_options: MQTT5 client options
270
- connect_options: MQTT5 connect options
271
- session_expiry_interval_sec (int): Session expiry interval
272
- request_response_information (bool): Request response information
273
- request_problem_information (bool): Request problem information
274
- receive_maximum (int): Maximum receive messages
275
- maximum_packet_size (int): Maximum packet size
276
- will_delay_interval_sec (int): Will delay interval
277
- session_behavior: Session behavior configuration
278
- extended_validation_and_flow_control_options: Flow control options
279
- offline_queue_behavior: Offline queue behavior
280
- topic_aliasing_options: Topic aliasing configuration
281
- retry_jitter_mode: Retry jitter mode
282
- min_reconnect_delay_ms (int): Minimum reconnect delay
283
- max_reconnect_delay_ms (int): Maximum reconnect delay
284
- connack_timeout_ms (int): CONNACK timeout
285
- ack_timeout_sec (int): Acknowledgment timeout
286
- on_publish_received: Callback for received publishes
287
- on_lifecycle_stopped: Lifecycle stopped callback
288
- on_lifecycle_attempting_connect: Attempting connect callback
289
- on_lifecycle_connection_success: Connection success callback
290
- on_lifecycle_connection_failure: Connection failure callback
291
- on_lifecycle_disconnection: Disconnection callback
292
293
Returns:
294
awscrt.mqtt5.Client: Configured MQTT5 client
295
"""
296
```
297
298
All other MQTT5 authentication methods follow the same pattern as MQTT3 but return `awscrt.mqtt5.Client` objects:
299
300
- `mtls_from_bytes(cert_bytes, pri_key_bytes, **kwargs)`
301
- `mtls_with_pkcs11(**kwargs)` (Unix only)
302
- `mtls_with_pkcs12(pkcs12_filepath, pkcs12_password, **kwargs)` (macOS only)
303
- `mtls_with_windows_cert_store_path(cert_store_path, **kwargs)` (Windows only)
304
- `websockets_with_default_aws_signing(region, credentials_provider, **kwargs)`
305
- `websockets_with_custom_handshake(websocket_handshake_transform, **kwargs)`
306
- `direct_with_custom_authorizer(**kwargs)`
307
- `websockets_with_custom_authorizer(**kwargs)`
308
- `new_default_builder(**kwargs)`
309
310
### Constants
311
312
```python { .api }
313
DEFAULT_WEBSOCKET_MQTT_PORT = 443
314
DEFAULT_DIRECT_MQTT_PORT = 8883
315
DEFAULT_KEEP_ALIVE = 1200
316
```
317
318
## Common Connection Patterns
319
320
### Basic mTLS Connection with Error Handling
321
322
```python
323
from awsiot import mqtt_connection_builder
324
from awscrt import mqtt
325
import sys
326
327
def on_connection_interrupted(connection, error, **kwargs):
328
print(f"Connection interrupted. Error: {error}")
329
330
def on_connection_resumed(connection, return_code, session_present, **kwargs):
331
print(f"Connection resumed. Return code: {return_code} Session present: {session_present}")
332
333
def on_connection_success(connection, callback_data, **kwargs):
334
print("Connection successful")
335
336
def on_connection_failure(connection, callback_data, **kwargs):
337
print("Connection failed")
338
339
def on_connection_closed(connection, callback_data, **kwargs):
340
print("Connection closed")
341
342
try:
343
connection = mqtt_connection_builder.mtls_from_path(
344
endpoint="your-endpoint.iot.us-east-1.amazonaws.com",
345
cert_filepath="/path/to/certificate.pem.crt",
346
pri_key_filepath="/path/to/private.pem.key",
347
client_id="my-device-123",
348
clean_session=False,
349
keep_alive_secs=30,
350
on_connection_interrupted=on_connection_interrupted,
351
on_connection_resumed=on_connection_resumed,
352
on_connection_success=on_connection_success,
353
on_connection_failure=on_connection_failure,
354
on_connection_closed=on_connection_closed
355
)
356
357
# Connect
358
connect_future = connection.connect()
359
connect_future.result()
360
print("Connected successfully!")
361
362
# Your application logic here
363
364
# Disconnect
365
disconnect_future = connection.disconnect()
366
disconnect_future.result()
367
print("Disconnected successfully!")
368
369
except Exception as e:
370
print(f"Connection error: {e}")
371
sys.exit(1)
372
```
373
374
### WebSocket Connection with IAM Credentials
375
376
```python
377
from awsiot import mqtt_connection_builder
378
from awscrt import auth
379
import boto3
380
381
# Get credentials from boto3 session
382
session = boto3.Session()
383
credentials = session.get_credentials()
384
385
# Create credentials provider
386
credentials_provider = auth.AwsCredentialsProvider.new_static(
387
access_key_id=credentials.access_key,
388
secret_access_key=credentials.secret_key,
389
session_token=credentials.token
390
)
391
392
connection = mqtt_connection_builder.websockets_with_default_aws_signing(
393
endpoint="your-endpoint.iot.us-east-1.amazonaws.com",
394
region=session.region_name,
395
credentials_provider=credentials_provider,
396
client_id="websocket-client-123",
397
clean_session=True
398
)
399
400
connect_future = connection.connect()
401
connect_future.result()
402
```