Azure IoT SDK for Python
Introduction
Welcome to the official documentation for the Azure IoT SDK for Python. This SDK provides a robust and flexible way for your Python applications to connect to Azure IoT Hub, send telemetry data, receive cloud-to-device messages, manage device twins, and invoke direct methods.
With this SDK, you can build intelligent edge and IoT solutions that leverage the power of Azure IoT services. Whether you are developing for a resource-constrained device or a powerful server, the Python SDK offers the tools you need.
Installation
The Azure IoT SDK for Python is available as a package on PyPI. You can install it using pip:
pip install azure-iot-device
For more advanced features or specific components, you might need to install additional packages:
pip install azure-iot-hub
(for service-side operations)
Getting Started
To begin using the SDK, you'll need an Azure IoT Hub instance. Once you have your IoT Hub created, you'll need to register a device and obtain its connection string.
1. Register a Device
Register your device in IoT Hub using the Azure portal or Azure CLI. You will get a device ID and a primary or secondary connection string.
2. Basic Device Client
Here's a simple example of how to create a device client and connect to IoT Hub:
from azure.iot.device import IoTHubDeviceClient
connection_string = "YOUR_DEVICE_CONNECTION_STRING"
device_client = IoTHubDeviceClient.create_from_connection_string(connection_string)
async def main():
await device_client.connect()
print("Device connected successfully!")
await device_client.disconnect()
print("Device disconnected.")
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Replace "YOUR_DEVICE_CONNECTION_STRING"
with your actual device connection string.
Core Concepts
The Azure IoT SDK for Python is built around several key concepts:
- Device Client: Represents your physical device connecting to IoT Hub.
- Telemetry: Data sent from the device to the cloud (e.g., sensor readings).
- Device Twin: A cloud representation of your device, used for managing device state and properties.
- Direct Methods: RPC-style calls from the cloud to the device.
- Cloud-to-Device (C2D) Messages: Messages sent from the cloud to the device.
Authentication
The SDK supports several authentication methods:
- Connection String: The simplest method, suitable for many scenarios.
- Symmetric Keys: Devices can authenticate using pre-shared keys.
- X.509 Certificates: For enhanced security, devices can use X.509 certificates.
Refer to the Authentication Guide for detailed instructions on each method.
Device Management
Device management involves tasks like device provisioning, configuration, and monitoring. The SDK facilitates this by enabling devices to report their status and capabilities.
Sending Telemetry
Devices can send telemetry data to IoT Hub asynchronously. This is typically done in a loop or in response to events.
import json
async def send_telemetry_data(client):
temperature = 25.5
humidity = 60
message = {"temperature": temperature, "humidity": humidity}
await client.send_message(json.dumps(message))
print(f"Sent message: {message}")
# Within your main async function:
# await send_telemetry_data(device_client)
Device Twins
Device twins allow for bidirectional synchronization of device state. You can update reported properties and receive desired properties from the cloud.
# Get reported properties
reported_properties = await device_client.get_twin().get_reported_properties()
print(f"Reported properties: {reported_properties}")
# Report new properties
new_properties = {"firmwareVersion": "1.0.2"}
await device_client.patch_twin_reported_properties(new_properties)
print(f"Patched reported properties: {new_properties}")
# Handle desired property updates
def twin_patch_handler(patch):
print(f"Received twin patch: {patch}")
# Update device configuration based on patch
if "interval" in patch.get("properties", {}).get("desired", {}):
new_interval = patch["properties"]["desired"]["interval"]
print(f"New desired interval: {new_interval}")
# Update internal device logic
device_client.on_twin_desired_properties_patch_received = twin_patch_handler
Direct Methods
Direct methods are used for invoking operations on a device from the cloud. You can implement handlers for these methods on your device.
async def method_request_handler(method_name, payload, device_client):
print(f"Received method: {method_name} with payload: {payload}")
if method_name == "reboot":
print("Executing reboot command...")
# Simulate reboot
response_payload = {"status": "reboot initiated"}
return await device_client.invoke_method_reply(method_payload=response_payload, method_status=200)
else:
print(f"Unknown method: {method_name}")
response_payload = {"status": "unknown method"}
return await device_client.invoke_method_reply(method_payload=response_payload, method_status=404)
# Assign the handler
device_client.on_method_request_received = method_request_handler
Cloud-to-Device Messages
Your device can receive C2D messages from IoT Hub. These messages can be used to send commands or data to the device.
async def message_handler(message):
print(f"Received C2D message: {message.data}")
# Process the message data
# e.g., await device_client.complete_message(message)
device_client.on_message_received = message_handler
Samples & Tutorials
Explore the official samples repository on GitHub for practical examples covering various scenarios, including:
- Sending telemetry
- Handling device twins
- Responding to direct methods
- Connecting with different authentication methods
- Working with specific hardware (e.g., Raspberry Pi)
Troubleshooting
If you encounter issues, please consult the following resources:
- Check your IoT Hub configuration and device connection string.
- Review the GitHub issues page for known problems and solutions.
- Ensure your network connectivity allows communication with Azure IoT Hub endpoints.
- Use logging to capture detailed information about your application's behavior.
AZURE_IOT_DEVICE_LOGGING_LEVEL
to DEBUG
or INFO
.