Azure IoT Hub Python SDK

Welcome to the Azure IoT Hub Python SDK documentation. This SDK provides a robust and easy-to-use interface for interacting with Azure IoT Hub from your Python applications.

Key Features

Installation

You can install the SDK using pip:

pip install azure-iot-device azure-iot-hub

Getting Started

Device Client Example

This example demonstrates how a device can connect to IoT Hub and send telemetry messages.


import asyncio
import os
from azure.iot.device.aio import IoTHubDeviceClient

async def main():
    # Replace with your device connection string
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    if not conn_str:
        print("Please set the IOTHUB_DEVICE_CONNECTION_STRING environment variable.")
        return

    # Create instance of the device client using the connection string
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the device client to IoT Hub
    await device_client.connect()

    # Send a message to IoT Hub
    message = "Hello, IoT Hub from Python SDK!"
    print(f"Sending message: {message}")
    await device_client.send_message(message)
    print("Message sent successfully.")

    # Optionally, you can implement message receiving or device twin operations here
    # For example, to receive messages:
    # async def message_handler(message):
    #     print(f"Received message: {message.data}")
    # await device_client.on_message_received(message_handler)

    # Keep the connection open (or implement specific logic)
    # For this simple example, we'll disconnect after sending
    await asyncio.sleep(1) # Give some time for async operations

    # Shut down the client
    await device_client.shutdown()

if __name__ == "__main__":
    asyncio.run(main())
            

Service Client Example

This example shows how to send a cloud-to-device (C2D) message from a service application.


import asyncio
import os
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import Twin

async def main():
    # Replace with your IoT Hub connection string (from the IoT Hub portal)
    iot_hub_connection_string = os.getenv("IOTHUB_CONNECTION_STRING")
    if not iot_hub_connection_string:
        print("Please set the IOTHUB_CONNECTION_STRING environment variable.")
        return

    # Create instance of the IoTHubRegistryManager
    registry_manager = IoTHubRegistryManager.from_connection_string(iot_hub_connection_string)

    # Specify the device ID to send the message to
    device_id = "your-device-id" # Replace with your actual device ID
    message_payload = "This is a C2D message from the cloud!"

    try:
        # Send the C2D message
        await registry_manager.send_c2d_message(device_id, message_payload)
        print(f"Successfully sent message to device {device_id}: {message_payload}")

    except Exception as ex:
        print(f"Error sending C2D message: {ex}")

if __name__ == "__main__":
    asyncio.run(main())
            

Core Concepts

API Reference

azure.iot.device.aio.IoTHubDeviceClient

create_from_connection_string(connection_string, **kwargs) Factory method to create a device client from a connection string. connect(**kwargs) Connects the device client to Azure IoT Hub. send_message(message, **kwargs) Sends a message from the device to Azure IoT Hub. shutdown(**kwargs) Shuts down the device client gracefully.

azure.iot.hub.IoTHubRegistryManager

from_connection_string(connection_string, **kwargs) Factory method to create a registry manager from an IoT Hub connection string. send_c2d_message(device_id, message, **kwargs) Sends a cloud-to-device message to a specific device.

Note

Ensure your environment variables (IOTHUB_DEVICE_CONNECTION_STRING and IOTHUB_CONNECTION_STRING) are correctly set before running the examples. For security, avoid hardcoding connection strings directly in production code.

Tip

Explore the official Azure IoT samples repository on GitHub for more comprehensive examples and advanced scenarios.