DEV Community

Valeriia Savenko
Valeriia Savenko

Posted on

IoT Edge module twin reported properties C#

This is a small guide that builds on top of existing IoT edge C# sample. You might have across IoT Edge C# sample. The IoT Edge module that you create in that tutorial filters the temperature data that's generated by your device. It only sends messages upstream if the temperature is above a specified threshold. This type of analysis at the edge is useful for reducing the amount of data that's communicated to and stored in the cloud. 😃

You can control/change the temperature from the cloud using module twins. Module twin's desired and reported properties are used to synchronize module configuration or conditions. Check this out to understand how to use module twins for IoT Hub.

The function OnDesiredPropertiesUpdate() from the sample is invoked when there is a change to the desired properties, however, it does not update the reported properties.

To update the reported properties we will make a few changes to the sample.

Declare ioTHubModuleClient as a global variable to the Program class.

   // Declare ModuleClient 
   private static ModuleClient ioTHubModuleClient = null;

Find the Init function. This function creates and configures a ModuleClient object, which allows the module to connect to the local Azure IoT Edge runtime to send and receive messages. Make the following changes:

   // Open a connection to the Edge runtime
        ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
        await ioTHubModuleClient.OpenAsync();
        Console.WriteLine("IoT Hub module client initialized.");

Navigate to onDesiredPropertiesUpdate method to the Program class and make the following changes to try-catch:

            Console.WriteLine("Desired property change:");

            var reportedProperties = new TwinCollection();

            if (desiredProperties["TemperatureThreshold"]!=null) {

                temperatureThreshold = desiredProperties["TemperatureThreshold"];
                reportedProperties["TemperatureThreshold"] = temperatureThreshold;

            if (reportedProperties.Count > 0)


Here we use ModuleClient.UpdateReportedPropertiesAsync Method to update the repoted properties.

Discussion (0)