首页 > 解决方案 > 如何使用 python IoT Hub Device SDK 从 iot 设备中检索完整的设备孪生

问题描述

我正在用 python 中的 IoT 中心设备 SDK 编写一个 azure iot 设备应用程序。

我在我的应用程序中使用设备孪生状态的所需属性,并通过来自天蓝色的设备孪生更改上的 device_twin_callback() 更新它们。但是,当我重新配置我的设备时(例如在重新启动时),我得到了 DPS 中指定的初始设备孪生状态,而不是 IoT 中心的当前孪生状态。

有没有办法在 python 中使用 IoT 中心设备 SDK 重新配置时检索当前设备孪生状态?

我想避免的一种解决方案是将设备的最后状态保存在文件中。

标签: pythonazureazure-iot-hub

解决方案


有没有办法在 python 中使用 IoT 中心设备 SDK 重新配置时检索当前设备孪生状态?

你的问题不准确。没有其他方法可以检索当前设备孪生状态,只有 REST APIService - Get Twin及其相关的 Python API iothub_twin_method.get_twin

重新配置时设备状态数据中包含的设备孪生仅取决于 的选择Reprovisioning policies,如下所示。

  • 重新配置和迁移数据:此策略是新注册条目的默认设置。当与注册条目关联的设备提交新请求 (1) 时,此策略会采取行动。根据注册条目配置,设备可能会重新分配给另一个 IoT 中心。如果设备正在更改 IoT 中心,则将删除在初始 IoT 中心的设备注册。来自该初始 IoT 中心的更新设备状态信息将迁移到新的 IoT 中心 (2)。在迁移期间,设备的状态将报告为正在分配。

  • 重新配置并重置为初始配置:当与注册条目关联的设备提交新的配置请求 (1) 时,此策略将采取行动。根据注册条目配置,设备可能会重新分配给另一个 IoT 中心。如果设备正在更改 IoT 中心,则将删除在初始 IoT 中心的设备注册。预配服务实例在预配设备时收到的初始配置数据将提供给新的 IoT 中心 (2)。在迁移期间,设备的状态将报告为正在分配。此策略通常用于在不更改 IoT 中心的情况下恢复出厂设置。

  • 从不重新配置:设备永远不会重新分配给不同的集线器。提供此策略是为了管理向后兼容性。

使用 Azure IoT SDK for Python,reprovisioning 策略由参数update_hub_assignment和对象设置migrate_device_dataReprovisionPolicy请参阅下面的说明。

The behavior of the service when a device is re-provisioned to an IoT hub.
All required parameters must be populated in order to send to Azure.
:param update_hub_assignment: Required. When set to true (default), the
 Device Provisioning Service will evaluate the device's IoT Hub assignment
 and update it if necessary for any provisioning requests beyond the first
 from a given device. If set to false, the device will stay assigned to its
 current IoT hub. Default value: True .
:type update_hub_assignment: bool
:param migrate_device_data: Required. When set to true (default), the
 Device Provisioning Service will migrate the device's data (twin, device
 capabilities, and device ID) from one IoT hub to another during an IoT hub
 assignment update. If set to false, the Device Provisioning Service will
 reset the device's data to the initial desired configuration stored in the
 corresponding enrollment list. Default value: True .
:type migrate_device_data: bool

并且该ReprovisionPolicy对象是作为在EnrollmentGrouporIndividualEnrollment对象中初始化的属性。

所以请尝试改变参数的组合update_hub_assignmentmigrate_device_data实现ReprovisionPolicy你的需求。否则,缓存历史数据的解决方法是唯一的解决方案。


推荐阅读