Source: Device Twins — Connected Objects
What are Device Twins?
JSON documents stored online in Azure IoT Hub — contain device state, metadata, configurations.
NOT for high-frequency telemetry — use D2C messages for that. Device twins are for configuration/state synchronization.
Device Twin Structure
{
"deviceId": "devA",
"tags": {
"deploymentLocation": { "building": "43", "floor": "1" }
},
"properties": {
"desired": {
"telemetryConfig": { "sendFrequency": "5m" }
},
"reported": {
"telemetryConfig": { "sendFrequency": "5m", "status": "success" },
"batteryLevel": 55
}
}
}Access Rules
| Property | Back-end (cloud) | Device app |
|---|---|---|
| tags | Read + Write | No access |
| desired | Read + Write | Read only |
| reported | Read only | Read + Write |
Properties starting with $ are Azure-managed — do NOT try to set them.
High-Level Flow
- Back-end sets desired property in IoT Hub
- Device reads desired property (immediately if connected, or on reconnect)
- Device processes the change
- Device sets reported property confirming new state
- Back-end reads reported property
Python Device Implementation
pip install azure-iot-devicefrom azure.iot.hub import IoTHubDeviceClient
# 1. Connect
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
device_client.connect()
# 2. Set callback for incoming desired property changes
def twin_patch_handler(twin_patch):
print(f"Twin patch received: {twin_patch}")
device_client.on_twin_desired_properties_patch_received = twin_patch_handler
# 3. Get full twin on first connect (device reconnection flow)
twin = device_client.get_twin()
# 4. Update reported properties
reported_patch = {"telemetry_interval": 20}
device_client.patch_twin_reported_properties(reported_patch)
# 5. Disconnect
device_client.shutdown()See Also
- Azure IoT Overview topic
- Device to Cloud Communication source