Fig. 1 Overview of device twins
A device twin is a JSON document that includes:
For more information about device twins, please refer to this page “Understand and use device twins in IoT Hub”.
1. Windows 10 with Visual Studio 2019 Community (“Python development” workload required) 2. Python Azure IoT SDK: https://github.com/Azure/azure-iot-sdk-python/tree/master/azure-iot-device/samples
import
os
asyncio
random
from
azure.iot.device.aio
IoTHubDeviceClient
async
def
main():
conn_str
=
"HostName=***.azure-devices.net;DeviceId=***;SharedAccessKey=***"
device_client
IoTHubDeviceClient.create_from_connection_string(conn_str)
# connect the client.
await device_client.connect()
# update the reported properties
reported_properties
{
"temperature"
: random.randint(
320
,
800
)
/
10
}
print
(
"Setting reported temperature to {}"
.format(reported_properties[
]))
await device_client.patch_twin_reported_properties(reported_properties)
# Finally, disconnect
await device_client.disconnect()
if
__name__
"__main__"
:
asyncio.run(main())
# If using Python 3.6 or below, use the following code instead of asyncio.run(main()):
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
# loop.close()
Fig. 3 Device twin on Azure portal
Now, if we want to update the configurations in the device, we can use desire properties of the device twins. Create a Python project with “Python Application” project temple, give a name such as “PythonIoTDemo”. Copy and paste the following code to “PythonIoTDemo.py”. Make sure that you substitute with your own connection string in the code.
# define behavior for receiving a twin patch
twin_patch_listener(device_client):
while
True
patch
await device_client.receive_twin_desired_properties_patch()
# blocking call
"the data in the desired properties patch was: {}"
.format(patch))
# define behavior for halting the application
stdin_listener():
selection
input(
"Press Q to quit\n"
"Q"
or
"q"
"Quitting..."
break
# Schedule task for twin patch
asyncio.create_task(twin_patch_listener(device_client))
# Run the stdin listener in the event loop
loop
asyncio.get_running_loop()
user_finished
loop.run_in_executor(
None
, stdin_listener)
# Wait for user to indicate they are done listening for messages
await user_finished
Run the application. Then, we add the following “desired” JSON code to the Device twin on Azure Portal
"desired"
: {
: 40.1,
"telemetryConfig"
"sendFrequency"
"1m"
},
"$metadata"
: {}