使用门户和 .NET 设备创建 IoT 中心模块标识和模块孪生入门Get started with IoT Hub module identity and module twin using the portal and .NET device

备注

模块标识和模块孪生类似于 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.

本教程介绍:In this tutorial, you will learn:

  1. 如何在门户中创建模块标识。How to create a module identity in the portal.
  • 如何使用 .NET 设备 SDK 更新设备的模块孪生。How to use a .NET device SDK to update the module twin from your device.

备注

有关 Azure IoT SDK 的信息(可以使用这些 SDK 生成可在设备和解决方案后端上运行的应用程序),请参阅 [Azure IoT SDK][lnk-hub-sdks]。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][lnk-hub-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.

在中心注册新设备Register a new device in the hub

本部分在 IoT 中心的标识注册表中创建设备标识。In this section, you create a device identity in the identity registry in your IoT hub. 除非设备在标识注册表中具有条目,否则设备无法连接到中心。A device cannot connect to a hub unless it has an entry in the identity registry. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see the IoT Hub developer guide.

  1. 在 IoT 中心导航菜单中,打开“IoT 设备” ,然后选择“新建” 以在 IoT 中心中添加设备。In your IoT hub navigation menu, open IoT Devices, then select New to add a device in your IoT hub.

    在门户中创建设备标识

  2. 在“创建设备” 中,为新设备提供名称(例如 myDeviceId),然后选择“保存” 。In Create a device, provide a name for your new device, such as myDeviceId, and select Save. 此操作会为 IoT 中心创建设备标识。This action creates a device identity for your IoT 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.

  3. 创建设备后,在“IoT 设备”窗格的列表中打开该设备 。After the device is created, open the device from the list in the IoT devices pane. 复制主连接字符串以便稍后使用。Copy the Primary Connection String to use later.

    设备连接字符串

备注

IoT 中心标识注册表仅存储用于实现 IoT 中心安全访问的设备标识。The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. 它存储设备 ID 和密钥作为安全凭据,以及启用/禁用标志让你禁用对单个设备的访问。It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. 如果应用程序需要存储其他特定于设备的元数据,则应使用特定于应用程序的存储。If your application needs to store other device-specific metadata, it should use an application-specific store. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

在门户中创建模块标识Create a module identity in the portal

在一个设备标识中,最多可以创建 20 个模块标识。Within one device identity, you can create up to 20 module identities. 若要添加标识,请执行以下步骤:To add an identity, follow these steps:

  1. 对于在上一部分创建的设备,请选择“添加模块标识”,以便创建第一个模块标识。 For the device you created in the previous section, choose Add Module Identity to create your first module identity.

  2. 输入名称“myFirstModule” 。Enter the name myFirstModule. 保存模块标识。Save your module identity.

    添加模块标识

    新的模块标识将出现在屏幕底部。Your new module identity appears at the bottom of the screen. 选择它即可查看模块标识详细信息。Select it to see module identity details.

    查看模块标识详细信息

保存“连接字符串 - 主密钥”。 Save the Connect string - primary key. 可以在下一部分使用它,以便在设备上设置模块。You use it in the next section to you set up your module on the device.

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

你已成功在 IoT 中心内创建模块标识。You've successfully created the module identity in your IoT Hub. 现在尝试从模拟设备与云进行通信。Let's try to communicate to the cloud from your simulated device. 创建模块标识后,在 IoT 中心内隐式创建模块孪生。Once a module identity is created, a module twin is implicitly created in IoT Hub. 在本节中,将在更新模块孪生报告属性的模拟设备上创建 .NET 控制台应用。In this section, you will create a .NET console app on your simulated device that updates the module twin reported properties.

创建 Visual Studio 项目Create a Visual Studio project

若要创建一个应用来更新模块孪生报告属性,请执行以下步骤:To create an app that updates the module twin reported properties, follow these steps:

  1. 在 Visual Studio 中依次选择“创建新项目”、“控制台应用(.NET Framework)”、“下一步”。 In Visual Studio, select Create a new project, then choose Console App (.NET Framework), and select Next.

  2. 在“配置新项目”中, 输入 UpdateModuleTwinReportedProperties 作为“项目名称”。 In Configure your new project, enter UpdateModuleTwinReportedProperties as the Project name. 选择“创建” 继续操作。Select Create to continue.

    配置 Visual Studio 项目

安装最新的 Azure IoT 中心 .NET 设备 SDKInstall the latest Azure IoT Hub .NET device SDK

模块标识和模块孪生为公共预览版。Module identity and module twin is in public preview. 仅在 IoT 中心预发行设备 SDK 中提供它。It's only available in the IoT Hub pre-release device SDKs. 若要安装它,请执行以下步骤:To install it, follow these steps:

  1. 在 Visual Studio 中,打开“工具” > “NuGet 包管理器” > “管理解决方案的 NuGet 包”。 In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

  2. 选择“浏览”,然后选择“包括预发行版” 。Select Browse, and then select Include prerelease. 搜索 Microsoft.Azure.Devices.ClientSearch for Microsoft.Azure.Devices.Client. 选择最新版本并安装。Select the latest version and install.

    安装 Azure IoT 中心 .NET 服务 SDK 预览版

    现在可以访问所有模块功能。Now you have access to all the module features.

获取模块连接字符串Get your module connection string

需要控制台应用的模块连接字符串。You need the module connection string for your console app. 执行以下步骤:Follow these steps:

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

  2. 导航到 IoT 中心并选择“IoT 设备”。 Navigate to your IoT hub and select IoT Devices. 打开 myFirstDevice,可以看到 myFirstModule 已成功创建。Open myFirstDevice and you see that myFirstModule was successfully created.

  3. 在“模块标识”下选择“myFirstModule”。 Select myFirstModule under Module Identities. 在“模块标识详细信息”中复制“连接字符串(主密钥)”。 In Module Identity Details, copy the Connection string (primary key).

    Azure 门户模块详细信息

创建 UpdateModuleTwinReportedProperties 控制台应用Create UpdateModuleTwinReportedProperties console app

若要创建应用,请按以下步骤操作:To create your app, follow these steps:

  1. 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 Newtonsoft.Json;
    
  2. 将以下字段添加到 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;
    
  3. 将以下方法“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);
        }
    
  4. 最后,将 Main方法替换为以下代码:Finally, replace the Main method with the following code:

    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));
    
            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.ReadKey();
        Client.CloseAsync().Wait();
    }
    
    private static void ConnectionStatusChangeHandler(ConnectionStatus status, ConnectionStatusChangeReason reason)
    {
        Console.WriteLine($"Status {status} changed: {reason}");
    }
    

可以通过 F5 生成并运行此应用。You can build and run this app by using F5.

此代码示例演示如何检索模块孪生和借助 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.

后续步骤Next steps

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

  • [通过 .NET 备份和 .NET 设备开始使用 IoT 中心模块标识和模块孪生][lnk-csharp-csharp-getstarted][Get started with IoT Hub module identity and module twin using .NET backup and .NET device][lnk-csharp-csharp-getstarted]
  • IoT Edge 入门Getting started with IoT Edge