IoTHub Device Management API

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives


If you want to programmatically implement device management in IoTHub, you should use a package .Microsoft.Azure.Devices.

This package provides a very simple API for device management. IotHub maintains under the hub a DocumentDB, which you typically cannot see. We say, “it is transparent for developers”, which is good.

Following code snippet demonstrates how to enlist already provisioned devices:

  private async static Task EnlistDevices()
  {
           var m_RegistryManager = 
          
RegistryManager.CreateFromConnectionString(Key with “Registry Read Perm”);

           

var devices = await m_RegistryManager.GetDevicesAsync(int
.MaxValue);
           
foreach (var device in
devices)
            {
               
Console.WriteLine("------------------------------"
);
               
Console.WriteLine(
"GenId:{0}, Id:{1}\r\nKey:{2}\r\nCommands:{3},
                ConnState:{4}\r\nLast Activity Time:{5}\r\nStatus:{6}, Reason{7},
                StatusUpdate:{8}"
,
                    device.GenerationId,
                    device.Id,
                    device.Authentication.SymmetricKey.PrimaryKey,
                    device.CloudToDeviceMessageCount,
                    device.ConnectionState,

                    device.LastActivityTime,
                    device.Status,
                    device.StatusReason,
                    device.StatusUpdatedTime);
            }

  }


In the code above you can grab all important device properties like deviceId or Key.

When you run code snippet shown above you should get list of all registered devices. Similarly, you can use device explorer tool to enlist all devices.

image

Following code sample demonstrated how to do provisioning of device programmatically. All you have to do is to chose deviceId. and to invoke a method AddDeviceAsync().

private async static Task AddDeviceAsync()
{
           
// Enter here your device name.

           
string deviceId = "mydesktopdevice";
           
Device
device;
           
try

            {
                device =
await
                m_RegistryManager.AddDeviceAsync(
new Device
(deviceId));
            }
           
catch (DeviceAlreadyExistsException
)
            {
                device =
await
m_RegistryManager.GetDeviceAsync(deviceId);
            }

           
Console.WriteLine("Device key: {0}"
,
            Device.Authentication.SymmetricKey.PrimaryKey);
}


This call will create a new device with specified identifier. Device key will be automatically created and it can be obtained right after successfully provisioned device.


Posted May 31 2016, 06:01 AM by Damir Dobric
developers.de is a .Net Community Blog powered by daenet GmbH.