Azure IoT Hub Service Library
The `azure-iot-hub` library is part of the Microsoft Azure SDK for Python, providing capabilities to manage IoT Hub resources and interact with connected devices from a backend service. This includes managing device identities, sending cloud-to-device messages, and invoking direct methods on devices. The current version is 2.7.0, and Azure SDKs typically follow a frequent release cadence, with minor updates and bug fixes released regularly.
Warnings
- breaking Migration from older V1 Python clients like `azure-iothub-service-client` to the V2 SDK `azure-iot-hub` involves significant breaking changes. The package name, module structure (e.g., `azure.iot.hub` vs `azure.iothub`), class names, and API signatures are completely different. Code written for V1 clients will not work with `azure-iot-hub` without extensive modifications.
- gotcha It's crucial to distinguish between `azure-iot-hub`, `azure-iot-device`, and `azure-iot-provisioningservice`. `azure-iot-hub` is for backend *service-side* operations (managing devices, sending C2D messages). `azure-iot-device` is for *device-side* operations (sending D2C messages, receiving C2D messages). `azure-iot-provisioningservice` is for interacting with the Device Provisioning Service. Using the wrong library for a task is a common mistake.
- gotcha The `IoTHubRegistryManager.from_connection_string` method requires an IoT Hub *service* connection string (e.g., from an `iothubowner` or `service` policy), not a device connection string. Using a device connection string will result in authentication errors.
- gotcha The `IoTHubRegistryManager` instance holds network connections. Failing to call `manager.close()` when you are finished with it can lead to resource leaks and prevent your application from cleanly exiting, especially in long-running processes or serverless functions.
Install
-
pip install azure-iot-hub
Imports
- IoTHubRegistryManager
from azure.iot.hub import IoTHubRegistryManager
- IoTHubDeviceManager
from azure.iot.hub import IoTHubDeviceManager
- CloudToDeviceMethod
from azure.iot.hub.models import CloudToDeviceMethod
from azure.iot.hub import CloudToDeviceMethod
Quickstart
import os
from azure.iot.hub import IoTHubRegistryManager
# Retrieve IoT Hub connection string from environment variables for security
IOT_HUB_CONNECTION_STRING = os.environ.get("AZURE_IOT_HUB_CONNECTION_STRING", "")
if not IOT_HUB_CONNECTION_STRING:
raise ValueError("AZURE_IOT_HUB_CONNECTION_STRING environment variable not set.")
DEVICE_ID = "myPythonManagedDevice"
manager = None
try:
# Create an instance of the IoTHubRegistryManager
# This connection string should be for a service/iothubowner policy
manager = IoTHubRegistryManager.from_connection_string(IOT_HUB_CONNECTION_STRING)
print(f"Attempting to create device: {DEVICE_ID}")
# Create a new device identity
# If the device already exists, this will raise an IoTHubError (409 Conflict)
try:
device = manager.create_device(DEVICE_ID)
print(f"Device '{device.device_id}' created successfully.")
except Exception as e:
if "409001 DeviceAlreadyExists" in str(e):
print(f"Device '{DEVICE_ID}' already exists. Retrieving it.")
device = manager.get_device(DEVICE_ID)
print(f"Retrieved device '{device.device_id}'.")
else:
raise e
# You can inspect the device object, e.g., its primary key
if device.authentication and device.authentication.symmetric_key:
print(f"Primary key: {device.authentication.symmetric_key.primary_key}")
print("Successfully interacted with IoT Hub Registry.")
finally:
# Close the manager to release resources
if manager:
print("Closing IoTHubRegistryManager...")
manager.close()
print("Manager closed.")