首页 文章

如何以安全的方式在IotHub中添加设备?

提问于
浏览
0

使用下面给出的代码片段在azure iot hub中添加设备

static RegistryManager registryManager;
static string connectionString = "{2131ueuruewejds342r2r2qq23udsjf}";

private static async Task AddDeviceAsync()
 {
     **string deviceId = "myFirstDevice"; // from where we get device id?**
     Device device;
     try
     {
         device = await registryManager.AddDeviceAsync(new Device(deviceId));
     }
     catch (DeviceAlreadyExistsException)
     {
         device = await registryManager.GetDeviceAsync(deviceId);
     }
     Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey);
 }

我的问题是,我们将从哪里获得设备ID?

快乐编码

1 回答

  • 1

    您正在使用的方法是在IoT Hub中创建新设备 . 您可以使用任何设备ID,例如“myNewIoTHubDevice”或“AcceleratorDevice” .

    此方法使用您的设备ID创建一个新设备,并返回设备的主键 . 之后,您可以使用该设备将数据发送到IoT Hub,如下面的代码段:

    private static async void SendDeviceToCloudMessagesAsync()
    {
     double avgWindSpeed = 10;
     Random rand = new Random();
    
     while (true)
     {
         double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 - 2;
    
         var telemetryDataPoint = new
         {
             deviceId = "myFirstDevice",
             windSpeed = currentWindSpeed
         };
         var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
         var message = new Message(Encoding.ASCII.GetBytes(messageString));
    
         await deviceClient.SendEventAsync(message);
         Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
    
         await Task.Delay(1000);
     }
    }
    

    如果您调用此方法并且此方法调用已成功,则可以在“设备资源管理器”下的IoT Hub下的Azure门户中查看该设备 .

    这种方式是一种安全的方式,可以生成新设备 .

    阅读this description以了解有关IoT Hub的更多信息 .

    我希望,我理解你的问题 .

相关问题