IoT 中心模块标识和模块孪生 (.NET) 入门Get started with IoT Hub module identity and module twin (.NET)

备注

模块标识和模块孪生类似于 Azure IoT 中心设备标识和设备孪生,但提供更精细的粒度。Module identities and module twins are similar to Azure IoT Hub device identity and device twin, but provide finer granularity. Azure IoT 中心设备标识和设备孪生允许后端应用程序配置设备并提供设备条件的可见性,而模块标识和模块孪生为设备的各个组件提供这些功能。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.

在本教程结束时,会获得两个 .NET 控制台应用:At the end of this tutorial, you have two .NET console apps:

  • CreateIdentitiesCreateIdentities. 此应用创建设备标识、模块标识和相关的安全密钥,以连接设备和模块客户端。This app creates a device identity, a module identity, and associated security key to connect your device and module clients.

  • UpdateModuleTwinReportedPropertiesUpdateModuleTwinReportedProperties. 此应用将更新的模块孪生报告属性发送到 IoT 中心。This app sends updated module twin reported properties to your IoT hub.

备注

有关 Azure IoT SDK 的信息(可以使用这些 SDK 构建可在设备和解决方案后端上运行的应用程序),请参阅 Azure IoT SDKFor 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。Visual Studio.

  • 有效的 Azure 帐户。An active Azure account. (如果没有帐户,只需几分钟即可创建一个试用帐户。)(If you don't have an account, you can create a trial account in just a couple of minutes.)

创建中心Create a hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。 From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。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. 有关详细信息,请参阅管理 Azure 资源管理器资源组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 中心名称:输入中心的名称。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.

    重要

    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

    在 Azure 门户中创建中心

  5. 在完成时选择“下一步: 大小和规模”,以继续创建中心。Select Next: Size and scale to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模

    在此屏幕中可以设置以下值: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. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT Hub in the free tier.

    • IoT 中心单元:每个单位每日允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层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. 大多数中心只需要 4 个分区。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.

    查看用于创建新中心的信息

  7. 选择“创建”以创建新的中心 。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

获取 IoT 中心连接字符串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. 默认情况下,每个 IoT 中心都使用名为 registryReadWrite 的共享访问策略创建,该策略授予此权限。By default, every IoT hub is created with a shared access policy named registryReadWrite that grants this permission.

若要获取 registryReadWrite 策略的 IoT 中心连接字符串,请执行以下步骤:To get the IoT Hub connection string for the registryReadWrite policy, follow these steps:

  1. Azure 门户中,选择“资源组” 。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. 从策略列表中选择“registryReadWrite” 策略。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.

    显示如何检索连接字符串

有关 IoT 中心共享访问策略和权限的详细信息,请参阅访问控制和权限For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

创建模块标识Create a module identity

本部分将创建一个 .NET 控制台应用,用于在中心的标识注册表中创建设备标识和模块标识。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. 有关详细信息,请参阅 IoT 中心开发人员指南的“标识注册表”部分For more information, see the Identity Registry section of the IoT Hub developer guide.

运行此控制台应用时,它会为设备和模块生成唯一的 ID 和密钥。When you run this console app, it generates a unique ID and key for both device and module. 设备和模块在向 IoT 中心发送设备到云的消息时,使用这些值来标识自身。Your device and module use these values to identify themselves when it sends device-to-cloud messages to IoT Hub. ID 区分大小写。The IDs are case-sensitive.

  1. 打开 Visual Studio,选择“新建项目” 。Open Visual Studio, and select Create a new project.

  2. 在“创建新项目”中,选择“控制台应用(.NET Framework)” 。In Create a new project, select Console App (.NET Framework).

  3. 选择“下一步”, 打开“配置新项目”。 Select Next to open Configure your new project. 将项目命名为 CreateIdentities,将解决方案命名为 IoTHubGetStarted 。Name the project CreateIdentities and name the solution IoTHubGetStarted. 确保 .NET Framework 版本为 4.6.1 或更高。Make sure the .NET Framework version is 4.6.1 or later.

    输入 Visual Studio 解决方案的名称和框架

  4. 在 Visual Studio 中,打开“工具” > “NuGet 包管理器” > “管理解决方案的 NuGet 包”。 In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 选择“浏览”按钮 。Select the Browse tab.

  5. 搜索 Microsoft.Azure.DevicesSearch for Microsoft.Azure.Devices. 选择它,然后选择“安装”。 Select it and then select Install.

    安装 Azure IoT 中心 .NET 服务 SDK 当前版本

  6. Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common.Exceptions;
    
  7. 将以下字段添加到 Program 类 。Add the following fields to the Program class. 将占位符值替换为在上一部分为中心创建的 IoT 中心连接字符串。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. 将以下代码添加到 Main 类。Add the following code to the Main class.

    static void Main(string[] args)
    {
        AddDeviceAsync().Wait();
        AddModuleAsync().Wait();
    }
    
  9. 将以下方法添加到 Program 类: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);
    }
    

    AddDeviceAsync 方法会创建 ID 为 myFirstDevice 的设备标识。The AddDeviceAsync method creates a device identity with ID myFirstDevice. 如果该设备 ID 已在标识注册表中,代码就只检索现有的设备信息。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.

    AddModuleAsync 方法在设备 myFirstDevice 下创建 ID 为 myFirstModule 的模块标识。The AddModuleAsync method creates a module identity with ID myFirstModule under device myFirstDevice. 如果该模块 ID 已在标识注册表中,代码就只检索现有的模块信息。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.

    重要

    收集的日志中可能会显示设备 ID 用于客户支持和故障排除,因此,在为日志命名时,请务必避免包含任何敏感信息。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 application, and make a note of the device key and module key.

