0
votes

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?

1
doesn't the result of registering the device give you a device id? The client will need to persist that for future requests.Nkosi
i'm getting device id back because i'm inserting it from request but how to get key / secret key / primary key i mean key is also there into connection string ?Neo

1 Answers

1
votes

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 (e.g. 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 (e.g. 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.