Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Introduction
Recently, Microsoft has released the new version of Python Azure IoT SDK (V2.0) (refer to this page on IoT blog: New version of the Python SDK released). According to the release announcement, we should upgrade SDK from V1 to V2 since the v2 SDK aims to provide a simplified, more natural experience for developers. It’s designed in native Python.
In the previous tutorials, we first installed the new Python Azure IoT SDK on Windows 10 and made a demo Python project with Visual Studio to send simulation date to the Azure IoTHub. Then we showed how to invoke Direct Methods from Backend App. Also, device twins including reported properties and desired properties were demonstrated. For more details, please refer to the pervious tutorials:
- How to use Python Azure IoT SDK with Visual Studio
- Python Azure IoT SDK: How to receive direct methods from IoT Hub
- Python Azure IoT SDK: How to use device twins in IoT Hub
In this article, we will walk you through the steps required to build a sample application for device provision service with symmetric keys in Python Azure IoT SDK.
Device provision service
The IoT Hub Device Provisioning Service (DPS) is a helper service for IoT Hub that enables zero-touch, just-in-time provisioning to the right IoT hub without requiring human intervention, allowing customers to provision millions of devices in a secure and scalable manner. The workflow of the device provision service is shown in Fig. 1. The first step is manual, all of the following steps are automated.
Fig. 1 Workflow of device provision service
- Device manufacturer adds the device registration information to the enrollment list in the Azure portal.
- Device contacts the DPS endpoint set at the factory. The device passes the identifying information to DPS to prove its identity.
- DPS validates the identity of the device by validating the registration ID and key against the enrollment list entry using either a nonce challenge (Trusted Platform Module) or standard X.509 verification (X.509).
- DPS registers the device with an IoT hub and populates the device's desired twin state.
- The IoT hub returns device ID information to DPS.
- DPS returns the IoT hub connection information to the device. The device can now start sending data directly to the IoT hub.
- The device connects to IoT hub.
- The device gets the desired state from its device twin in IoT hub.
For more information about device provision service, please refer to this page “Provisioning devices with Azure IoT Hub Device Provisioning Service”.
Device Provisioning Service supports the following forms of attestation:
- X.509 certificates based on the standard X.509 certificate authentication flow.
- Trusted Platform Module (TPM) based on a nonce challenge, using the TPM standard for keys to present a signed Shared Access Signature (SAS) token. This form of attestation does not require a physical TPM on the device, but the service expects to attest using the endorsement key per the TPM spec.
- Symmetric Key based on shared access signature (SAS) Security tokens, which include a hashed signature and an embedded expiration. For more information, see Symmetric key attestation.
In this tutorial, we will use symmetric keys for attestation.
Prerequisites
- 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
- 3. Setup IoT Hub Device Provisioning Service with the Azure portal
Create a device enrollment entry in the portal
Please sign in to the Azure portal, select the All resources button on the left-hand menu and open your Device Provisioning service. Select the Manage enrollments tab, and then select the Add individual enrollment button at the top. In the Add Enrollment panel, enter the following information, and press the Save button.
- Mechanism: Select Symmetric Key as the identity attestation Mechanism.
- Auto-generate keys: Check this box.
- Registration ID: Enter a registration ID to identify the enrollment. Use only lowercase alphanumeric and dash ('-') characters. For example, symm-key-test-001.
- IoT Hub Device ID: Enter a device identifier. For example, test-device-001.
The settings are also shown in Fig. 2.
Fig. 2 Add individual enrollment for DPS test
** **
Test DPS service on your device
This application will cause the device to be recognized and assigned to an IoT hub linked to the Device Provisioning Service instance. First, we need the provisioning host, id scope, registration id and symmetric key, which can be find in Azure Portal. Navigate to the Overview of your DPS service and you will find provisioning host and id scope as shown in Fig. 3.
Fig.3 Service host and ID Scope for DPS service
Then, you will find registration id and symmetric key in the Management Enrollments tab in your DPS service, which is shown in Fig. 4.
Fig. 4 Registration id and symmetric key for DPS service
Create a Python project with “Python Application” project temple, give a name such as “PythonIoTDPSDemo”. Copy and paste the following code to “PythonIoTDPSDemo.py”. Make sure that you substitute with your own provisioning host, id scope, registration id and symmetric key in the code.
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import asyncio
from azure.iot.device.aio import ProvisioningDeviceClient
import os
from azure.iot.device.aio import IoTHubDeviceClient
from azure.iot.device import Message
import uuid
messages_to_send = 10
provisioning_host = "***.azure-devices-provisioning.net"
id_scope = "0ne000*****"
registration_id = "*****"
symmetric_key = "*****"
async def main():
provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
provisioning_host=provisioning_host,
registration_id=registration_id,
id_scope=id_scope,
symmetric_key=symmetric_key,
)
registration_result = await provisioning_device_client.register()
print("The complete registration result is")
print(registration_result.registration_state)
if registration_result.status == "assigned":
print("Will send telemetry from the provisioned device")
device_client = IoTHubDeviceClient.create_from_symmetric_key(
symmetric_key=symmetric_key,
hostname=registration_result.registration_state.assigned_hub,
device_id=registration_result.registration_state.device_id,
)
# Connect the client.
await device_client.connect()
async def send_test_message(i):
print("sending message #" + str(i))
msg = Message("test wind speed " + str(i))
msg.message_id = uuid.uuid4()
msg.correlation_id = "correlation-1234"
msg.custom_properties["count"] = i
msg.custom_properties["tornado-warning"] = "yes"
await device_client.send_message(msg)
print("done sending message #" + str(i))
# send `messages_to_send` messages in parallel
await asyncio.gather(*[send_test_message(i) for i in range(1, messages_to_send + 1)])
# finally, disconnect
await device_client.disconnect()
else:
print("Can not send telemetry from the provisioned device")
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()
In this application, we will first provision the device and then the device will send device-to-cloud messages. Once the messages are sent, we will see the output information as shown in Fig. 5.
Fig. 5 Debug output in Visual Studio
Now, as soon as the device provision service is done, we can see the status on Azure Portal as presented in Fig. 6.
Fig. 6 The registration status on Azure portal
Summary
In this tutorial, we have presented the process to use device provision service with symmetric keys of Azure IoT Python SDK, including “create a device enrollment entry in the portal” and “test device provision on your device”.
Resources
- Microsoft Docs: Provisioning devices with Azure IoT Hub Device Provisioning Service
- IoT Blog: New version of the Python SDK released
- azure-iot-sdk-python: https://github.com/Azure/azure-iot-sdk-python/tree/master/azure-iot-device/samples
- My Projects on Hackster: Jiong Shi
- Azure IoT Docs: Azure IoTHub