Azure IoT Device Library
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
- breaking Python 3.7 support was dropped in `v2.14.0`. Applications on Python 3.7 must upgrade to 3.8+ or pin `azure-iot-device<2.14.0`.
- breaking Breaking Python version changes are frequent. Python 3.6 was dropped in `v2.13.0`, and 2.7/3.5 in `v2.11.0`. Always check release notes for your Python version.
- gotcha Dependency churn for `requests-unixsocket`: `v2.14.0` switched to `requests-unixsocket2` due to the original being abandoned. However, `v2.15.0rc1` indicates a return to the original `requests-unixsocket` after it was updated. This may cause unexpected dependency conflicts or behavior if directly managing sub-dependencies.
- gotcha The upcoming `v2.15.0rc1` switches `Paho-MQTT` dependency from 1.x to 2.x. This could introduce breaking changes or require code adjustments if your application directly interacts with `Paho-MQTT` or relies on specific behaviors from version 1.x.
Install
-
pip install azure-iot-device
Imports
- IoTHubDeviceClient
from azure.iot.hub.protocol.iot_hub_device_client import IoTHubDeviceClient
from azure.iot.device import IoTHubDeviceClient
- IoTHubModuleClient
from azure.iot.device import ModuleClient
from azure.iot.device import IoTHubModuleClient
- ProvisioningDeviceClient
from azure.iot.device import ProvisioningDeviceClient
- Message
from azure.iot.device import Message
Quickstart
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()