Categories:

Getting Started with Device Twin In Azure IoT Hub (.NET)

In this article, you’re going to see how to create IoT device identity in the IoT Hub’s identity registry and how to add device metadata as tags from the back-end app. Then create a simulated device app to report the device connectivity information in the device twin. Here you can also learn how to query this information using IoT query language.

Please read the previous part of the articles before continuing with this one.

  1. How to Create Azure IoT Hub Using PowerShell
  2. How to Register IoT Device in Azure IoT Hub Using PowerShell
  3. How to Send Telemetry from An IoT Device to The Azure IoT Hub Using C#

What is device twin?

Device twins contains the information IoT device configurations, metadata and conditions. Device twins store device state information in JSON document.

Prerequisites

Before you begin to ensure that you have created Azure IoT Hub and registered IoT device in the IoT Hub. if not ,Here is the article on How To Create Azure IoT Hub Using PowerShell and also, How to Register IoT Device in Azure IoT Hub Using PowerShell.

Get IoT Hub connection string

  • Open the IoT Hub in the Azure Portal. Select resource groups, select the resource group where you created the IoT Hub is located.
  • In the left pane, you can see the Shared access policies. From the top menu select +Add.
  • Enter the access policy name as serviceAndRegistryRead. choose permissions Registry Read and Service connect. Then click Create.
  • Back on the Shared access policy now you can see the newly created. Select copy icon for the Connection string –primary key.

Create the service app to add tags and query the device twins

Here we create the .NET console app using c# that add the location metadata to device twin associated with the registered IoT device. Here we queries the device twins store in the IoT Hub to select devices located in Coimbatore, and then reported a cellular connection.

  • Open Visual Studio -> choose create a new project and select Console App (.NET Core) and click Next.
  • Enter the project name as AddTagsAndQuery, location, solution name and click Create.
  • In Solution Explorer, right click the AddTagsAndQuery project, and then click Manage NuGet package. In the Nuget Package Manager, click the Browse tab and search Microsoft.Azure.Devices, and select Install.
  • Add the following code in the program.cs file.

using System;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.Azure.Devices;

namespace AddTagsAndQuery

{

    class Program

    {

        static RegistryManager registryManager;

        static string connectionString = “<Enter the IoT Hub Connection String>”;

        static void Main(string[] args)

        {

            registryManager = RegistryManager.CreateFromConnectionString(connectionString);

            AddTagsAndQuery().Wait();

            Console.WriteLine(“Press Enter to exit.”);

            Console.ReadLine();

            Console.WriteLine(“Hello World!”);

        }

        public static async Task AddTagsAndQuery()

        {

            var twin = await registryManager.GetTwinAsync(“RPi01”);

            var patch =

                @”{

            tags: {

                location: {

                    region: ‘India’,

                    plant: ‘Coimbatore’

                }

            }

        }”;

            await registryManager.UpdateTwinAsync(twin.DeviceId, patch, twin.ETag);

            var query = registryManager.CreateQuery(

              “SELECT * FROM devices WHERE tags.location.plant = ‘Coimbatore'”, 100);

            var twinsInCoimbatore = await query.GetNextAsTwinAsync();

            Console.WriteLine(“Devices in Coimbatore: {0}”,

              string.Join(“, “, twinsInCoimbatore.Select(t => t.DeviceId)));

            query = registryManager.CreateQuery(“SELECT * FROM devices WHERE tags.location.plant = ‘Coimbatore’ AND properties.reported.connectivity.type = ‘cellular'”, 100);

            var twinsInCoimbatoreUsingCellular = await query.GetNextAsTwinAsync();

            Console.WriteLine(“Devices in Coimbatore using cellular network: {0}”,

              string.Join(“, “, twinsInCoimbatoreUsingCellular.Select(t => t.DeviceId)));

        }

    }

}

  • Here we use Registry Manager class that interact with device twins from the service. It initialize the registryManager object, then retrieves the device twin for my Device Id (RPi01). And it updates the tags to desired location information as Coimbatore.
  • After updating it executes two queries , first select the device twins that device located in Coimbatore. Second refines the query to select the devices that are connected through cellular network.
  • Run the project using F5 function key.
  • You can see the one device that located in Coimbatore plant and none for the query that restricts the results to devices use a cellular network.

Get IoT device connect string from Azure IoT Hub

  • Open your Azure portal and choose your IoT Hub.
  • Click IoT devices In Explorers. You can see the list of devices that are connected to the IoT Hub.
  • Double click the device, copy the connection string (primary key) to use later.

Create the device app to report that is connected using cellular network

Here we create the .NET console app using c# that connect to your IoT Hub as RPi01 (IoT device) and then updates the properties contain information where the IoT device is connected over cellular network

  • Open Visual Studio -> Create a new project and select Console App (.NET Core) and click Next.
  • Enter the project name as ReportConnectivity, location, solution name and click Create.
  • In Solution Explorer, right click the ReportConnectivity project, and then click Manage NuGet package..
  • In the Nuget Package Manager, click the Browse tab and search Microsoft.Azure.Devices.Client , and select Install.
  • Add the following code in the program.cs file. Replace the DeviceConnection value that you copied in the previous section.

using Microsoft.Azure.Devices.Client;

using Microsoft.Azure.Devices.Shared;

using Newtonsoft.Json;

static string DeviceConnectionString =  “Enter the device connection string”;

static DeviceClient Client = null;

  • Add the following method in the Program class. The Client object retrieves the device from the device twins.

public static async void InitClient()

{

    try

    {

        Console.WriteLine(“Connecting to hub”);

        Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString,

          TransportType.Mqtt);

        Console.WriteLine(“Retrieving twin”);

        await Client.GetTwinAsync();

    }

    catch (Exception ex)

    {

        Console.WriteLine();

        Console.WriteLine(“Error in sample: {0}”, ex.Message);

    }

}

  • Add the following method in the Program class. Below code updates the property type is cellular with the connectivity information.

public static async void ReportConnectivity()

{

    try

    {

        Console.WriteLine(“Sending connectivity data as reported property”);

        TwinCollection reportedProperties, connectivity;

        reportedProperties = new TwinCollection();

        connectivity = new TwinCollection();

        connectivity[“type”] = “cellular”;

        reportedProperties[“connectivity”] = connectivity;

        await Client.UpdateReportedPropertiesAsync(reportedProperties);

    }

    catch (Exception ex)

    {

        Console.WriteLine();

        Console.WriteLine(“Error in sample: {0}”, ex.Message);

    }

}

  • Finally, add the below code in the main method.

try

{

    InitClient();

    ReportConnectivity();

}

catch (Exception ex)

{

    Console.WriteLine();

    Console.WriteLine(“Error in sample: {0}”, ex.Message);

}

Console.WriteLine(“Press Enter to exit.”);

Console.ReadLine();

  • Run the project using F5 function key.
  • You can see that code retrieves the twin and sending connectivity data as reported property.
  • Now Run the AddTagsAndQuery app. Now the device RPi01 appears in both the query.

That’s it, I hope you have learned what is device twins and add create device identity in the IoT Hub , add metadata as tags to IoT  device and device app to report the device connectivity information in the device twin. Feel free to fill up the comment box below if you need any further assistance from me.

Sharing is Caring!

Leave a Reply

Your email address will not be published. Required fields are marked *