How to obtain IoT Device hostname to use in a C# app to generate custom data telemetry

GuidoL 310 Reputation points
2023-12-18T17:18:42.1833333+00:00

Hi, as suggested @LeelaRajeshSayana-MSFT

i use the following code to generate custom telemetry in Iot Central device:


using Microsoft.Azure.Devices.Client;
using System.Text;
using Newtonsoft.Json;


namespace MyApp 
{
    internal class SimpleApp
    {
        private const string ModelId = "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor;1";


        //public static string DeviceId = "<DeviceId";
        public static string DeviceId = "LibraryItemGateCheckSensor02";

        // obtain if you get it once connected to the device
        //public static string DeviceSymmetricKey = "<DevicePrimaryKey>"
        public static string DeviceSymmetricKey = "vttfVFxa********UCvVE1***uJqRg=";


        public static string hostname = "<IoTCentralHostname>";
        //public static string hostname = "???";

        static async Task Main(string[] args)
        {
            Console.WriteLine("Generating Data..");

            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceSymmetricKey);


            var options = new ClientOptions
            {
                ModelId = ModelId,
            };

            DeviceClient deviceClient = DeviceClient.Create(hostname, authMethod, TransportType.Mqtt, options);

            var cts = new CancellationTokenSource();

            List<string> ItemID = new List<string>() {
                "USB 2364",
                "USB 2365",
                "USB 2366",
                "USB 2367",
                "USB 2370",
                "USB 2373",
                "USB 2375",
                "USB 2376",
                "USB 2501",
                "USB 2606"
            };

            List<string> Description = new List<string>() {
                "*Re-inventare la famiglia : guida teorico-pratica per i professionisti dell'educazione / a cura di Laura Formenti Santarcangelo di Romagna : Maggioli, 2016.. XXII, 451 p. ; 21 cm",
                "Le *parole dell'etica / Antonio Da Re [Milano] : Bruno Mondadori, 2010 XII, 215 p. ; 21 cm",
                "*Teoria e prassi in pedagogia : questioni epistemologiche / a cura di Massimo Baldacci ed Enza Colicchi Roma : Carocci, 2016 258 p. ; 22 cm",
                "*Cantar ottave : per una storia culturale dell'intonazione cantata in ottava rima / a cura di Maurizio Agamennone Lucca : Libreria musicale italiana, 2017 XXVI, 184 p. ; 24 cm",
                "*sacré dans la vie quotidienne : suivi de Notes pour Le sacré dans la vie quotidienne ou L'homme sans honneur / Michel Leiris ; présentation et notes de Denis Hollier ; préface de Lionel Menasché Paris : Allia, 2018 140 p. ; 17 cm",
                "*Didattica e intercultura / Donatello Santarone Roma : Armando, 2012 127 p. ; 20 cm",
                "*Teorie e metodi di pedagogia interculturale / Mariangela Giusti Bari ; Roma : Laterza, 2017 VI, 188 p. ; 21 cm",
                "L'*italiano accademico : uno studio sulla glottodidattica dell'italiano lingua di studio all'università a studenti in mobilità internazionale / Elena Ballarin Saarbrücken : Edizioni Accademiche Italiane, 2017 243 p. : ill. ; 22 cm",
                "*Empirismo e soggettività : Saggio sulla natura umana secondo Hume / Gilles Deleuze ; a cura di Adriano Vinale. - 2. Ed Napoli : Cronopio , 2012 174 p. ; 21 cm",
                "La *vita delle piante : metafisica della mescolanza / Emanuele Coccia Bologna : Il mulino, 2018 159 p. ; 21 cm"
            };


            List<string> Location = new List<string>() {
                "Main Gate"             
            };


            Random randNum = new Random();
            while (true)
            {
                string telemetryName = "ItemId";
                int index = randNum.Next(ItemID.Count);
                Encoding messageEncoding = Encoding.UTF8;
                IDictionary<string, object> telemetryPairs = new Dictionary<string, object> { { telemetryName, ItemID[index] } };

                telemetryName = "Description";
                index = randNum.Next(Description.Count);
                telemetryPairs.Add(telemetryName, Description[index]);

                telemetryName = "Location";
                index = randNum.Next(Location.Count);
                telemetryPairs.Add(telemetryName, Location[index]);
                telemetryName = "DateTimeGateEvent";
                DateTime time = DateTime.Now;
                telemetryPairs.Add(telemetryName, time);

                string payload = JsonConvert.SerializeObject(telemetryPairs);
                var message = new Message(messageEncoding.GetBytes(payload))
                {
                    ContentEncoding = messageEncoding.WebName,
                    ContentType = "application/json",
                };
                await deviceClient.SendEventAsync(message, cts.Token);

                Console.WriteLine("Message delivered");

                Thread.Sleep(30000);
            }

        }
    }


but i'm not able to obtain the hostname .

He suggested that

"The best wat to get this value is by observing the hostname property in the Program.cs file by executing the TemperatureController solution. To get this, open the azure-ot-sdk-csharp/iothub/device/samples/solutions/pnpdevicesamples/TemperatureController solution in Visual Studio, put a break point on line 165 of Program.cs file and launch the program in Debug mode. Once the program execution hits the line, inspect the value assigned  to hostname variable. Please refer the below image for more details"

but in my case is there an easier way to obtain the hostname that i need for code? In IoT Central device management i can't find any reference or even in messages properties of Iot Central Service bus queue explorer that i used to update my Digital Twins properties.

I remain available for any clarifications needed.

Thanks in advance.

Guido

Azure IoT
Azure IoT
A category of Azure services for internet of things devices.
391 questions
Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
358 questions
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 13,951 Reputation points
    2024-01-16T22:24:22.7066667+00:00

    Hi @GuidoL Thank you for connecting with us offline. The Azure IoT Central uses IoT Hub on the backend. The hostname referenced in the code is the IoT Hub hostname. As far as I can tell there is no exposed endpoint that lets us know the IoT Hub hostname being used by the IoT Central application.

    Here is the approach originally mentioned to achieve the IoT Hub Hostname

    Open azure-ot-sdk-csharp/iothub/device/samples/solutions/pnpdevicesamples/TemperatureController solution in Visual Studio, put a break point on line 165 of Program.cs and launching the program in Debug mode to get the hostname.

    Thank you for pointing out the alternate approach to achieve the same without having to going through the code. I am sharing the same with the community here for the benefit of others.

    1. Create a test device on the Azure IoT Central portal.
    2. Download IoT Plug and Play application on your mobile device.
    3. Open the Connect settings of the device on the Azure portal and click on the QR code option.
    4. From the IoT Plug and Play application on the device, scan the QR code of the device.
    5. Once the device connects, click on the logs tab and inspect the logs to find the section Got credentials for DPS. The host parameter value reveals the underlying IoT Hub hostname used by the IoT Central. Please find the below image for reference.

    User's image

    We will update this thread once we get more information from the team on any other approaches. Hope this helps!


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful