Azure IoT Device SDK for Python

repository·main·Indexed 19 days ago

https://github.com/azure/azure-iot-sdk-python

The Azure IoT Device SDK for Python enables developers to create IoT device solutions connecting to Azure IoT Hub and IoT Edge ecosystems via the MQTT protocol. It provides three primary client types: IoTHub Device Client for individual devices, IoTHub Module Client for Linux-based IoT Edge modules, and Provisioning Device Client for the Azure IoT Device Provisioning Service (DPS). The current library is distributed as the azure-iot-device package and requires Python 3.9 or higher.

Tokens
10.8K
Snippets
39
Records
66
Agent score
64%

What's inside azure-iot-sdk-python

  1. Overview of Azure IoT SDK for Python SDK Lab tools

    main

    The sdklab directory contains a collection of command-line tools designed to exercise the Azure IoT SDK for Python through various testing methodologies, including end-to-end tests, stress tests, and long-haul tests.

    Key characteristics of these tools:

    • Purpose: They are used to validate library quality and prevent bit-rot, often by being integrated into CI/CD pipelines via run_gate_tests.py.
    • Behavior: Most tools are designed to return a success value (0) 100% of the time. Tools that return a failure are specifically intended to expose known, currently unfixed issues.
    • Usage Warning: While these tools demonstrate library usage, they should not be used as production samples. Some tools intentionally use undocumented knowledge, distort library behavior, or simulate extreme conditions to expose theoretical bugs or weaknesses.
  2. Overview of Advanced IoT Edge Scenario Samples

    main

    The following samples demonstrate specific asynchronous and edge-specific communication patterns using the Azure IoT Hub Device SDK:

    • receive_data.py: Demonstrates how to receive messages, twin patches, and method requests sent to an Edge module.
    • send_message.py: Demonstrates how to send multiple telemetry messages in parallel from an Edge module to either the Azure IoT Hub or Azure IoT Edge.
    • send_message_to_output.py: Demonstrates how to send multiple messages in parallel from an Edge module to a specific defined output.
    • send_message_downstream.py: Demonstrates how to send messages from a downstream (or 'leaf') device to IoT Edge.
  3. Overview of Azure IoT Device SDK for Python features

    main

    The SDK provides three primary client types for connecting to the Azure IoT ecosystem. Note that all clients currently only support the MQTT protocol.

    IoTHub Device Client

    Used for connecting individual devices to IoT Hub. Supported features include:

    • Authentication: Symmetric key, X-509 Self Signed, CA Signed, and SASToken.
    • Messaging: Send device-to-cloud messages (max 256KB) with custom properties; receive cloud-to-device messages with custom/system properties.
    • Device Twins: Get twin tags and subscribe to desired properties.
    • Direct Methods: Handle method-specific and generic operations invoked from the cloud.
    • File Upload: Initiate file uploads to Blob storage.
    • Connection Management: Automatic retry of dropped connections (default 10s interval, configurable).

    IoTHub Module Client

    Used for IoT Edge modules. Note: Scoped to Linux containers and devices only. Supported features include:

    • Authentication: Symmetric key, X-509 Self Signed, and CA Signed (SASToken is not supported).
    • Messaging: Send device-to-cloud messages (max 256KB); receive cloud-to-device messages with options to complete/reject/abandon.
    • Device Twins: Get twin tags and subscribe to desired properties.
    • Direct Methods: Handle cloud-invoked methods and direct invocation of methods on other modules via the Edge Gateway.
    • Connection Management: Automatic retry of dropped connections (default 10s interval, configurable).

    Provisioning Device Client

    Used for device provisioning via Azure IoT Device Provisioning Service (DPS). Supported features include:

    • X.509 Individual Enrollment: Provisioning via X.509 root certificate.
    • X.509 Enrollment Group: Provisioning via X.509 leaf certificate.
    • Symmetric Key Enrollment: Provisioning via Symmetric key attestation.
    • Note: TPM Individual Enrollment is not currently supported.
  4. Explore additional IoT Hub and IoT Edge samples

    main

    The repository contains several directories for advanced scenarios:

    • async-hub-scenarios/: Complex asynchronous IoT Hub scenarios including:
      • Sending multiple telemetry messages.
      • Receiving Cloud-to-Device (C2D) messages.
      • Sending/receiving updates to device twins.
      • Receiving direct method invocations.
      • Uploading files to Azure storage.
    • async-edge-scenarios/: Complex asynchronous IoT Edge scenarios including:
      • Module telemetry and input message handling.
      • Sending messages to Module Outputs.
      • Communicating from downstream/leaf devices to IoT Edge.
    • sync-samples/: Samples using the synchronous client API.
    • pnp/: Samples for Azure IoT Plug and Play.
  5. Understand pip/PyPi package aliases

    main
    The pip_alias packages are security measures designed to occupy old package names. Instead of containing original code, these alias packages simply contain dependencies on the current, correct package names to prevent dependency confusion attacks or the use of deprecated/insecure package names.
  6. Understand IoT Plug and Play device sample scenarios

    main

    The PnP samples demonstrate how devices following IoT Plug and Play conventions interact with IoT Hub or IoT Central to perform three main tasks:

    1. Send telemetry
    2. Update properties (both read-only and read-write)
    3. Respond to command invocation

    There are two primary model implementations provided in the samples:

    • Thermostat Model: A single interface defining telemetry, read-only/read-write properties, and commands.
    • Temperature Controller Model: A multi-component model. The top-level interface defines telemetry, a read-only property, and commands. It includes two Thermostat components and a device information component.
  7. Connect to IoT Hub using TLS 1.3

    main

    To use TLS 1.3 with Azure IoT Hub (currently in preview), you must use a specific connection string format. The standard connection string format (<hub name>.azure-devices.<dnsSuffix>) only supports TLS 1.0, 1.1, and 1.2.

    To enable TLS 1.3 support, use the preview endpoints by modifying your connection string to include .device. or .service. as shown below:

    • Device connection string: <hub name>.device.azure-devices.<dnsSuffix>
    • Service connection string: <hub name>.service.azure-devices.<dnsSuffix>

    The Python SDK automatically advertises support for both TLS 1.2 and TLS 1.3 in the 'Client Hello' message. When using the correct connection string, IoT Hub will negotiate and select TLS 1.3 for the connection.

    # Example Device Connection String for TLS 1.3
    <hub name>.device.azure-devices.<dnsSuffix>
  8. Migrate sending telemetry to v2

    main

    In v2, use the Message class. Custom properties are now managed via the custom_properties dictionary rather than a properties() method. Sending is performed using the asynchronous await client.send_message(message) method.

    from azure.iot.device import Message
    
    message = Message("telemetry message")
    message.message_id = "message id"
    message.correlation_id = "correlation id"
    
    # Set custom properties via dictionary
    message.custom_properties["property"] = "property_value"
    
    await client.send_message(message)
  9. Migrate receiving messages to v2

    main

    In v2, message receiving is handled by assigning a callback function to the client.on_message_received property. The handler function receives a message object where data is accessed via .data and custom properties via .custom_properties.

    # define behavior for receiving a message
    def message_handler(message):
        print("the data in the message received was ")
        print(message.data)
        print("custom properties are")
        print(message.custom_properties)
    
    # set the message handler on the client
    client.on_message_received = message_handler