How to connect to an IoT Central device using C# code in a SIMPLE WAY and generate CUSTOM telemetry data?

GuidoL 310 Reputation points
2024-01-15T12:54:31+00:00

Hi, i need to connect to an IoT central device using a C# application to generate custom telemetry as indicated in a question still unanswered. I experienced that it's not easy at all; the only available examples refer to this code https://github.com/Azure/azure-iot-sdk-csharp that needs to customize; in particolar i need to modify the TemperatureControllerSample.cs file under the directory \azure-iot-sdk-csharp-main\iothub\device\samples\solutions\PnpDeviceSamples\TemperatureController to simulate telemetry data and It's difficult to obtain the IoT Central device hostname required for connection. I noticed that an easy way to obtain the hostname is connecting to IoT Central device using smartphone with the IoT Pnp app (with QR Code in device group) and find the hostname in app logs; in this way, however, json template device is replaced by the one provided in the app and if the template is updated again with the original i obtain unmodeled data: I think this is not a correct way... Is it possible that an EASY way was not foreseen by Microsoft to connect to a device and generate CUSTOM telemetry data as easily as in the IoT Pnp app ?! The only example is the one I indicated or at least I haven't been able to find any other such examples so far. I believe the solution will benefit many developers. Thanks in advance. Guido

Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
362 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,189 questions
0 comments No comments
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 15,241 Reputation points Microsoft Employee
    2024-01-16T22:39:26.49+00:00

    Hi @GuidoL Thank you for connecting with us offline to further investigate this issue. I am sharing more details on this thread to add more context. The code sample provided on a similar Q&A question - How to generate in a single and simple C# project custom telemetry for a IoT Device Template with complex object? should work and help you send telemetry from a single file. However, in our observations offline, we have noticed that even the default code sample C# SDK failed to connect with your devices. Sharing the code below

    using System;
    using Microsoft.Azure.Devices.Client;
    using System.Text;
    using Newtonsoft.Json;
    
    
    namespace MyApp // Note: actual namespace depends on the project name.
    {
        internal class SimpleApp
        {
            private const string ModelId = "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor;1";
    
    
            public static string DeviceId = "<DeviceId";
    
            public static string DeviceSymmetricKey = "<DevicePrimaryKey>";
    
            public static string hostname = "<IoTCentralHostname>";
    
            static async Task Main(string[] args)
            {
                Console.WriteLine("Hello World!");
    
                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>() { "Item1", "Item2", "Item3", "Item4" };
                List<string> Description = new List<string>() { "Des 1", "Des 2", "Des 3", "Des 4", "Des 5", "Des 6", "Des 7" };
                List<string> Location = new List<string>() { "Downingtown", "Midtown", "Redmond", "Hyderabad" };
                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);
                }
    
            }
        }
    }
    

    Please replace the ModelId, DeviceId, DeviceSymmetricKey, hostname in the code with the appropriate values. Note that the easiest way to obtain the hostname is by putting a break point on the line 165 in Program.cs file of TemperatureController project DeviceClient deviceClient = DeviceClient.Create(hostname, authenticationMethod, TransportType.Mqtt, options);

    Update

    The code sample from the above thread is accurate. Code works as expected after updating the nuget packages to latest versions. Below are the versions the packages got updated to.

    • Azure.Core v.1.37.0
    • Microsoft.Azure.Devices.Client v.1.42.2
    • Newtonsoft.Json v.13.0.3

    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.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Dom 1,631 Reputation points Microsoft Employee
    2024-01-15T15:03:25.7433333+00:00

    This example shows you how to connect a simple application to IoT Central. You don't need to know the internal IoT HUb hostname - internally, IoT Central uses DPS: https://video2.skills-academy.com/azure/iot-central/core/tutorial-connect-device For a more in-depth discussion, see: https://video2.skills-academy.com/azure/iot-central/core/overview-iot-central-developer

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.