AWS IoT Device SDK for Python v2

repository·main·Indexed 19 days ago

https://github.com/aws/aws-iot-device-sdk-python-v2

A SDK for connecting Python applications to the AWS IoT platform. It supports MQTT 5.0, device state management via Shadows, remote operations via Jobs, and automated device provisioning. The SDK includes service clients for AWS IoT Core and Greengrass IPC for local deployments, component management, and streaming events. Requires Python 3.8+ and is compatible with Linux, Windows 11+, and macOS 14+.

Tokens
34.4K
Snippets
75
Records
121
Agent score
65%

What's inside aws-iot-device-sdk-python-v2

  1. Explore AWS IoT Device SDK v2 Python Sample Applications

    main

    The samples/ directory contains various application examples categorized by their primary interaction pattern. These samples demonstrate how to use the SDK to connect to AWS IoT Core, interact with IoT services, or work with AWS Greengrass.

    MQTT5 Client Samples

    MQTT5 is the recommended protocol for the SDK. Samples include:

    • X.509-based mutual TLS: Connecting using certificates and private keys.
    • Websockets with Sigv4: Authenticating over websockets using AWS Signature Version 4.
    • AWS Custom Authorizer Lambda: Connecting with signed or unsigned Lambda-backed custom authorizers.
    • PKCS#11: Connecting using a Hardware Security Module (HSM) or smartcard.

    Service Client Samples

    These samples demonstrate how to use SDK service clients to interact with specific AWS IoT services:

    • Shadow: Manage and sync device state.
    • Jobs: Receive and execute remote operations.
    • Fleet Provisioning: Basic provisioning or CSR-based (Certificate Signing Request) provisioning.

    Greengrass Samples

    For interacting with AWS Greengrass environments:

    • Greengrass Discovery: Discover and connect to a local Greengrass core.
    • Greengrass IPC: Demonstrate Inter-Process Communication (IPC) with Greengrass components.
  2. Explore the AWS IoT Device SDK for Python v2 API Reference

    main

    The SDK provides specialized modules for different AWS IoT capabilities. Key functional areas include:

    • MQTT Connection & Clients: Use mqtt_connection_builder and mqtt5_client_builder to establish connectivity.
    • IoT Shadow: Manage device shadows via iotshadow.
    • IoT Jobs: Handle device jobs via iotjobs.
    • Greengrass Integration: Use greengrasscoreipc and greengrass_discovery for AWS IoT Greengrass environments.
    • EventStreamRPC: Support for EventStream RPC protocols.
    • IoT Identity: Manage device identities via iotidentity.
  3. How Shadow reported and desired states work together

    main

    A device shadow consists of two independent states used to coordinate between a device and control applications:

    1. Reported State: Represents the device's last-known local state. The device updates this to inform the service of its current status.
    2. Desired State: Represents the state a control application wants the device to achieve. Control applications update this to request changes.

    Coordination Workflow

    To change a device property (e.g., changing a color from green to red):

    1. Control App: Updates the desired state (e.g., update-desired {"Color":"red"}).
    2. Service: Emits a ShadowDeltaUpdated event indicating the property is out-of-sync.
    3. Device: Receives the delta, applies the change locally, and then updates the reported state (e.g., update-reported {"Color":"red"}) to bring the states back into sync.
    4. Service: Once reported matches desired, no further ShadowDeltaUpdated events are emitted.
  4. Understand MQTT5 Lifecycle Events

    main

    The MQTT5 client emits several events related to state and network status:

    • AttemptingConnect: Emitted when the client begins a connection attempt.
    • ConnectionSuccess: Emitted after receiving a CONNACK packet. Includes NegotiatedSettings (final session settings).
    • ConnectionFailure: Emitted if a connection fails between DNS resolution and CONNACK receipt. May include error codes or the CONNACK packet if a failing reason code was sent.
    • Disconnect: Emitted when the network connection is shut down (local action, event, or remote reset). Only emitted after a ConnectionSuccess. Includes an error code and potentially the server-sent DISCONNECT packet.
    • Stopped: Emitted once the client has shut down all network connections and entered an idle state (after stop() is called).
  5. How JobExecutionsChanged and NextJobExecutionChanged events work

    main

    When interacting with the AWS IoT Jobs service, the SDK uses two primary MQTT-based streaming operations to notify devices of changes:

    • create_job_executions_changed_stream (JobExecutionsChanged event): Emitted every time the set of queued or in-progress job executions for the device changes. If you create $N$ jobs, you will receive $N$ of these events.
    • create_next_job_execution_changed_stream (NextJobExecutionChanged event): Emitted only when the specific job that is next in line to be executed changes. This typically happens when a job is completed or when a new job is queued that becomes the new 'next' job.

    Developers should open both streams to maintain an accurate local state of pending work.

  6. Use the Fleet Provisioning service client

    main

    The Fleet Provisioning service (also known as Identity Service) allows devices to securely receive certificates and private keys upon their first connection. The v2 SDK provides a client for this service that follows the same subscription-then-publish pattern as the Jobs and Shadow services.

    1. Subscribe to the required Fleet Provisioning topics to receive data and feedback.
    2. Use the service client APIs to interact with the server (e.g., updating status or requesting data).
  7. Recommended architecture for a device job-processing application

    main

    To build a robust, persistent job executor on an IoT device, follow this architectural pattern:

    1. Initialization: On startup, create and open streaming operations for both JobExecutionsChanged and NextJobExecutionChanged events.
    2. State Synchronization: On startup, call get_pending_job_executions to fetch and cache the current set of incomplete jobs.
    3. Reactive Updates: Keep the local cache up to date by reacting to the JobExecutionsChanged and NextJobExecutionChanged MQTT events.
    4. Execution Loop: While there are incomplete jobs in the cache, execute them (e.g., one-at-a-time). If the cache is empty, wait for a new event to trigger the next execution.
  8. Use the AWS IoT Jobs service in v2

    main

    The v2 SDK Jobs service client (iotjobs.IotJobsClient) follows the same subscription-based pattern as the Device Shadow service. You must subscribe to necessary topics (like NextJobExecutionChangedSubscriptionRequest) before the client can effectively interact with the server to receive or update job statuses.

    # Initialize Jobs client
    mqtt5_client.start()
    jobs_client = iotjobs.IotJobsClient(mqtt5_client)
    
    # Subscribe to necessary topics
    changed_subscription_request = iotjobs.NextJobExecutionChangedSubscriptionRequest(
        thing_name="<thing name>"
    )
    
    def on_next_job_execution_changed(event):
        return
  9. Use MQTT5 features in AWS IoT Device SDK for Python v2

    main

    The AWS IoT Device SDK for Python v2 supports advanced MQTT5 features through the underlying awscrt library. Key features include:

    • Clean Start and Session Expiry: Manage persistent sessions using awscrt.mqtt5.ClientSessionBehaviorType and NegotiatedSettings.session_expiry_interval_sec.
    • Reason Codes: Debug interactions (Subscribe, Publish, Acknowledge, Connect, Disconnect) using specific reason code enums like PubAckReasonCode, SubackReasonCode, UnsubackReasonCode, ConnectReasonCode, and DisconnectReasonCode.
    • Topic Aliases: Reduce bandwidth by substituting topic names with two-byte integers. Use mqtt5.TopicAliasingOptions with mqtt5.ClientOptions, and provide topic_alias(int) when creating a PUBLISH packet.
    • Message Expiry: Set message_expiry_interval_sec when creating a PUBLISH packet to define how long a message remains valid.
    • Server Disconnect: Handle proactive server-initiated closures by monitoring DisconnectPacket which includes a reason code.
    • Request/Response: Implement a request/response pattern by using the response_topic method in the PublishPacket class.
    • Maximum Packet Size: Negotiate packet limits using ConnectPacket.maximum_packet_size(int), NegotiatedSettings.maximum_packet_size_to_server, and ConnAckPacket.maximum_packet_size.
    • Payload Format and Content Type: Specify if a payload is binary or text and define its content type using the content_type(str) method in the PublishPacket class.
    • Shared Subscriptions: Distribute messages from a single topic across multiple clients using random distribution. AWS IoT Core supports Shared Subscriptions for both MQTT3 and MQTT5.
  10. Listen to Shadow state changes with streaming APIs

    main

    The Shadow service provides two primary streaming operations to react to changes without manual polling or complex JSON diffing:

    • create_shadow_updated_stream: Emits ShadowUpdatedEvent whenever any part of the shadow (metadata, state, or version) changes. This is useful for general monitoring.
    • create_shadow_delta_updated_stream: Emits ShadowDeltaUpdatedEvent specifically when properties become out-of-sync between the desired and reported states. This allows a device to focus only on the specific properties that require action.
  11. Avoid deadlocks in callbacks

    main
    You MUST NOT perform blocking operations inside any callback function. For example, do not initiate a publish and then wait for its associated future to complete within an on_publish_received callback. Because the client cannot process further work until the callback returns, this will cause a deadlock.