设备孪生入门 (.NET)Get started with device twins (.NET)

设备孪生是存储设备状态信息(包括元数据、配置和条件)的 JSON 文档。Device twins are JSON documents that store device state information, including metadata, configurations, and conditions. IoT 中心为连接到它的每台设备保留一个设备孪生。IoT Hub persists a device twin for each device that connects to it.


本文介绍的功能仅在 IoT 中心的标准层中可用。The features described in this article are available only in the standard tier of IoT Hub. 有关基本和标准/免费 IoT 中心层的详细信息,请参阅选择合适的 IoT 中心层For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

使用设备孪生可以:Use device twins to:

  • 存储来自解决方案后端的设备元数据。Store device metadata from your solution back end.

  • 通过设备应用报告当前状态信息,例如可用功能和条件(例如,使用的连接方法)。Report current state information such as available capabilities and conditions, for example, the connectivity method used, from your device app.

  • 同步设备应用和后端应用之间长时间运行的工作流的状态(例如固件和配置更新)。Synchronize the state of long-running workflows, such as firmware and configuration updates, between a device app and a back-end app.

  • 查询设备的元数据、配置或状态。Query your device metadata, configuration, or state.

设备孪生旨在执行同步以及查询设备的配置和条件。Device twins are designed for synchronization and for querying device configurations and conditions. 了解设备孪生中提供了有关何时使用设备孪生的详细信息。More information on when to use device twins can be found in Understand device twins.

设备孪生存储在 IoT 中心内,并且包含以下元素:Device twins are stored in an IoT hub and contain the following elements:

  • 标记Tags. 仅可由解决方案后端访问的设备元数据。Device metadata accessible only by the solution back end.

  • 所需属性Desired properties. 可以由解决方案后端修改并可由设备应用观察的 JSON 对象。JSON objects modifiable by the solution back end and observable by the device app.

  • 报告属性Reported properties. 可由设备应用修改并可由解决方案后端读取的 JSON 对象。JSON objects modifiable by the device app and readable by the solution back end.

标记和属性不能包含数组,但可以嵌套对象。Tags and properties cannot contain arrays, but objects can be nested.

下图显示了设备孪生组织:The following illustration shows device twin organization:


此外,解决方案后端可以根据上述所有数据查询设备孪生。Additionally, the solution back end can query device twins based on all the above data. 有关设备孪生的详细信息,请参阅了解设备孪生For more information about device twins, see Understand device twins. 有关查询的详细信息,请参阅 IoT 中心查询语言For more information about querying, see IoT Hub query language.

本教程演示如何:This tutorial shows you how to:

  • 创建将标记添加到设备孪生的后端应用,以及将其连接通道作为设备孪生上的报告属性进行报告的模拟设备应用。Create a back-end app that adds tags to a device twin, and a simulated device app that reports its connectivity channel as a reported property on the device twin.

  • 使用标记上的筛选器和之前创建的属性通过后端应用查询设备。Query devices from your back-end app using filters on the tags and properties previously created.

在本教程中,将创建以下 .NET 控制台应用:In this tutorial, you create these .NET console apps:

  • AddTagsAndQuery。AddTagsAndQuery. 此后端应用添加标记并查询设备孪生。This back-end app adds tags and queries device twins.

  • ReportConnectivity。ReportConnectivity. 此设备应用模拟使用早先创建的设备标识连接到 IoT 中心的设备,并报告其连接状况。This device app simulates a device that connects to your IoT hub with the device identity created earlier, and reports its connectivity condition.


Azure IoT SDK 一文介绍了可用于构建设备和后端应用的 Azure IoT SDK。The article Azure IoT SDKs provides information about the Azure IoT SDKs that you can use to build both device and back-end apps.


  • Visual Studio。Visual Studio.
  • 有效的 Azure 帐户。An active Azure account. (如果没有帐户,只需几分钟即可创建一个试用订阅。)(If you don't have an account, you can create a trial subscription in just a couple of minutes.)
  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本文中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this article uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

创建 IoT 中心Create an IoT 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 门户为新的中心设置大小和规模

    可在此处接受默认设置。You can accept the default settings here. 如果需要,可以修改以下任何字段:If desired, you can modify any of the following fields:

    • 定价和缩放层:选择的层。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 中心设备流的快速入门,请选择免费层。If you are working through a Quickstart for IoT Hub device streams, select 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. 在完成时选择“下一步: 标记”继续到下一屏幕。Select Next: Tags to continue to the next screen.

    标记是名称/值对。Tags are name/value pairs. 可以为多个资源和资源组分配相同的标记,以便对资源进行分类并合并计费。You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. 有关详细信息,请参阅使用标记来组织 Azure 资源for more information, see Use tags to organize your Azure resources.

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

  7. 在完成时选择“下一步: 查看+创建”可查看选择。Select Next: Review + create to review your choices. 你会看到类似于此屏幕的内容,但其中包含创建中心时选择的值。You see something similar to this screen, but with the values you selected when creating the hub.


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

在 IoT 中心内注册新设备Register a new device in the IoT 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.

获取 IoT 中心连接字符串Get the IoT hub connection string

在本文中,将创建一个后端服务,该服务将所需的属性添加到设备孪生,然后查询标识注册表以查找具有已相应更新的报告属性的所有设备。In this article, you create a backend service that adds desired properties to a device twin and then queries the identity registry to find all devices with reported properties that have been updated accordingly. 你的服务需要“服务连接” 权限才能修改设备孪生的所需属性,并且需要“注册表读取” 权限才能查询标识注册表。Your service needs the service connect permission to modify desired properties of a device twin, and it needs the registry read permission to query the identity registry. 没有仅包含这两个权限的默认共享访问策略,因此需要创建一个。There is no default shared access policy that contains only these two permissions, so you need to create one.

若要创建一个共享访问策略以授予“服务连接”和“注册表读取”权限,同时获取该策略的连接字符串,请执行以下步骤: To create a shared access policy that grants service connect and registry read permissions and get a connection string for this 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. 从策略列表上方的顶部菜单中选择“添加” 。From the top menu above the list of policies, select Add.

  4. 在“添加共享访问策略”下,为策略输入一个说明性名称,例如 serviceAndRegistryRead。Under Add a shared access policy, enter a descriptive name for your policy, such as serviceAndRegistryRead. 在“权限”下选择“注册表读取”和“服务连接”,然后选择“创建” 。 Under Permissions, select Registry read and Service connect, and then select Create.


  5. 从策略列表中选择新策略。Select your new policy from the list of policies.

  6. 在“共享访问密钥” 下,选择“连接字符串 - 主密钥” 所对应的“复制”图标并保存该值。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 the service app

在本部分中,将创建一个 .NET 控制台应用(使用 C#),该应用将位置元数据添加到与 myDeviceId 关联的设备孪生。In this section, you create a .NET console app, using C#, that adds location metadata to the device twin associated with myDeviceId. 然后,该应用将选择位于美国的设备来查询存储在 IoT 中心的设备孪生,然后查询报告手机网络连接的设备孪生。It then queries the device twins stored in the IoT hub selecting the devices located in the US, and then the ones that reported a cellular connection.

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

  2. 在“配置新项目”中,将项目命名为 AddTagsAndQuery 。In Configure your new project, name the project AddTagsAndQuery.

    配置 AddTagsAndQuery 项目

  3. 在“解决方案资源管理器”中,右键单击“AddTagsAndQuery”项目,然后选择“管理 NuGet 程序包”。In Solution Explorer, right-click the AddTagsAndQuery project, and then select Manage NuGet Packages.

  4. 选择“浏览”,然后搜索并选择“Microsoft.Azure.Devices”。Select Browse and search for and select Microsoft.Azure.Devices. 选择“安装”。Select Install.

    “NuGet 包管理器”窗口

    此步骤将下载、安装 Azure IoT 服务 SDK NuGet 包及其依赖项并添加对其的引用。This step downloads, installs, and adds a reference to the Azure IoT service SDK NuGet package and its dependencies.

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

    using Microsoft.Azure.Devices;
  6. 将以下字段添加到 Program 类。Add the following fields to the Program class. {iot hub connection string} 替换为在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串。Replace {iot hub connection string} with the IoT Hub connection string that you copied in Get the IoT hub connection string.

    static RegistryManager registryManager;
    static string connectionString = "{iot hub connection string}";
  7. 将以下方法添加到 Program 类:Add the following method to the Program class:

    public static async Task AddTagsAndQuery()
        var twin = await registryManager.GetTwinAsync("myDeviceId");
        var patch =
                tags: {
                    location: {
                        region: 'US',
                        plant: 'Redmond43'
        await registryManager.UpdateTwinAsync(twin.DeviceId, patch, twin.ETag);
        var query = registryManager.CreateQuery(
          "SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'", 100);
        var twinsInRedmond43 = await query.GetNextAsTwinAsync();
        Console.WriteLine("Devices in Redmond43: {0}", 
          string.Join(", ", twinsInRedmond43.Select(t => t.DeviceId)));
        query = registryManager.CreateQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity.type = 'cellular'", 100);
        var twinsInRedmond43UsingCellular = await query.GetNextAsTwinAsync();
        Console.WriteLine("Devices in Redmond43 using cellular network: {0}", 
          string.Join(", ", twinsInRedmond43UsingCellular.Select(t => t.DeviceId)));

    RegistryManager 类公开从该服务与设备孪生交互所需的所有方法。The RegistryManager class exposes all the methods required to interact with device twins from the service. 上面的代码首先初始化 registryManager 对象,并检索 myDeviceId 的设备孪生,最后使用所需位置信息更新其标记。The previous code first initializes the registryManager object, then retrieves the device twin for myDeviceId, and finally updates its tags with the desired location information.

    在更新后,它将执行两个查询:第一个仅选择位于 Redmond43 工厂的设备的设备孪生,第二个将查询细化为仅选择还要通过移动电话网络连接的设备。After updating, it executes two queries: the first selects only the device twins of devices located in the Redmond43 plant, and the second refines the query to select only the devices that are also connected through cellular network.

    上面的代码创建 query 对象时,会指定返回的最大文档数。The previous code, when it creates the query object, specifies a maximum number of returned documents. query 对象包含 HasMoreResults 布尔值属性,可以使用它多次调用 GetNextAsTwinAsync 方法来检索所有结果。The query object contains a HasMoreResults boolean property that you can use to invoke the GetNextAsTwinAsync methods multiple times to retrieve all results. 名为 GetNextAsJson 的方法可用于非设备孪生的结果(例如聚合查询的结果)。A method called GetNextAsJson is available for results that are not device twins, for example, results of aggregation queries.

  8. 最后,在 Main 方法中添加以下行:Finally, add the following lines to the Main method:

    registryManager = RegistryManager.CreateFromConnectionString(connectionString);
    Console.WriteLine("Press Enter to exit.");
  9. 右键单击 AddTagsAndQuery 项目并选择“调试”,选择“启动新实例”来运行此应用程序。Run this application by right-clicking on the AddTagsAndQuery project and selecting Debug, followed by Start new instance. 在查询位于 Redmond43 的所有设备的查询结果中,应该会看到一个设备,而在将结果限制为使用蜂窝网络的设备的查询结果中没有任何设备。You should see one device in the results for the query asking for all devices located in Redmond43 and none for the query that restricts the results to devices that use a cellular network.


在下一部分中,创建的设备应用将报告连接信息,并更改上一部分中查询的结果。In the next section, you create a device app that reports the connectivity information and changes the result of the query in the previous section.

创建设备应用Create the device app

本部分中会创建一个 .NET 控制台应用,该应用以 myDeviceId 连接到中心,然后更新其报告属性,使报告中包含它使用移动电话网络进行连接的信息。In this section, you create a .NET console app that connects to your hub as myDeviceId, and then updates its reported properties to contain the information that it is connected using a cellular network.

  1. 在 Visual Studio 中,选择“文件” > “新建” > “项目”。In Visual Studio, select File > New > Project. 在“创建新项目”中,选择“控制台应用(.NET Framework)”,然后选择“下一步” 。In Create new project, choose Console App (.NET Framework), and then select Next.

  2. 在“配置新项目”中,将项目命名为 ReportConnectivity 。In Configure your new project, name the project ReportConnectivity. 对于“解决方案”,选择“添加到解决方案”,然后选择“创建”。For Solution, choose Add to solution, and then select Create.

  3. 在“解决方案资源管理器”中,右键单击“ReportConnectivity”项目,然后选择“管理 NuGet 程序包” 。In Solution Explorer, right-click the ReportConnectivity project, and then select Manage NuGet Packages.

  4. 选择“浏览”,然后搜索并选择“Microsoft.Azure.Devices.Client”。Select Browse and search for and choose Microsoft.Azure.Devices.Client. 选择“安装”。Select Install.

    此步骤将下载、安装 Azure IoT 设备 SDK NuGet 包及其依赖项并添加对其的引用。This step downloads, installs, and adds a reference to the Azure IoT device SDK NuGet package and its dependencies.

  5. 在 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;
  6. 将以下字段添加到 Program 类。Add the following fields to the Program class. {device connection string} 替换为在在 IoT 中心内注册新设备中记下的设备连接字符串。Replace {device connection string} with the device connection string that you noted in Register a new device in the IoT hub.

    static string DeviceConnectionString = "HostName=<yourIotHubName>.azure-devices.cn;
    static DeviceClient Client = null;
  7. 将以下方法添加到 Program 类:Add the following method to the Program class:

    public static async void InitClient()
            Console.WriteLine("Connecting to hub");
            Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, 
            Console.WriteLine("Retrieving twin");
            await Client.GetTwinAsync();
        catch (Exception ex)
            Console.WriteLine("Error in sample: {0}", ex.Message);

    Client 对象公开从该设备与设备孪生交互所需的所有方法。The Client object exposes all the methods you require to interact with device twins from the device. 代码如上所示,初始化 Client 对象,然后检索 myDeviceId 的设备孪生 。The code shown above initializes the Client object, and then retrieves the device twin for myDeviceId.

  8. 将以下方法添加到 Program 类:Add the following method to the Program class:

    public static async void ReportConnectivity()
            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("Error in sample: {0}", ex.Message);

    上面的代码使用连接信息更新了 myDeviceId 的报告属性。The code above updates the reported property of myDeviceId with the connectivity information.

  9. 最后,在 Main 方法中添加以下行:Finally, add the following lines to the Main method:

    catch (Exception ex)
        Console.WriteLine("Error in sample: {0}", ex.Message);
    Console.WriteLine("Press Enter to exit.");
  10. 在解决方案资源管理器中,右键单击解决方案并选择“设置启动项目”。In Solution Explorer, right-click on your solution, and select Set StartUp Projects.

  11. 在“通用属性” > “启动项目”中,选择“多启动项目”。In Common Properties > Startup Project, select Multiple startup projects. 对于“ReportConnectivity”,选择“启动”作为“操作”。For ReportConnectivity, select Start as the Action. 选择“确定”保存更改。Select OK to save your changes.

  12. 右键单击 ReportConnectivity 项目并选择“调试”,然后选择“启动新实例”来运行此应用 。Run this app by right-clicking the ReportConnectivity project and selecting Debug, then Start new instance. 应该显示应用正在获取孪生信息,然后将连接性作为报告属性发送。You should see the app getting the twin information, and then sending connectivity as a reported property.


    设备报告了其连接信息之后,该信息应显示在两个查询中。After the device reported its connectivity information, it should appear in both queries.

  13. 右键单击“AddTagsAndQuery”项目,然后选择“调试” > “启动新实例”以再次运行查询。Right-click the AddTagsAndQuery project and select Debug > Start new instance to run the queries again. 这一次 myDeviceId 应显示在两个查询结果中。This time, myDeviceId should appear in both query results.


后续步骤Next steps

在本教程中,你已在 Azure 门户中配置了新的 IoT 中心,并在 IoT 中心的标识注册表中创建了设备标识。In this tutorial, you configured a new IoT hub in the Azure portal, and then created a device identity in the IoT hub's identity registry. 已从后端应用以标记形式添加了设备元数据,并编写了模拟的设备应用,用于报告设备孪生中的设备连接信息。You added device metadata as tags from a back-end app, and wrote a simulated device app to report device connectivity information in the device twin. 还学习了如何使用类似于 SQL 的 IoT 中心查询语言查询此信息。You also learned how to query this information using the SQL-like IoT Hub query language.

可以通过以下资源了解详细信息:You can learn more from the following resources: