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

PropertyBack-end (cloud)Device app
tagsRead + WriteNo access
desiredRead + WriteRead only
reportedRead onlyRead + Write

Properties starting with $ are Azure-managed — do NOT try to set them.

High-Level Flow

  1. Back-end sets desired property in IoT Hub
  2. Device reads desired property (immediately if connected, or on reconnect)
  3. Device processes the change
  4. Device sets reported property confirming new state
  5. Back-end reads reported property

Python Device Implementation

pip install azure-iot-device
from 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