Search code examples
azure-iot-sdk

.NET get DeviceId from Microsoft.Azure.Devices.Client.ModuleClient


I would like to get the assigned device-id from Microsoft.Azure.Devices.Client.ModuleClient assigned from the IoT-Hub to my module.

What is the best way to retrieve the device-id at runtime?


Solution

  • So we have to make use of a back-end solution to Read Module Twin Properties, like deviceId. This is by design, you have to make use of Back end app as stated in following Document : Module twins , Inside the Module App only Desired and Reported are available. enter image description here

    Please refer to Get started with IoT Hub module identity and module twin (.NET)

    Sample Console C# app : Make use of 'registryManager' to query all devices with the query language. The query functionality is exposed by the C# service SDK in the RegistryManager class.

    var query = registryManager.CreateQuery("SELECT * FROM devices", 100);

    Complete sample console C# code snippet is as shown below. [using Microsoft.Azure.Devices;]

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common.Exceptions;
    using Newtonsoft.Json;
    using System;
    using System.Threading.Tasks;
    
    namespace CreateIds
    {
        class Program
        {
            const string connectionString ="<>";     
            static void Main(string[] args)
            {
                GetDeviceIdAsync().Wait();
            }
            private static async Task GetDeviceIdAsync()
            {
                RegistryManager registryManager =
                  RegistryManager.CreateFromConnectionString(connectionString);
                try
                {
                    
                    var query = registryManager.CreateQuery("SELECT * FROM devices", 100);
                    while (query.HasMoreResults)
                    {
                        var page = await query.GetNextAsTwinAsync();
                        foreach (var twin in page)
                        {
                            Console.WriteLine(JsonConvert.SerializeObject(twin.DeviceId));
                        }
                    }
                }
                catch (DeviceAlreadyExistsException dvcEx)
                {
                    Console.WriteLine("Error : {0}", dvcEx);
                }
    
            }
        }
    }
    

    enter image description here

    Update 1: Using 'Where' clause to get deviceId Example json twin from devices.modules looks like the below one. Now we have to query by using 'Where' clause like moduleId='sampleModule'

    Sample:{"deviceId":"devkitdps","moduleId":"sampleModule","etag":"AAAAAAAAAAE=","version":4,"status":"enabled","statusUpdateTime":"0001-01-01T00:00:00Z","connectionState":"Disconnected","lastActivityTime":"0001-01-01T00:00:00Z","cloudToDeviceMessageCount":0,"authenticationType":"sas","x509Thumbprint":{"primaryThumbprint":null,"secondaryThumbprint":null},"properties":{"desired":{"$metadata":{"$lastUpdated":"0001-01-01T00:00:00Z"},"$version":1},"reported":{"DateTimeLastAppLaunch":"2020-06-23T17:22:19.4938255-07:00","$metadata":{"$lastUpdated":"2020-06-24T00:22:19.6523448Z","DateTimeLastAppLaunch":{"$lastUpdated":"2020-06-24T00:22:19.6523448Z"}},"$version":3}}}
    
      var query = registryManager.CreateQuery("SELECT * FROM devices.modules Where moduleId='sampleModule'", 100);
                    while (query.HasMoreResults)
                    {
                        var page = await query.GetNextAsTwinAsync();
                        foreach (var twin in page)
                        {
                            Console.WriteLine(JsonConvert.SerializeObject(twin.DeviceId));
                        }
                    }
    

    Please let us know if you need further help!