Azure IoT Device Library

2.14.0 · active · verified Wed Apr 15

The Microsoft Azure IoT Device Library provides an easy-to-use API for Python applications to connect to Azure IoT Hub or Azure IoT Edge. It allows devices to send telemetry, receive commands, update device twins, and handle direct methods. The library is actively maintained with frequent releases, currently at version 2.14.0, with release candidates often preceding major updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect an Azure IoT Device Client to IoT Hub using a connection string from an environment variable and send a basic JSON telemetry message. Ensure the `IOTHUB_DEVICE_CONNECTION_STRING` environment variable is set with your device's connection string before running.

import os
from azure.iot.device import IoTHubDeviceClient, Message

# NOTE: Environment variables are used for security and ease of management.
# Replace with your actual connection string from Azure IoT Hub device details.
CONNECTION_STRING = os.environ.get("IOTHUB_DEVICE_CONNECTION_STRING", "")

def main():
    if not CONNECTION_STRING:
        print("Error: IOTHUB_DEVICE_CONNECTION_STRING environment variable not set.")
        print("Please set it to your device's connection string.")
        exit(1)

    print("Connecting to IoT Hub...")
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    client.connect()
    print("Client connected!")

    # Send a simple telemetry message
    telemetry_msg = Message('{"temperature": 25.0, "humidity": 60.5}')
    telemetry_msg.content_encoding = "utf-8"
    telemetry_msg.content_type = "application/json"

    print("Sending message...")
    client.send_message(telemetry_msg)
    print("Message sent!")

    # Disconnect
    client.shutdown()
    print("Client disconnected.")

if __name__ == "__main__":
    main()

view raw JSON →