AWS IoT SDK based on the AWS Common Runtime for connecting IoT devices to AWS IoT Core services
npx @tessl/cli install tessl/pypi-awsiotsdk@1.24.00
# AWS IoT Device SDK Python v2
1
2
A comprehensive Python SDK for connecting IoT devices to AWS IoT Core services. Built on the AWS Common Runtime, it provides high-performance MQTT client implementations (both MQTT3 and MQTT5), device shadow management, job execution capabilities, fleet provisioning, and Greengrass discovery functionality with certificate-based authentication, WebSocket connections, and automatic reconnection support.
3
4
## Package Information
5
6
- **Package Name**: awsiotsdk
7
- **Language**: Python
8
- **Installation**: `pip install awsiotsdk`
9
- **Documentation**: https://aws.github.io/aws-iot-device-sdk-python-v2/
10
- **Repository**: https://github.com/aws/aws-iot-device-sdk-python-v2
11
12
## Core Imports
13
14
Basic import for core SDK functionality:
15
16
```python
17
import awsiot
18
```
19
20
Import specific modules for different capabilities:
21
22
```python
23
# MQTT connection builders
24
from awsiot import mqtt_connection_builder, mqtt5_client_builder
25
26
# Service clients
27
from awsiot import iotjobs, iotshadow, iotidentity, greengrass_discovery
28
29
# Greengrass Core IPC
30
from awsiot.greengrasscoreipc import connect
31
32
# Event Stream RPC (used by Greengrass)
33
from awsiot import eventstreamrpc
34
```
35
36
## Basic Usage
37
38
### MQTT Connection with mTLS
39
40
```python
41
from awsiot import mqtt_connection_builder
42
import json
43
44
# Create MQTT connection using mTLS certificates
45
mqtt_connection = mqtt_connection_builder.mtls_from_path(
46
endpoint="your-iot-endpoint.iot.us-east-1.amazonaws.com",
47
cert_filepath="path/to/certificate.pem.crt",
48
pri_key_filepath="path/to/private.pem.key",
49
client_id="my-device-123",
50
clean_session=False,
51
keep_alive_secs=30
52
)
53
54
# Connect to AWS IoT Core
55
connection_future = mqtt_connection.connect()
56
connection_future.result()
57
print("Connected to AWS IoT Core!")
58
59
# Publish a message
60
message = {"temperature": 23.5, "humidity": 60.2}
61
mqtt_connection.publish(
62
topic="device/data",
63
payload=json.dumps(message),
64
qos=mqtt.QoS.AT_LEAST_ONCE
65
)
66
67
# Disconnect
68
disconnect_future = mqtt_connection.disconnect()
69
disconnect_future.result()
70
```
71
72
### Device Shadow Operations
73
74
```python
75
from awsiot import mqtt_connection_builder, iotshadow
76
77
# Create connection (using previous connection setup)
78
mqtt_connection = mqtt_connection_builder.mtls_from_path(
79
endpoint="your-iot-endpoint.iot.us-east-1.amazonaws.com",
80
cert_filepath="path/to/certificate.pem.crt",
81
pri_key_filepath="path/to/private.pem.key",
82
client_id="my-device-123"
83
)
84
85
# Create shadow client
86
shadow_client = iotshadow.IotShadowClient(mqtt_connection)
87
88
# Update device shadow
89
update_request = iotshadow.UpdateShadowRequest(
90
thing_name="MyDevice",
91
state=iotshadow.ShadowState(
92
desired={"temperature": 22.0, "fan_speed": "medium"}
93
)
94
)
95
96
future = shadow_client.publish_update_shadow(update_request, mqtt.QoS.AT_LEAST_ONCE)
97
future.result()
98
```
99
100
## Architecture
101
102
The AWS IoT Device SDK Python v2 is built on several key architectural components:
103
104
- **Connection Layer**: Multiple connection builders supporting mTLS, WebSockets, custom authorizers, and PKCS#11/PKCS#12 for different authentication methods
105
- **Service Clients**: High-level clients for IoT Jobs, Device Shadow, Fleet Provisioning, and Greengrass discovery with both V1 (callback-based) and V2 (Future-based) APIs
106
- **MQTT Protocol Support**: Native support for both MQTT3 and MQTT5 protocols with extensive configuration options
107
- **Greengrass Integration**: Complete IPC client for Greengrass Core communication enabling edge computing scenarios
108
- **Error Handling**: Comprehensive exception hierarchy with structured error responses and deserialization failure handling
109
- **Cross-Platform**: Platform-specific implementations for Windows certificate stores, macOS Keychain, and Unix PKCS#11
110
111
## Capabilities
112
113
### MQTT Connection Management
114
115
MQTT3 and MQTT5 connection builders supporting multiple authentication methods including mTLS certificates, WebSocket connections with AWS signing, custom authorizers, and platform-specific certificate stores.
116
117
```python { .api }
118
# MQTT3 Connection Builders
119
def mtls_from_path(cert_filepath, pri_key_filepath, **kwargs): ...
120
def mtls_from_bytes(cert_bytes, pri_key_bytes, **kwargs): ...
121
def mtls_with_pkcs11(**kwargs): ... # Unix only
122
def mtls_with_pkcs12(pkcs12_filepath, pkcs12_password, **kwargs): ... # macOS only
123
def mtls_with_windows_cert_store_path(cert_store_path, **kwargs): ... # Windows only
124
def websockets_with_default_aws_signing(region, credentials_provider, **kwargs): ...
125
def websockets_with_custom_authorizer(region, **kwargs): ...
126
def direct_with_custom_authorizer(**kwargs): ...
127
128
# MQTT5 Client Builders
129
def mtls_from_path(cert_filepath, pri_key_filepath, **kwargs): ...
130
def mtls_from_bytes(cert_bytes, pri_key_bytes, **kwargs): ...
131
def mtls_with_pkcs11(**kwargs): ... # Unix only
132
def mtls_with_pkcs12(pkcs12_filepath, pkcs12_password, **kwargs): ... # macOS only
133
def mtls_with_windows_cert_store_path(cert_store_path, **kwargs): ... # Windows only
134
def websockets_with_default_aws_signing(region, credentials_provider, **kwargs): ...
135
def websockets_with_custom_authorizer(region, **kwargs): ...
136
def direct_with_custom_authorizer(**kwargs): ...
137
```
138
139
[MQTT Connection Management](./mqtt-connections.md)
140
141
### Device Shadow Operations
142
143
Complete device shadow functionality including get, update, delete operations for both classic and named shadows, with support for shadow delta events and real-time shadow document updates.
144
145
```python { .api }
146
class IotShadowClient:
147
def publish_get_shadow(self, request, qos): ...
148
def publish_update_shadow(self, request, qos): ...
149
def publish_delete_shadow(self, request, qos): ...
150
def subscribe_to_shadow_delta_events(self, request, qos, callback): ...
151
152
class IotShadowClientV2:
153
def get_shadow(self, request): ...
154
def update_shadow(self, request): ...
155
def delete_shadow(self, request): ...
156
```
157
158
[Device Shadow Operations](./device-shadow.md)
159
160
### IoT Jobs Management
161
162
Job execution capabilities for device management including job discovery, execution updates, status reporting, and real-time job notifications with support for both pending and in-progress job handling.
163
164
```python { .api }
165
class IotJobsClient:
166
def publish_get_pending_job_executions(self, request, qos): ...
167
def publish_start_next_pending_job_execution(self, request, qos): ...
168
def publish_update_job_execution(self, request, qos): ...
169
def subscribe_to_job_executions_changed_events(self, request, qos, callback): ...
170
171
class IotJobsClientV2:
172
def get_pending_job_executions(self, request): ...
173
def start_next_pending_job_execution(self, request): ...
174
def update_job_execution(self, request): ...
175
```
176
177
[IoT Jobs Management](./iot-jobs.md)
178
179
### Fleet Provisioning
180
181
Device certificate provisioning and thing registration including certificate creation from CSR, keys and certificate generation, and device thing registration for automated fleet provisioning workflows.
182
183
```python { .api }
184
class IotIdentityClient:
185
def publish_create_certificate_from_csr(self, request, qos): ...
186
def publish_create_keys_and_certificate(self, request, qos): ...
187
def publish_register_thing(self, request, qos): ...
188
189
class IotIdentityClientV2:
190
def create_certificate_from_csr(self, request): ...
191
def create_keys_and_certificate(self, request): ...
192
def register_thing(self, request): ...
193
```
194
195
[Fleet Provisioning](./fleet-provisioning.md)
196
197
### Greengrass Discovery
198
199
Greengrass Core discovery functionality for edge computing scenarios including connectivity information retrieval and core device discovery for local communication setup.
200
201
```python { .api }
202
class DiscoveryClient:
203
def __init__(self, bootstrap, socket_options, tls_context, region, gg_server_name, proxy_options): ...
204
def discover(self, thing_name): ...
205
```
206
207
[Greengrass Discovery](./greengrass-discovery.md)
208
209
### Greengrass Core IPC
210
211
Complete Greengrass Core Inter-Process Communication client providing access to all Greengrass Core services including component management, configuration, local deployment, pub/sub messaging, and secrets management.
212
213
```python { .api }
214
def connect(**kwargs): ...
215
216
class GreengrassCoreIPCClient:
217
def new_get_component_details(self): ...
218
def new_list_components(self): ...
219
def new_publish_to_topic(self): ...
220
def new_subscribe_to_topic(self): ...
221
def new_get_thing_shadow(self): ...
222
def new_update_thing_shadow(self): ...
223
```
224
225
[Greengrass Core IPC](./greengrass-ipc.md)
226
227
### Event Stream RPC
228
229
Low-level event-stream RPC protocol implementation used by Greengrass Core IPC and other AWS IoT services, providing connection management, operation handling, and streaming capabilities for bidirectional communication.
230
231
```python { .api }
232
class Connection:
233
def connect(self, connection_lifecycle_handler): ...
234
def close(self): ...
235
def new_stream(self, operation_name, payload, stream_response_handler): ...
236
237
class Client:
238
def __init__(self, connection, shape_index): ...
239
def new_operation(self, operation_name): ...
240
def close(self): ...
241
242
# Error classes
243
class ConnectionClosedError(RuntimeError): ...
244
class StreamClosedError(RuntimeError): ...
245
class EventStreamError(RuntimeError): ...
246
class EventStreamOperationError(RuntimeError): ...
247
```
248
249
## Error Handling
250
251
The SDK provides comprehensive error handling through structured exception types:
252
253
```python { .api }
254
class V2ServiceException(Exception):
255
"""Wrapper exception for V2 service client failures"""
256
def __init__(self, message: str, inner_error: Exception, modeled_error: Any): ...
257
258
class V2DeserializationFailure(Exception):
259
"""Exception for MQTT message deserialization failures"""
260
def __init__(self, message: str, inner_error: Exception, payload: bytes): ...
261
```
262
263
Common error patterns include network failures, authentication errors, malformed requests, and service-specific errors that are propagated through the Future-based APIs with detailed error information.
264
265
## Types
266
267
### Core Base Classes
268
269
```python { .api }
270
class MqttServiceClient:
271
"""Base class for AWS MQTT service clients"""
272
def __init__(self, mqtt_connection): ...
273
def unsubscribe(self, topic: str): ...
274
275
class ModeledClass:
276
"""Base for input/output classes generated from AWS service model"""
277
def __repr__(self): ...
278
279
@dataclass
280
class ServiceStreamOptions:
281
"""Configuration options for MQTT-based service streaming operations"""
282
incoming_event_listener: Callable
283
subscription_status_listener: Optional[Callable] = None
284
deserialization_failure_listener: Optional[Callable] = None
285
```