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

设备孪生是存储设备状态信息(元数据、配置和条件)的 JSON 文档。Device twins are JSON documents that store device state information (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 only available in the standard tier of IoT hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to 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:

  • 标记,仅可由解决方案后端访问的设备元数据;tags, device metadata accessible only by the solution back end;
  • 所需属性,可以由解决方案后端修改以及由设备应用观察的 JSON 对象;以及desired properties, JSON objects modifiable by the solution back end and observable by the device app; and
  • 报告属性,可由设备应用修改以及由解决方案后端读取的 JSON 对象。reported properties, 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.


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

本教程演示如何: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.

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

  • AddTagsAndQuery.py,这是一个 Python 后端应用,用于添加标记并查询设备孪生。AddTagsAndQuery.py, a Python back-end app, which adds tags and queries device twins.
  • ReportConnectivity.py,这是一个 .Python 应用,用于模拟使用早先创建的设备标识连接到 IoT 中心的设备,并报告其连接状况。ReportConnectivity.py, a Python app, which 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.

若要完成本教程,需要满足以下条件:To complete this tutorial you need the following:


适用于 azure-iothub-service-clientazure-iothub-device-client 的 pip 包目前仅供 Windows OS 使用。The pip packages for azure-iothub-service-client and azure-iothub-device-client are currently available only for Windows OS. 对于 Linux/Mac OS,请参阅准备适用于 Python 的开发环境一文中特定于 Linux 和 Mac OS 的部分。For Linux/Mac OS, please refer to the Linux and Mac OS-specific sections on the Prepare your development environment for Python post.

创建 IoT 中心Create an IoT hub

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

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

  2. 选择“+创建资源”,然后搜索市场,寻找 IoT 中心Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. 选择“IoT 中心”,然后单击“创建”按钮 。Select IoT Hub and click the Create button. 随即显示 IoT 中心创建过程的第一个屏幕。You see the first screen for creating an IoT hub.

    在 Azure 门户中创建中心

    填充字段。Fill in the fields.

    订阅:请选择要用于 IoT 中心的订阅。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. 有关详细信息,请参阅管理 Azure 资源管理器资源组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 中心名称:输入 IoT 中心的名称。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.


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

  4. 单击“下一步: 大小和规模”,以便继续创建 IoT 中心。Click Next: Size and scale to continue creating your IoT hub.

    使用 Azure 门户为新的 IoT 中心设置大小和缩放级别

    在此屏幕上,可以采用默认值,只需在底部单击“查看+创建”即可 。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. 它允许 500 台设备连接到 IoT 中心,并且每天最多传输 8,000 条信息。It allows 500 devices to be connected to the IoT 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. 例如,如果希望 IoT 中心支持 700,000 条消息输入,则选择两个 S1 层单位。For example, if you want the IoT 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 / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数 IoT 中心只需要 4 个分区。Most IoT hubs only need four partitions.

  5. 单击“查看+创建” 可查看选择。Click Review + create to review your choices. 会显示类似于以下的屏幕。You see something similar to this screen.

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

  6. 单击“创建”以创建新的 IoT 中心 。Click Create to create your new IoT hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

检索 IoT 中心的连接字符串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. 单击中心,查看“IoT 中心”窗格,其中包含“设置”等内容。Click on your hub to see the IoT Hub pane with Settings, and so on. 单击“共享访问策略”。Click Shared access policies.

  2. 在“共享访问策略”中,选择 iothubowner 策略。In Shared access policies, select the iothubowner policy.

  3. 在“共享访问密钥”下,复制“连接字符串 -- 主密钥”供以后使用。Under Shared access keys, copy the Connection string -- primary key to be used later.


    有关详细信息,请参阅“IoT 中心开发人员指南”中的访问控制For more information, see Access control in the "IoT Hub developer guide."

在 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. 设备无法连接到 IoT 中心,除非它在标识注册表中具有条目。A device cannot connect to IoT 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

  1. 在 IoT 中心导航菜单中,打开“IoT 设备”,然后单击“添加”,在 IoT 中心注册新设备。In your IoT hub navigation menu, open IoT Devices, then click Add to register a new device in your IoT hub.


  2. 提供新设备的名称(例如 myDeviceId),然后单击“保存”。Provide a name for your new device, such as myDeviceId, and click Save. 此操作会为 IoT 中心创建新设备标识。This action creates a new 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 Connection string---primary key 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 the service app

在本部分中,将创建一个 Python 控制台应用,该应用将位置元数据添加到与 {Device Id} 关联的设备孪生。In this section, you create a Python console app that adds location metadata to the device twin associated with your {Device Id}. 然后,该应用将选择位于 Redmond 的设备来查询存储在 IoT 中心的设备孪生,然后查询报告移动电话网络连接的设备孪生。It then queries the device twins stored in the IoT hub selecting the devices located in Redmond, and then the ones that are reporting a cellular connection.

  1. 打开命令提示符,然后安装用于 Python 的 Azure IoT 中心服务 SDK。Open a command prompt and install the Azure IoT Hub Service SDK for Python. 在安装 SDK 之后关闭命令提示符。Close the command prompt after you install the SDK.

    pip install azure-iothub-service-client
  2. 使用文本编辑器,新建一个 AddTagsAndQuery.py 文件。Using a text editor, create a new AddTagsAndQuery.py file.

  3. 添加以下代码,从服务 SDK 导入所需模块:Add the following code to import the required modules from the service SDK:

    import sys
    import iothub_service_client
    from iothub_service_client import IoTHubRegistryManager, IoTHubRegistryManagerAuthMethod
    from iothub_service_client import IoTHubDeviceTwin, IoTHubError
  4. 添加以下代码,将 [IoTHub Connection String][Device Id] 的占位符替换为在前面的部分中创建的 IoT 中心的连接字符串和设备 ID。Add the following code, replacing the placeholder for [IoTHub Connection String] and [Device Id] with the connection string for the IoT hub and the device id you created in the previous sections.

    CONNECTION_STRING = "[IoTHub Connection String]"
    DEVICE_ID = "[Device Id]"
    UPDATE_JSON = "{\"properties\":{\"desired\":{\"location\":\"Redmond\"}}}"
    UPDATE_JSON_SEARCH = "\"location\":\"Redmond\""
    UPDATE_JSON_CLIENT_SEARCH = "\"connectivity\":\"cellular\""
  5. 将以下代码添加到 AddTagsAndQuery.py 文件:Add the following code to the AddTagsAndQuery.py file:

    def iothub_service_sample_run():
           iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
           iothub_registry_statistics = iothub_registry_manager.get_statistics()
           print ( "Total device count                       : {0}".format(iothub_registry_statistics.totalDeviceCount) )
           print ( "Enabled device count                     : {0}".format(iothub_registry_statistics.enabledDeviceCount) )
           print ( "Disabled device count                    : {0}".format(iothub_registry_statistics.disabledDeviceCount) )
           print ( "" )
           number_of_devices = iothub_registry_statistics.totalDeviceCount
           dev_list = iothub_registry_manager.get_device_list(number_of_devices)
           iothub_twin_method = IoTHubDeviceTwin(CONNECTION_STRING)
           for device in range(0, number_of_devices):
               if dev_list[device].deviceId == DEVICE_ID:
                   twin_info = iothub_twin_method.update_twin(dev_list[device].deviceId, UPDATE_JSON)
           print ( "Devices in Redmond: " )        
           for device in range(0, number_of_devices):
               twin_info = iothub_twin_method.get_twin(dev_list[device].deviceId)
               if twin_info.find(UPDATE_JSON_SEARCH) > -1:
                   print ( dev_list[device].deviceId )
           print ( "" )
           print ( "Devices in Redmond using cellular network: " )
           for device in range(0, number_of_devices):
               twin_info = iothub_twin_method.get_twin(dev_list[device].deviceId)
               if twin_info.find(UPDATE_JSON_SEARCH) > -1:
                   if twin_info.find(UPDATE_JSON_CLIENT_SEARCH) > -1:
                       print ( dev_list[device].deviceId )
       except IoTHubError as iothub_error:
           print ( "Unexpected error {0}".format(iothub_error) )
       except KeyboardInterrupt:
           print ( "IoTHub sample stopped" )

    Registry 对象公开从服务与设备孪生进行交互所需的所有方法。The Registry object exposes all the methods required to interact with device twins from the service. 此代码将首先初始化 Registry 对象,然后更新 deviceId 的设备孪生,最后运行两个查询。The code first initializes the Registry object, then updates the device twin for deviceId, and finally runs two queries. 第一个查询仅选择位于 Redmond43 工厂的设备的设备孪生,第二个查询将查询细化为仅选择还要通过移动电话网络连接的设备。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.

  6. AddTagsAndQuery.py 的末尾添加以下代码来实现 iothub_service_sample_run 函数:Add the following code at the end of AddTagsAndQuery.py to implement the iothub_service_sample_run function:

    if __name__ == '__main__':
        print ( "Starting the IoT Hub Device Twins Python service sample..." )
  7. 使用以下内容运行应用程序:Run the application with:

    python AddTagsAndQuery.py

    在查询位于 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.

    第一个显示 Redmond 中所有设备的查询

在下一部分中,创建的设备应用会报告连接信息,并更改上一部分中查询的结果。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

在本部分中,将创建一个 Python 控制台应用,该应用以你的 {Device Id} 身份连接到中心,然后更新其设备孪生的报告属性,来说明它是使用手机网络进行连接的。In this section, you create a Python console app that connects to your hub as your {Device Id}, and then updates its device twin's reported properties to contain the information that it is connected using a cellular network.

  1. 打开命令提示符,然后安装用于 Python 的 Azure IoT 中心服务 SDK。Open a command prompt and install the Azure IoT Hub Service SDK for Python. 在安装 SDK 之后关闭命令提示符。Close the command prompt after you install the SDK.

    pip install azure-iothub-device-client
  2. 使用文本编辑器,新建一个 ReportConnectivity.py 文件。Using a text editor, create a new ReportConnectivity.py file.

  3. 添加以下代码,从服务 SDK 导入所需模块:Add the following code to import the required modules from the service SDK:

    import time
    import iothub_client
    from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubError
  4. 添加以下代码,将 [IoTHub Device Connection String] 的占位符替换为在前面的部分中创建的 IoT 中心设备的连接字符串。Add the following code, replacing the placeholder for [IoTHub Device Connection String] with the connection string for the IoT hub device you created in the previous sections.

    CONNECTION_STRING = "[IoTHub Device Connection String]"
    # choose HTTP, AMQP, AMQP_WS or MQTT as transport protocol
    PROTOCOL = IoTHubTransportProvider.MQTT
  5. 将以下代码添加到 ReportConnectivity.py 文件以实现设备孪生功能:Add the following code to the ReportConnectivity.py file to implement the device twins functionality:

    def device_twin_callback(update_state, payload, user_context):
        print ( "" )
        print ( "Twin callback called with:" )
        print ( "    updateStatus: %s" % update_state )
        print ( "    payload: %s" % payload )
    def send_reported_state_callback(status_code, user_context):
        print ( "" )
        print ( "Confirmation for reported state called with:" )
        print ( "    status_code: %d" % status_code )
    def iothub_client_init():
        client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
        if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
                device_twin_callback, TWIN_CONTEXT)
        return client
    def iothub_client_sample_run():
            client = iothub_client_init()
            if client.protocol == IoTHubTransportProvider.MQTT:
                print ( "Sending data as reported property..." )
                reported_state = "{\"connectivity\":\"cellular\"}"
                client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
            while True:
                print ( "Press Ctrl-C to exit" )
                status_counter = 0
                while status_counter <= TIMER_COUNT:
                    status = client.get_send_status()
                    status_counter += 1 
        except IoTHubError as iothub_error:
            print ( "Unexpected error %s from IoTHub" % iothub_error )
        except KeyboardInterrupt:
            print ( "IoTHubClient sample stopped" )

    Client 对象公开从该设备与设备孪生交互所需的所有方法。The Client object exposes all the methods you require to interact with device twins from the device. 上面的代码首先初始化 Client 对象,然后检索你的设备的设备孪生,并使用连接信息更新其报告属性。The previous code, after it initializes the Client object, retrieves the device twin for your device and updates its reported property with the connectivity information.

  6. ReportConnectivity.py 的末尾添加以下代码来实现 iothub_client_sample_run 函数:Add the following code at the end of ReportConnectivity.py to implement the iothub_client_sample_run function:

    if __name__ == '__main__':
        print ( "Starting the IoT Hub Device Twins Python client sample..." )
  7. 运行设备应用:Run the device app:

    python ReportConnectivity.py

    应当会看到关于设备孪生已更新的确认。You should see confirmation the device twins were updated.


  8. 现在设备报告了其连接信息,应出现在两个查询中。Now that the device reported its connectivity information, it should appear in both queries. 回过头来再次运行查询:Go back and run the queries again:

    python AddTagsAndQuery.py

    这一次,两个查询结果中应当都会显示你的 {Device ID}This time your {Device ID} 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. 你还学习了如何使用注册表查询此信息。You also learned how to query this information using the registry.

充分利用以下资源:Use the following resources to learn how to: