How to generate in a single and simple C# project custom telemetry for a IoT Device Template with complex object?

GuidoL 310 Reputation points
2023-06-13T16:20:35.44+00:00

Hi,

in accordance with what you suggested in an answer to my question about custom telemetry generation,

i simulate the Data telemetry using a C# SDK.

You suggested that one of the easiest ways to simulate this scenario is by

creating a List of strings that i anticipate the Telemetry data would hold and

iterate the lists to pick a random value before passing the telemetry.

The code is based on the followig Github repository:

https://github.com/Azure/azure-iot-sdk-csharp

Now I need to use the following device template on my IoT Central app to update, using an azure function trigger, some digital twins properties:

{
    "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor;1",
    "@type": "Interface",
    "contents": [
        {
            "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData;1",
            "@type": "Telemetry",
            "displayName": {
                "en": "LibraryItemData"
            },
            "name": "LibraryItemData",
            "schema": {
                "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData:schema;1",
                "@type": "Object",
                "displayName": {
                    "en": "Object"
                },
                "fields": [
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData:schema:ItemId;1",
                        "displayName": {
                            "en": "ItemId"
                        },
                        "name": "ItemId",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData:schema:Description;1",
                        "displayName": {
                            "en": "Description"
                        },
                        "name": "Description",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData:schema:Location;1",
                        "displayName": {
                            "en": "Location"
                        },
                        "name": "Location",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemData:schema:DateTimeValue;1",
                        "displayName": {
                            "en": "DateTimeValue"
                        },
                        "name": "DateTimeValue",
                        "schema": "dateTime"
                    }
                ]
            }
        },
        {
            "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty;1",
            "@type": "Property",
            "displayName": {
                "en": "LibraryItemDataProperty"
            },
            "name": "LibraryItemDataProperty",
            "schema": {
                "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty:schema;1",
                "@type": "Object",
                "displayName": {
                    "en": "Object"
                },
                "fields": [
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty:schema:ItemId;1",
                        "displayName": {
                            "en": "ItemId"
                        },
                        "name": "ItemId",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty:schema:Description;1",
                        "displayName": {
                            "en": "Description"
                        },
                        "name": "Description",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty:schema:Location;1",
                        "displayName": {
                            "en": "Location"
                        },
                        "name": "Location",
                        "schema": "string"
                    },
                    {
                        "@id": "dtmi:digitaltwins:org:archive:download:rfidsmartlibrary:RfidSmartLibraryowl:LibraryItemGateCheckSensor:LibraryItemDataProperty:schema:DateTime;1",
                        "displayName": {
                            "en": "DateTime"
                        },
                        "name": "DateTime",
                        "schema": "dateTime"
                    }
                ]
            },
            "writable": true
        }
    ],
    "displayName": {
        "en": "LibraryItemGateCheckSensor"
    },
    "@context": [
        "dtmi:iotcentral:context;2",
        "dtmi:dtdl:context;2"
    ]
}

Is there a way an easier way to use the Github repository and modified the TemperatureControllerSample.cs file under the directory \azure-iot-sdk-csharp-main\iothub\device\samples\solutions\PnpDeviceSamples\TemperatureController to simulate telemetry data with by not loading all the 59 projects in Visual Studio?

Thanks in advance.

Guido

Azure Digital Twins
Azure Digital Twins
An Azure platform that is used to create digital representations of real-world things, places, business processes, and people.
229 questions
Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
362 questions
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 15,241 Reputation points Microsoft Employee
    2023-06-15T00:38:34.01+00:00

    Hi @GuidoL Greetings! I have looked into the code sample and could extract a simplified version to simulate the same data. Please refer the following code sample

    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);

    Running this code would simulate the data on to IoT Central without any issues. Please refer the following image.

    enter image description here

    Hope this helps. Please let us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes. 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.

2 additional answers

Sort by: Most helpful
  1. Dom 1,631 Reputation points Microsoft Employee
    2023-06-14T07:34:47.6266667+00:00

    This tutorial shows you how to build and run that specific sample from the command line without needing to use Visual Studio: https://video2.skills-academy.com/azure/iot-develop/quickstart-send-telemetry-central?pivots=programming-language-csharp

    You can then use an editor of your choice to edit the code sample.

    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

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.