Get started with IoT Hub module identity and module twin (.NET)

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 provide 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, module identities and module twins allow for isolated configuration and conditions for each component.

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

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

  • UpdateModuleTwinReportedProperties. This app 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.

Prerequisites

  • 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 a hub

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

  1. Sign in to the Azure portal.

  2. Choose Create a resource, and then enter IoT Hub in the Search the Marketplace field.

  3. Select IoT Hub from the search results, and then select Create.

  4. On the Basics tab, complete the fields as follows:

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

    • Resource Group: Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use. To use an existing resource group, select that resource group. For more information, see Manage Azure Resource Manager resource groups.

    • Region: Select the region in which you want your hub to be located. Select the location closest to you.

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

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    Create a hub in the Azure portal

  5. Select Next: Size and scale to continue creating your hub.

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

    This screen allows you to set the following values:

    • Pricing and scale tier: Your selected 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 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 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 Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most hubs need only four partitions.

  6. For this article, accept the default choices, and then select Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new hub

  7. Select Create to create your new hub. Creating the hub takes a few minutes.

Get the IoT hub connection string

In this article, you create a back-end service that adds a device in the identity registry and then adds a module to that device. Your service requires the registry write permission. By default, every IoT hub is created with a shared access policy named registryReadWrite that grants this permission.

To get the IoT Hub connection string for the registryReadWrite policy, follow these steps:

  1. In the Azure portal, select Resource groups. Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. On the left-side pane of your hub, select Shared access policies.

  3. From the list of policies, select the registryReadWrite policy.

  4. Under Shared access keys, select the copy icon for the Connection string -- primary key and save the value.

    Show how to retrieve the connection string

For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

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 hub. A device or module can't connect to 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 themselves when it sends device-to-cloud messages to IoT Hub. The IDs are case-sensitive.

  1. Open Visual Studio, and select Create a new project.

  2. In Create a new project, select Console App (.NET Framework).

  3. Select Next to open Configure your new project. Name the project CreateIdentities and name the solution IoTHubGetStarted. Make sure the .NET Framework version is 4.6.1 or later.

    Enter name and framework for your Visual Studio solution

  4. In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution. Select the Browse tab.

  5. Search for Microsoft.Azure.Devices. Select it and then select Install.

    Install Azure IoT Hub .NET service SDK current version

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

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common.Exceptions;
    
  7. 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";
    
  8. Add the following code to the Main class.

    static void Main(string[] args)
    {
        AddDeviceAsync().Wait();
        AddModuleAsync().Wait();
    }
    
  9. 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 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 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.

  10. Run this app, 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 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 app 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.

Before you begin, get your module connection string. Sign in to the Azure portal. Navigate to your hub and select IoT Devices. Find myFirstDevice. Select myFirstDevice to open it, and then select myFirstModule to open it. In Module Identity Details, copy the Connection string (primary key) when needed in the following procedure.

Azure portal module detail

  1. In Visual Studio, add a new project to your solution by selecting File > New > Project. In Create a new project, select Console App (.NET Framework), and select Next.

  2. Name the project UpdateModuleTwinReportedProperties. For Solution, select Add to solution. Make sure the .NET Framework version is 4.6.1 or later.

    Create a Visual Studio project

  3. Select Create to create your project.

  4. In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution. Select the Browse tab.

  5. Search for and select Microsoft.Azure.Devices.Client, and then select Install.

    Install Azure IoT Hub .NET service SDK current version

  6. 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;
    
  7. 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);
    }
    
  8. 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);
        }
    
  9. 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.

  10. Optionally, you can add these statements to the Main method to send an event to IoT Hub from your module. Place these lines below the try catch block.

    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 can now run the apps.

  1. In Visual Studio, in Solution Explorer, right-click your solution, and then select Set StartUp projects.

  2. Under Common Properties, select Startup Project.

  3. Select Multiple startup projects, and then select Start as the action for the apps, and OK to accept your changes.

  4. Press F5 to start the apps.

Next steps

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