教程:使用 Azure IoT 中心设备预配服务客户端将设备登记到 IoT 中心 (.NET)Tutorial: Enroll the device to an IoT hub using the Azure IoT Hub Provisioning Service Client (.NET)

前面的教程介绍了设置设备以连接到设备预配服务的方法。In the previous tutorial, you learned how to set up a device to connect to your Device Provisioning service. 本教程介绍如何使用此服务通过 单独登记登记组 将设备预配到单个 IoT 中心。In this tutorial, you learn how to use this service to provision your device to a single IoT hub, using both Individual Enrollment and Enrollment Groups. 本教程演示如何:This tutorial shows you how to:

  • 注册设备Enroll the device
  • 启动设备Start the device
  • 验证设备已注册Verify the device is registered

先决条件Prerequisites

继续之前,请确保已配置设备及其“硬件安全模块”(按使用 Azure IoT 中心设备预配服务设置设备以进行预配教程所述) 。Before you proceed, make sure to configure your device and its Hardware Security Module as discussed in the tutorial Set up a device to provision using Azure IoT Hub Device Provisioning Service.

  • Visual StudioVisual Studio

备注

不需要 Visual Studio。Visual Studio is not required. 只需安装 .NET 便已足够,开发人员可以在 Windows 或 Linux 上使用其偏好的编辑器。The installation of .NET is sufficient and developers can use their preferred editor on Windows or Linux.

本教程模拟在将设备信息添加到预配服务时,硬件制造过程中或紧接在该过程之后的情况。This tutorial simulates the period during or right after the hardware manufacturing process, when device information is added to the provisioning service. 此代码通常在电脑上,或者在可以运行 .NET 代码的工厂设备上运行,不应添加到设备本身。This code is usually run on a PC or a factory device that can run .NET code and should not be added to the devices themselves.

注册设备Enroll the device

此步骤需要将设备的唯一安全项目添加到设备预配服务。This step involves adding the device's unique security artifacts to the Device Provisioning Service. 这些安全项目如下所示:These security artifacts are as follows:

  • 对于基于 TPM 的设备:For TPM-based devices:

    • 对每个 TPM 芯片或模拟唯一的“认可密钥” 。The Endorsement Key that is unique to each TPM chip or simulation. 请阅读了解 TPM 认可密钥获取详细信息。Read the Understand TPM Endorsement Key for more information.
    • 注册 ID,用于在命名空间/作用域内唯一标识设备 。The Registration ID that is used to uniquely identify a device in the namespace/scope. 可能与设备 ID 相同或不同。This may or may not be the same as the device ID. 此 ID 是每台设备的必备项。The ID is mandatory for every device. 对于基于 TPM 的设备,可能从 TPM 本身派生注册 ID,例如 TPM 认可密钥的 SHA-256 哈希。For TPM-based devices, the registration ID may be derived from the TPM itself, for example, an SHA-256 hash of the TPM Endorsement Key.
  • 对于基于 X.509 的设备:For X.509 based devices:

    • 颁发给设备的 X.509 证书,采用 .pem.cer 文件格式。The X.509 certificate issued to the device, in the form of either a .pem or a .cer file. 对于单独登记,需要对 X.509 系统使用叶证书;对于登记组,需要使用根证书或同等的签名人证书 。For individual enrollment, you need to use the leaf certificate for your X.509 system, while for enrollment groups, you need to use the root certificate or an equivalent signer certificate.
    • 注册 ID,用于在命名空间/作用域内唯一标识设备 。The Registration ID that is used to uniquely identify a device in the namespace/scope. 可能与设备 ID 相同或不同。This may or may not be the same as the device ID. 此 ID 是每台设备的必备项。The ID is mandatory for every device. 对于基于 X.509 的设备,注册 ID 派生自证书的公用名 (CN)。For X.509 based devices, the registration ID is derived from the certificate's common name (CN). 有关这些要求的详细信息,请参阅设备概念For further information on these requirements see Device concepts.

可通过两种方法向设备预配服务注册设备:There are two ways to enroll the device to the Device Provisioning Service:

  • 单独注册 表示可使用设备预配服务进行注册的单一设备条目。Individual Enrollments This represents an entry for a single device that may register with the Device Provisioning Service. 单独注册可使用 X.509 证书或 SAS 令牌(在真实或虚拟 TPM 中)作为证明机制。Individual enrollments may use either X.509 certificates or SAS tokens (in a real or virtual TPM) as attestation mechanisms. 建议对需要唯一初始配置的设备或仅能通过 TPM 使用 SAS 令牌作为证明机制的设备使用单独登记。We recommend using individual enrollments for devices, which require unique initial configurations, or for devices that can only use SAS tokens via TPM as the attestation mechanism. 单独注册可能会指定所需 IoT 中心设备 ID。Individual enrollments may have the desired IoT hub device ID specified.

  • 注册组 表示共享特定证明机制的一组设备。Enrollment Groups This represents a group of devices that share a specific attestation mechanism. 对于共享所需初始配置的大量设备,或者全部转到同一租户的设备,建议使用注册组。We recommend using an enrollment group for a large number of devices, which share a desired initial configuration, or for devices all going to the same tenant. 登记组只使用 X.509,所有组共享其 X.509 证书链中的签名证书。Enrollment groups are X.509 only and all share a signing certificate in their X.509 certificate chain.

使用单独登记来登记设备Enroll the device using Individual Enrollments

  1. 在 Visual Studio 中,使用“控制台应用”项目模板创建一个 Visual C# 控制台应用程序项目。 In Visual Studio, create a Visual C# Console Application project by using the Console App project template. 将项目命名为 DeviceProvisioningName the project DeviceProvisioning.

  2. 在解决方案资源管理器中,右键单击“DeviceProvisioning”项目,然后单击“管理 NuGet 包...”。 In Solution Explorer, right-click the DeviceProvisioning project, and then click Manage NuGet Packages....

  3. 在“NuGet 包管理器”窗口中,选择“浏览”,搜索 microsoft.azure.devices.provisioning.serviceIn the NuGet Package Manager window, select Browse and search for microsoft.azure.devices.provisioning.service. 选择该项,单击“安装”以安装 Microsoft.Azure.Devices.Provisioning.Service 包,并接受使用条款。 Select the entry and click Install to install the Microsoft.Azure.Devices.Provisioning.Service package, and accept the terms of use. 此过程会下载、安装 Azure IoT 设备预配服务 SDK NuGet 包及其依赖项并添加对它的引用。This procedure downloads, installs, and adds a reference to the Azure IoT Device Provisioning Service SDK NuGet package and its dependencies.

  4. 在 Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices.Provisioning.Service;
    
  5. 将以下字段添加到 Program 类 。Add the following fields to the Program class. 将占位符值替换为上一部分中所述的设备预配服务连接字符串。Replace the placeholder value with the Device Provisioning Service connection string noted in the previous section.

    static readonly string ServiceConnectionString = "{Device Provisioning Service connection string}";
    
    private const string SampleRegistrationId = "sample-individual-csharp";
    private const string SampleTpmEndorsementKey =
            "AToAAQALAAMAsgAgg3GXZ0SEs/gakMyNRqXXJP1S124GUgtk8qHaGzMUaaoABgCAAEMAEAgAAAAAAAEAxsj2gUS" +
            "cTk1UjuioeTlfGYZrrimExB+bScH75adUMRIi2UOMxG1kw4y+9RW/IVoMl4e620VxZad0ARX2gUqVjYO7KPVt3d" +
            "yKhZS3dkcvfBisBhP1XH9B33VqHG9SHnbnQXdBUaCgKAfxome8UmBKfe+naTsE5fkvjb/do3/dD6l4sGBwFCnKR" +
            "dln4XpM03zLpoHFao8zOwt8l/uP3qUIxmCYv9A7m69Ms+5/pCkTu/rK4mRDsfhZ0QLfbzVI6zQFOKF/rwsfBtFe" +
            "WlWtcuJMKlXdD8TXWElTzgh7JS4qhFzreL0c1mI0GCj+Aws0usZh7dLIVPnlgZcBhgy1SSDQMQ==";
    private const string OptionalDeviceId = "myCSharpDevice";
    private const ProvisioningStatus OptionalProvisioningStatus = ProvisioningStatus.Enabled;
    
  6. 添加以下代码,用于执行设备登记:Add the following to implement the enrollment for the device:

    static async Task SetRegistrationDataAsync()
    {
        Console.WriteLine("Starting SetRegistrationData");
    
        Attestation attestation = new TpmAttestation(SampleTpmEndorsementKey);
    
        IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, attestation);
    
        individualEnrollment.DeviceId = OptionalDeviceId;
        individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
    
        Console.WriteLine("\nAdding new individualEnrollment...");
        var serviceClient = ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString);
    
        IndividualEnrollment individualEnrollmentResult =
            await serviceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
    
        Console.WriteLine("\nIndividualEnrollment created with success.");
        Console.WriteLine(individualEnrollmentResult);
    }
    
  7. 最后,将以下代码添加到 Main 方法,打开与 IoT 中心的连接并开始组登记:Finally, add the following code to the Main method to open the connection to your IoT hub and begin the enrollment:

    try
    {
        Console.WriteLine("IoT Device Provisioning example");
    
        SetRegistrationDataAsync().GetAwaiter().GetResult();
    
        Console.WriteLine("Done, hit enter to exit.");
    }
    catch (Exception ex)
    {
        Console.WriteLine();
        Console.WriteLine("Error in sample: {0}", ex.Message);
    }
    Console.ReadLine();
    
  8. 在 Visual Studio 的“解决方案资源管理器”中右键单击解决方案,并单击“设置启动项目...” 。选择“单个启动项目”,并在下拉菜单中选择“DeviceProvisioning”项目。 In the Visual Studio Solution Explorer, right-click your solution, and then click Set StartUp Projects.... Select Single startup project, and then select the DeviceProvisioning project in the dropdown menu.

  9. 运行 .NET 设备应用 DeviceProvisiongRun the .NET device app DeviceProvisiong. 该应用应会设置设备预配:It should set up provisioning for the device:

    运行单独注册

成功注册后,设备应显示在门户中,如下所示:When the device is successfully enrolled, you should see it displayed in the portal as following:

门户中的成功登记消息

使用登记组来登记设备Enroll the device using Enrollment Groups

备注

登记组示例需要 X.509 证书。The enrollment group sample requires an X.509 certificate.

  1. 在 Visual Studio 的解决方案资源管理器中,打开前面创建的“DeviceProvisioning”项目。 In the Visual Studio Solution Explorer, open the DeviceProvisioning project created above.

  2. 在 Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

    using System.Security.Cryptography.X509Certificates;
    
  3. 将以下字段添加到 Program 类 。Add the following fields to the Program class. 将占位符值替换为 X509 证书位置。Replace the placeholder value with the X509 certificate location.

    private const string X509RootCertPathVar = "{X509 Certificate Location}";
    private const string SampleEnrollmentGroupId = "sample-group-csharp";
    
  4. 将以下代码添加到 Program.cs,用于执行组登记:Add the following to Program.cs implement the enrollment for the group:

    public static async Task SetGroupRegistrationDataAsync()
    {
        Console.WriteLine("Starting SetGroupRegistrationData");
    
        using (ProvisioningServiceClient provisioningServiceClient =
                ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString))
        {
            Console.WriteLine("\nCreating a new enrollmentGroup...");
    
            var certificate = new X509Certificate2(X509RootCertPathVar);
    
            Attestation attestation = X509Attestation.CreateFromRootCertificates(certificate);
    
            EnrollmentGroup enrollmentGroup = new EnrollmentGroup(SampleEnrollmentGroupId, attestation);
    
            Console.WriteLine(enrollmentGroup);
            Console.WriteLine("\nAdding new enrollmentGroup...");
    
            EnrollmentGroup enrollmentGroupResult =
                await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
    
            Console.WriteLine("\nEnrollmentGroup created with success.");
            Console.WriteLine(enrollmentGroupResult);
        }
    }
    
  5. 最后,在 Main 方法中替换以下代码,打开与 IoT 中心的连接并开始登记:Finally, replace the following code to the Main method to open the connection to your IoT hub and begin the group enrollment:

    try
    {
        Console.WriteLine("IoT Device Group Provisioning example");
    
        SetGroupRegistrationDataAsync().GetAwaiter().GetResult();
    
        Console.WriteLine("Done, hit enter to exit.");
        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine();
        Console.WriteLine("Error in sample: {0}", ex.Message);
    }
    
  6. 运行 .NET 设备应用 DeviceProvisiongRun the .NET device app DeviceProvisiong. 该应用应会设置设备的组预配:It should set up group provisioning for the device:

    运行组注册

    成功登记设备组后,该组应会显示在门户中,如下所示:When the device group is successfully enrolled, you should see it displayed in the portal as following:

    门户中的登记组成功消息

启动设备Start the device

现在,以下设置已可用于设备注册:At this point, the following setup is ready for device registration:

  1. 设备或一组设备将向设备预配服务进行注册,并且Your device or group of devices are enrolled to your Device Provisioning service, and
  2. 现在可以使用设备预配服务客户端 SDK 通过应用程序在设备中配置安全性并对其进行访问。Your device is ready with the security configured and accessible through the application using the Device Provisioning Service client SDK.

启动设备可使客户端应用程序开始向设备预配服务进行注册。Start the device to allow your client application to start the registration with your Device Provisioning service.

验证设备已注册Verify the device is registered

设备启动后,应进行以下操作。Once your device boots, the following actions should take place. 请参阅预配设备客户端示例,了解更多详细信息。See the Provisioning Device Client Sample for more details.

  1. 设备会向设备预配服务发送注册请求。The device sends a registration request to your Device Provisioning service.

  2. 对于 TPM 设备,设备预配服务将回复注册质询,设备需对此进行答复。For TPM devices, the Device Provisioning Service sends back a registration challenge to which your device responds.

  3. 注册成功后,设备预配服务会向设备发送 IoT 中心 URI、设备 ID 和加密密钥。On successful registration, the Device Provisioning Service sends the IoT hub URI, device ID, and the encrypted key back to the device.

  4. 设备上的 IoT 中心客户端应用程序随后会连接到你的中心。The IoT Hub client application on the device then connects to your hub.

  5. 成功连接到中心后,设备应出现在 IoT 中心的“Device Explorer”中 。On successful connection to the hub, you should see the device appear in the IoT hub's Device Explorer.

    成功连接到门户中的中心

后续步骤Next steps

在本教程中,你了解了如何执行以下操作:In this tutorial, you learned how to:

  • 注册设备Enroll the device
  • 启动设备Start the device
  • 验证设备已注册Verify the device is registered

前往下一教程,了解如何跨负载均衡的中心预配多台设备。Advance to the next tutorial to learn how to provision multiple devices across load-balanced hubs.