备注

IoT 中心标识注册表只存储设备和模块标识,以启用对 IoT 中心的安全访问。The IoT Hub identity registry only stores device and module identities to enable secure access to the IoT hub. 标识注册表存储用作安全凭据的设备 ID 和密钥。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. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

使用 .NET 设备 SDK 更新模块孪生Update the module twin using .NET device SDK

在本节中,将在更新模块孪生报告属性的模拟设备上创建 .NET 控制台应用。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. 登录 Azure 门户Sign in to the Azure portal. 导航到中心并选择“IoT 设备”。 Navigate to your hub and select IoT Devices. 找到 myFirstDeviceFind myFirstDevice. 选择 myFirstDevice 将其打开,然后选择 myFirstModule 将其打开。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 门户模块详细信息

  1. 在 Visual Studio 中将新项目添加到解决方案,只需选择“文件” > “新建” > “项目”即可。 In Visual Studio, add a new project to your solution by selecting File > New > Project. 在“创建新项目”中,选择“控制台应用(.NET Framework)”,然后选择“下一步” 。In Create a new project, select Console App (.NET Framework), and select Next.

  2. 将项目命名为“UpdateModuleTwinReportedProperties” 。Name the project UpdateModuleTwinReportedProperties. 对于“解决方案”,请选择“添加到解决方案”。 For Solution, select Add to solution. 确保 .NET Framework 版本为 4.6.1 或更高。Make sure the .NET Framework version is 4.6.1 or later.

    创建 Visual Studio 项目

  3. 选择“创建” 来创建项目。Select Create to create your project.

  4. 在 Visual Studio 中,打开“工具” > “NuGet 包管理器” > “管理解决方案的 NuGet 包”。 In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 选择“浏览”按钮 。Select the Browse tab.

  5. 搜索并选择 Microsoft.Azure.Devices.Client,然后选择“安装”。 Search for and select Microsoft.Azure.Devices.Client, and then select Install.

    安装 Azure IoT 中心 .NET 服务 SDK 当前版本

  6. 在 Program.cs 文件顶部添加以下 using 语句: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. 将以下字段添加到 Program 类 。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. 将以下方法“OnDesiredPropertyChanged”添加到“Program”类 :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. Main 方法中添加以下行: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();
    }
    

    此代码示例演示如何检索模块孪生和借助 AMQP 协议更新报告属性。This code sample shows you how to retrieve the module twin and update reported properties with AMQP protocol. 在公开预览版中,我们仅支持通过 AMQP 进行模块孪生操作。In public preview, we only support AMQP for module twin operations.

  10. 也可将这些语句添加到 Main 方法,以便将事件从模块发送到 IoT 中心。Optionally, you can add these statements to the Main method to send an event to IoT Hub from your module. 将这些行置于 try catch 块下。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. 在 Visual Studio 的“解决方案资源管理器”中,右键单击解决方案并选择“设置启动项目”。 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. F5 启动应用。Press F5 to start the apps.

后续步骤Next steps

若要继续了解 IoT 中心入门知识并浏览其他 IoT 方案,请参阅:To continue getting started with IoT Hub and to explore other IoT scenarios, see: