azure - 使用 mqtt 以编程方式在 Azure IoT-hub 上注册设备

标签 azure azure-iot-hub azure-iot-hub-device-management

是否可以使用自行/CA 创建的证书以编程方式将新设备注册到 azure iot-hub 上?

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

提前致谢。

问候, 普拉迪普

最佳答案

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

您可以通过创建单独注册(对于单个设备加入)或组注册(对于一组设备,通常如果您使用证书或共享访问 key 身份验证类型)来设置 DPS。 注册通常包含设备应提供的标识类型,以及应将具有所提供标识的设备分配到的 IoT 中心。

典型的流程是设备使用一些公共(public)标识(证书链、TPM 注册 ID 或 SAS key )联系 DPS。然后在内部,DPS 可以挑战设备( proof-of-possesion in case of CA certificates ),如果设备成功解决挑战,则意味着该设备包含标识该设备的特定 secret (在 CA 证书的情况下为私钥),因此 DPS将在该特定注册中为分配的集线器创 build 备标识。这个过程称为attestation .

因此,在设备端,您至少会收到 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 的官方示例,您可以找到 here

Here这是您使用 IoT 中心和 DPS 创建和验证证书的方式。

关于azure - 使用 mqtt 以编程方式在 Azure IoT-hub 上注册设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65911888/

相关文章:

azure - 使用 Azure 事件中心向所有使用者广播事件

azure - Azure IOT 中心可以用于从某些设备读取(获取)数据吗?

azure - 如何从移动应用程序配置 Azure IoT 设备

c# - 如何使用 Azure IoT C SDK 为 AMQP 协议(protocol)设置某些系统属性,以及它们在 EventHub 中的最终位置?

c# - 使用 Azure IoT 中心设备预配服务 (DPS) 时出现未经授权的异常

azure - Microsoft Azure Iot Hub 中的分区有什么作用?

azure - 授权用户访问 azure blob

Azure 数据流在创建新文件夹路径时生成包含无法识别的扩展名的文件

c# - 在连接 Azure Cosmos DB API for MongoDB 时,如果 ConnectionModeSwitch 设置为 UseConnectionMode,则无法使用 DirectConnection

使用 mqtt 的 Azure Iot Hub 设备配置系统