简体   繁体   中英

How to get device key using device id from IoT hub using C#?

I have created a IoT hub in Azure.

Register a device into IoT hub using below code -

 public async Task<HttpResponseMessage> RegisterDeviceAsyncData(DeviceData deviceApp)
        {
            

                        deviceApp.PlatformName = _appSettingsAccessor.GetAppSettingValue(DEFAULT_HUB_KEY);
   


                    var result = await _deviceRegistrationHandler.RegisterDeviceAsync(deviceApp);
               

                response = HttpResponseMessageFactory.CreateMessageWithObjectBody(results);
            }

it is successfully registering devices into Iot hub, now I want to send data to these devices using C#.

I have code to send data to device below but I don't know how to get connection string of particular device or key to send data.

 private static async Task SendDeviceToCloudMessagesAsync()
        {
    DeviceClient deviceClient = DeviceClient.CreateFromConnectionString("deviceConnectionString");
            while (true)
            {

                string messageString = string.Empty;
                Message iotHubMsg = new Message();

                foreach (BaseMessage msg in currentDevice.Messages)
                {


                        iotHubMsg = msg.ReadAsIotHubMessage();

                    messageString = Encoding.UTF8.GetString(iotHubMsg.GetBytes());

                        //Send the current messages and clear them
                        await deviceClient.SendEventAsync(iotHubMsg);
                        }
                        }
                        }

For now I tried to get connection string using portal.azure.com, but in real time after register device how can I retrieve a connection string? Can I use a SAS token or something like that?

I would try to solve this issue with one of these approaches:

  1. Using a generic device connection string:
    a) go to IoT Hub and from 'Shared access policies" get a connection string for the 'device' policy (eg HostName=iothub.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=abcd1234)
    b) This is a generic connection string. If you add "DeviceId=" it would be specific to your device and IotHub would be able to identify your new/existing device (eg HostName=iothub.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=abcd1234;DeviceId=device001)
  2. Using automatic device provisioning with the help of Azure Device provisioning Service . I have never personally used it, but it should be working. Furthermore, this should be the approach if you have a really big number of devices.

Hopefully, this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM