首页 > 解决方案 > 使用 mqtt 以编程方式在 Azure IoT-hub 上注册设备

问题描述

无论如何,是否可以使用自我/CA 创建的证书以编程方式将新设备注册到 azure iot-hub?

例如,我想将我的树莓派从同一个树莓派注册到我新创建的 IOT-HUB。我知道我们可以使用 AZ Cli 来做到这一点。我正在寻找的是有一种方法可以使用 MQTT/REST 以编程方式进行吗?

提前致谢。

问候, Pradeep

标签: azureazure-iot-hubazure-iot-hub-device-management

解决方案


您可以使用设备配置服务 - DPS。DPS 是另一项服务,其目的是识别您的设备,如果设备标识被 DPS 识别,DPS 将在您的 IoT Hub 中创建一个身份。

您设置 DPS 的方式是创建个人注册(用于单个设备载入)或组注册(对于一组设备,通常如果您使用证书或共享访问密钥身份验证类型)。注册通常包含设备应显示的标识类型,以及应将具有显示标识的设备分配到的 IoT 中心。

典型流程是设备通过一些公共标识(证书链、TPM 注册 ID 或 SAS 密钥)联系 DPS。然后在内部,DPS 可以质询设备(CA 证书的情况下为占有证明),如果设备成功解决了质询,则意味着该设备包含一个特定的秘密(CA 证书的情况下为私钥)标识该设备,因此 DPS 将为该特定注册中分配的集线器创建设备标识。这个过程称为证明

因此,在设备端,您至少会收到 IoT 中心终结点以及用于与 IoT 中心通信的设备 ID。

下面是如何使用 CA 证书和 C# 执行此操作的代码片段:

var certificate = new X509Certificate2(leafCertificatePath, leafCertificatePassword);
    using (var security = new SecurityProviderX509Certificate(certificate))
    using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
    {
        ProvisioningDeviceClient provClient =
        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsScope, security, transport);
    
        var deviceAuthentication = await GetDeviceRegistrationResultAsync(provClient, security);
    
        var auth = new DeviceAuthenticationWithX509Certificate(deviceAuthentication.DeviceId, security.GetAuthenticationCertificate());
    
        var deviceClient = DeviceClient.Create(hostname: deviceAuthentication.AssignedHub,
                                               authenticationMethod: auth,
                                               transportType: TransportType.Mqtt);
    
    
        if (deviceClient == null)
        {
            Console.WriteLine("Failed to create DeviceClient!");
        }
        else
        {
            SendEvents(deviceClient, MESSAGE_COUNT).Wait();
        }
    }

从DPS获取设备注册结果的方法:

static async Task<DeviceRegistrationResult> GetDeviceRegistrationResultAsync(ProvisioningDeviceClient provClient, SecurityProviderX509 security)
{
    DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
    {
        throw new Exception("Device not assigned");
    }
    return result;
}

您可以在此处找到来自 MSFT 的官方示例

以下是使用 IoT 中心和 DPS 创建和验证证书的方法。


推荐阅读