Get started with IoT Hub module identity and module twin using .NET back end and .NET device

Note

Module identities and module twins are similar to Azure IoT Hub device identity and device twin, but provide finer granularity. While Azure IoT Hub device identity and device twin enable the back-end application to configure a device and provides visibility on the device’s conditions, a module identity and module twin provide these capabilities for individual components of a device. On capable devices with multiple components, such as operating system based devices or firmware devices, it allows for isolated configuration and conditions for each component.

At the end of this tutorial, you have two .NET console apps:

  • CreateIdentities, which creates a device identity, a module identity and associated security key to connect your device and module clients.

  • UpdateModuleTwinReportedProperties, which sends updated module twin reported properties to your IoT Hub.

Note

For information about the Azure IoT SDKs that you can use to build both applications to run on devices, and your solution back end, see Azure IoT SDKs.

To complete this tutorial, you need the following:

  • Visual Studio.

  • An active Azure account. (If you don't have an account, you can create a free account in just a couple of minutes.)

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Log in to the Azure portal.

  2. Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. Select IoT Hub and click the Create button. You see the first screen for creating an IoT hub.

    Create a hub in the Azure portal

    Fill in the fields.

    Subscription: Select the subscription to use for your IoT hub.

    Resource Group: You can create a new resource group or use an existing one. To create a new one, click Create new and fill in the name you want to use. To use an existing resource group, click Use existing and select the resource group from the dropdown list. For more information, see Manage Azure Resource Manager resource groups.

    Region: This is the region in which you want your hub to be located. Select the location closest to you from the dropdown list.

    IoT Hub Name: Put in the name for your IoT Hub. This name must be globally unique. If the name you enter is available, a green check mark appears.

    Important

    The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

  4. Click Next: Size and scale to continue creating your IoT hub.

    Set the size and scale for a new IoT hub using the Azure portal

    On this screen, you can take the defaults and just click Review + create at the bottom.

    Pricing and scale tier: You can choose from several tiers depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in the free tier.

    IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the IoT hub to support ingress of 700,000 messages, you choose two S1 tier units.

    For details about the other tier options, see Choosing the right IoT Hub tier.

    Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs only need four partitions.

  5. Click Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new IoT hub

  6. Click Create to create your new IoT hub. Creating the hub takes a few minutes.

Retrieve connection string for IoT hub

After your hub has been created, retrieve the connection string for the hub. This is used to connect devices and applications to your hub.

  1. Click on your hub to see the IoT Hub pane with Settings, and so on. Click Shared access policies.

  2. In Shared access policies, select the iothubowner policy.

  3. Under Shared access keys, copy the Connection string -- primary key to be used later.

    Show how to retrieve the connection string

    For more information, see Access control in the "IoT Hub developer guide."

You have now created your IoT hub, and you have the host name and IoT Hub connection string that you need to complete the rest of this tutorial.

Create a module identity

In this section, you create a .NET console app that creates a device identity and a module identity in the identity registry in your IoT hub. A device or module cannot connect to IoT hub unless it has an entry in the identity registry. For more information, see the Identity Registry section of the IoT Hub developer guide. When you run this console app, it generates a unique ID and key for both device and module. Your device and module use these values to identify itself when it sends device-to-cloud messages to IoT Hub. The IDs are case-sensitive.

  1. Create a Visual Studio project - In Visual Studio, add a Visual C# Windows Classic Desktop project to a new solution by using the Console App (.NET Framework) project template. Make sure the .NET Framework version is 4.6.1 or later. Name the project CreateIdentities and name the solution IoTHubGetStarted.

    Create a visual studio solution

  2. Install Azure IoT Hub .NET service SDK V1.16.0-preview-001 - Module identity and module twin is in public preview. It's only available in the IoT Hub prerelease service SDKs. In Visual Studio, open tools > Nuget package manager > manage Nuget packages for solution. Search Microsoft.Azure.Devices. Make sure you've checked include prerelease check box. Select version 1.16.0-preview-001 and install. Now you have access to all the module features.

    Install Azure IoT Hub .NET service SDK V1.16.0-preview-001

  3. Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common.Exceptions;
    
  4. Add the following fields to the Program class. Replace the placeholder value with the IoT Hub connection string for the hub that you created in the previous section.

    const string connectionString = "<replace_with_iothub_connection_string>";
    const string deviceID = "myFirstDevice";
    const string moduleID = "myFirstModule";
    
  5. Add the following code to the Main class.

    static void Main(string[] args)
    {
        AddDeviceAsync().Wait();
        AddModuleAsync().Wait();
    }
    
  6. Add the following methods to the Program class:

    private static async Task AddDeviceAsync()
    {
       RegistryManager registryManager = 
         RegistryManager.CreateFromConnectionString(connectionString);
       Device device;
    
       try
       {
           device = await registryManager.AddDeviceAsync(new Device(deviceID));
       }
       catch (DeviceAlreadyExistsException)
        {
            device = await registryManager.GetDeviceAsync(deviceID);
        }
    
        Console.WriteLine("Generated device key: {0}", 
          device.Authentication.SymmetricKey.PrimaryKey);
    }
    
    private static async Task AddModuleAsync()
    {
        RegistryManager registryManager = 
          RegistryManager.CreateFromConnectionString(connectionString);
        Module module;
    
        try
        {
            module = 
              await registryManager.AddModuleAsync(new Module(deviceID, moduleID));
        }
        catch (ModuleAlreadyExistsException)
        {
            module = await registryManager.GetModuleAsync(deviceID, moduleID);
        }
    
        Console.WriteLine("Generated module key: {0}", module.Authentication.SymmetricKey.PrimaryKey);
    }
    

    The AddDeviceAsync() method creates a device identity with ID myFirstDevice. (If that device ID already exists in the identity registry, the code simply retrieves the existing device information.) The app then displays the primary key for that identity. You use this key in the simulated device app to connect to your IoT hub.

    The AddModuleAsync() method creates a module identity with ID myFirstModule under device myFirstDevice. (If that module ID already exists in the identity registry, the code simply retrieves the existing module information.) The app then displays the primary key for that identity. You use this key in the simulated module app to connect to your IoT hub.

    Important

    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  7. Run this application, and make a note of the device key and module key.

Note

The IoT Hub identity registry only stores device and module identities to enable secure access to the IoT hub. The identity registry stores device IDs and keys to use as security credentials. The identity registry also stores an enabled/disabled flag for each device that you can use to disable access for that device. If your application needs to store other device-specific metadata, it should use an application-specific store. There is no enabled/disabled flag for module identities. For more information, see IoT Hub developer guide.

Update the module twin using .NET device SDK

In this section, you create a .NET console app on your simulated device that updates the module twin reported properties.

  1. Create a Visual Studio project: In Visual Studio, add a Visual C# Windows Classic Desktop project to the existing solution by using the Console App (.NET Framework) project template. Make sure the .NET Framework version is 4.6.1 or later. Name the project UpdateModuleTwinReportedProperties.

    Create a visual studio project

  2. Install the latest Azure IoT Hub .NET device SDK: Module identity and module twin is in public preview. It's only available in the IoT Hub prerelease device SDKs. In Visual Studio, open tools > Nuget package manager > manage Nuget packages for solution. Search Microsoft.Azure.Devices.Client. Make sure you've checked include prerelease check box. Select the latest version and install. Now you have access to all the module features.

    Install Azure IoT Hub .NET service SDK V1.16.0-preview-005

  3. Get your module connection string -- now if you login to Azure portal. Navigate to your IoT Hub and click IoT Devices. Find myFirstDevice, open it and you see myFirstModule was successfully created. Copy the module connection string. It is needed in the next step.

    Azure portal module detail

  4. Create UpdateModuleTwinReportedProperties console app

    Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Shared;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    

    Add the following fields to the Program class. Replace the placeholder value with the module connection string.

    private const string ModuleConnectionString = 
      "<Your module connection string>";
    private static ModuleClient Client = null;
    static void ConnectionStatusChangeHandler(ConnectionStatus status, 
      ConnectionStatusChangeReason reason)
    {
        Console.WriteLine("Connection Status Changed to {0}; the reason is {1}", 
          status, reason);
    }
    

    Add the following method OnDesiredPropertyChanged to the Program class:

    private static async Task OnDesiredPropertyChanged(TwinCollection desiredProperties, 
      object userContext)
        {
            Console.WriteLine("desired property change:");
            Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));
            Console.WriteLine("Sending current time as reported property");
            TwinCollection reportedProperties = new TwinCollection
            {
                ["DateTimeLastDesiredPropertyChangeReceived"] = DateTime.Now
            };
    
            await Client.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
        }
    

    Finally, add the following lines to the Main method:

    static void Main(string[] args)
    {
        Microsoft.Azure.Devices.Client.TransportType transport = 
          Microsoft.Azure.Devices.Client.TransportType.Amqp;
    
        try
        {
            Client = 
              ModuleClient.CreateFromConnectionString(ModuleConnectionString, transport);
            Client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
            Client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).Wait();
    
            Console.WriteLine("Retrieving twin");
            var twinTask = Client.GetTwinAsync();
            twinTask.Wait();
            var twin = twinTask.Result;
            Console.WriteLine(JsonConvert.SerializeObject(twin.Properties)); 
    
            Console.WriteLine("Sending app start time as reported property");
            TwinCollection reportedProperties = new TwinCollection();
            reportedProperties["DateTimeLastAppLaunch"] = DateTime.Now;
    
            Client.UpdateReportedPropertiesAsync(reportedProperties);
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Error in sample: {0}", ex);
        }
    
        Console.WriteLine("Waiting for Events.  Press enter to exit...");
        Console.ReadLine();
        Client.CloseAsync().Wait();
    }
    

    This code sample shows you how to retrieve the module twin and update reported properties with AMQP protocol. In public preview, we only support AMQP for module twin operations.

  5. In addition to the above Main method, you can add below code block to send event to IoT Hub from your module:

    Byte[] bytes = new Byte[2];
    bytes[0] = 0;
    bytes[1] = 1;
    var sendEventsTask = Client.SendEventAsync(new Message(bytes));
    sendEventsTask.Wait();
    Console.WriteLine("Event sent to IoT Hub.");
    

Run the apps

You are now ready to run the apps. In Visual Studio, in Solution Explorer, right-click your solution, and then click Set StartUp projects. Select Multiple startup projects, and then select Start as the action for the console app. And then press F5 to start the app.

Next steps

To continue getting started with IoT Hub and to explore other IoT scenarios, see: