了解 IoT 中心的标识注册表Understand the identity registry in your IoT hub

每个 IoT 中心都有一个标识注册表,存储允许连接到 IoT 中心的设备和模块的相关信息。Every IoT hub has an identity registry that stores information about the devices and modules permitted to connect to the IoT hub. IoT 中心的标识注册表中必须先有设备或模块的条目,然后该设备或模块才能连接到 IoT 中心。Before a device or module can connect to an IoT hub, there must be an entry for that device or module in the IoT hub's identity registry. 设备或模块还必须基于标识注册表中存储的凭据向 IoT 中心进行身份验证。A device or module must also authenticate with the IoT hub based on credentials stored in the identity registry.

标识注册表中存储的设备或模块 ID 区分大小写。The device or module ID stored in the identity registry is case-sensitive.

概括地说,标识注册表是支持 REST 的设备或模块标识资源集合。At a high level, the identity registry is a REST-capable collection of device or module identity resources. 在此标识注册表中添加条目时,IoT 中心会创建一组每设备资源,如包含未送达云到设备消息的队列。When you add an entry in the identity registry, IoT Hub creates a set of per-device resources such as the queue that contains in-flight cloud-to-device messages.

在需要时执行以下操作时可使用标识注册表:Use the identity registry when you need to:

  • 设置连接到 IoT 中心的设备或模块。Provision devices or modules that connect to your IoT hub.
  • 控制每个设备/每个模块对中心的面向设备或模块的终结点的访问。Control per-device/per-module access to your hub's device or module-facing endpoints.

Note

  • 标识注册表不包含任何应用程序特定的元数据。The identity registry does not contain any application-specific metadata.
  • 模块标识和模块孪生为公共预览版。Module identity and module twin is in public preview. 下面的有关模块标识的功能在公开发布后会受支持。Below feature will be supported on module identity when it's general available.

标识注册表操作Identity registry operations

IoT 中心标识注册表公开以下操作:The IoT Hub identity registry exposes the following operations:

  • 创建设备或模块标识Create device or module identity
  • 更新设备或模块标识Update device or module identity
  • 按 ID 检索设备或模块标识Retrieve device or module identity by ID
  • 删除设备或模块标识Delete device or module identity
  • 最多列出 1000 个标识List up to 1000 identities
  • 将设备标识导出到 Azure Blob 存储Export device identities to Azure blob storage
  • 将设备标识从 Azure Blob 存储导入Import device identities from Azure blob storage

上述所有操作均可以使用 RFC7232 中指定的乐观并发。All these operations can use optimistic concurrency, as specified in RFC7232.

Important

如果要检索 IoT 中心标识注册表中的所有标识,唯一方法是使用导出功能。The only way to retrieve all identities in an IoT hub's identity registry is to use the Export functionality.

IoT 中心标识注册表:An IoT Hub identity registry:

  • 不包含任何应用程序元数据。Does not contain any application metadata.
  • 可以将 deviceIdmoduleId 作为键进行访问,就像字典一样。Can be accessed like a dictionary, by using the deviceId or moduleId as the key.
  • 不支持表达性查询。Does not support expressive queries.

IoT 解决方案通常具有不同的解决方案特定存储,其中包含应用程序特定的元数据。An IoT solution typically has a separate solution-specific store that contains application-specific metadata. 例如,智能建筑物解决方案中的解决方案特定存储将记录部署温度感应器的房间信息。For example, the solution-specific store in a smart building solution would record the room in which a temperature sensor is deployed.

Important

只将标识注册表用于设备管理和预配操作。Only use the identity registry for device management and provisioning operations. 运行时的高吞吐量操作不应依赖于在标识注册表中执行操作。High throughput operations at run time should not depend on performing operations in the identity registry. 例如,在发送命令前先检查设备的连接状态就是不支持的模式。For example, checking the connection state of a device before sending a command is not a supported pattern. 请确保检查限制速率 for the identity registry, and the device heartbeat 模式。Make sure to check the throttling rates for the identity registry, and the device heartbeat pattern.

禁用设备Disable devices

可以通过更新标识注册表中标识的 状态 属性来禁用设备。You can disable devices by updating the status property of an identity in the identity registry. 通常在两种情况下使用此属性:Typically, you use this property in two scenarios:

  • 在预配协调过程中。During a provisioning orchestration process. 有关详细信息,请参阅设备预配For more information, see Device Provisioning.
  • 出于任何原因认为设备遭到入侵或未经授权。If, for any reason, you think a device is compromised or has become unauthorized.

此功能不适用于模块。This feature is not availble for modules.

导入和导出设备标识Import and export device identities

可以使用 IoT 中心资源提供程序终结点上的异步操作,从 IoT 中心的标识注册表批量导出设备标识。Use asynchronous operations on the IoT Hub resource provider endpoint to export device identities in bulk from an IoT hub's identity registry. 导出是长时间运行的作业,它使用客户提供的 blob 容器来保存从标识注册表读取的设备标识数据。Exports are long-running jobs that use a customer-supplied blob container to save device identity data read from the identity registry.

可以使用 IoT 中心资源提供程序终结点上的异步操作,向 IoT 中心的标识注册表批量导入设备标识。Use asynchronous operations on the IoT Hub resource provider endpoint to import device identities in bulk to an IoT hub's identity registry. 导入是长时间运行的作业,它使用客户提供的 blob 容器中的数据,将设备标识数据写入标识注册表。Imports are long-running jobs that use data in a customer-supplied blob container to write device identity data into the identity registry.

有关导入和导出 API 的详细信息,请参阅 IoT 中心资源提供程序 REST API. To learn more about running import and export jobs, see Bulk management of IoT Hub device identitiesFor more information about the import and export APIs, see IoT Hub resource provider REST APIs. To learn more about running import and export jobs, see Bulk management of IoT Hub device identities.

Device ProvisioningDevice provisioning

给定的 IoT 解决方案存储的设备数据取决于该解决方案的特定要求。The device data that a given IoT solution stores depends on the specific requirements of that solution. 但是,解决方案必须至少存储设备标识和身份验证密钥。But, as a minimum, a solution must store device identities and authentication keys. Azure IoT 中心包含标识注册表,可以存储每个设备的值,例如 ID、身份验证密钥和状态代码。Azure IoT Hub includes an identity registry that can store values for each device such as IDs, authentication keys, and status codes. 解决方案可以使用其他 Azure 服务(例如表存储、Blob 存储或 Cosmos DB)来存储任何其他设备数据。A solution can use other Azure services such as table storage, blob storage, or Cosmos DB to store any additional device data.

设备预配是将初始设备数据添加到解决方案中存储中的过程。Device provisioning is the process of adding the initial device data to the stores in your solution. 要使新设备能够连接到中心,必须将设备 ID 和密钥添加到 IoT 中心的标识注册表。To enable a new device to connect to your hub, you must add a device ID and keys to the IoT Hub identity registry. 在预配过程中,可能需要初始化其他解决方案存储中的设备特定数据。As part of the provisioning process, you might need to initialize device-specific data in other solution stores.

检测信号Device heartbeat

IoT 中心标识注册表包含名为 connectionState的字段。The IoT Hub identity registry contains a field called connectionState. 开发和调试期间仅使用 connectionState 字段。Only use the connectionState field during development and debugging. IoT 解决方案不应在运行时查询字段。IoT solutions should not query the field at run time. 例如,不要在发送云到设备的消息或 SMS 之前查询 connectionState 字段以检查设备是否已连接。For example, do not query the connectionState field to check if a device is connected before you send a cloud-to-device message or an SMS.

如果 IoT 解决方案需要知道设备是否已连接,则可实现检测信号模式If your IoT solution needs to know if a device is connected, you can implement the heartbeat pattern. 在检测信号模式下,设备每隔固定时间至少发送一次设备到云的消息(例如,每小时至少一次)。In the heartbeat pattern, the device sends device-to-cloud messages at least once every fixed amount of time (for example, at least once every hour). 因此,即使设备没有任何要发送的数据,仍会发送空的设备到云的消息(通常具有可供识别为检测信号的属性)。Therefore, even if a device does not have any data to send, it still sends an empty device-to-cloud message (usually with a property that identifies it as a heartbeat). 在服务端,该解决方案维护着与每个设备收到的最后一个检测信号的映射。On the service side, the solution maintains a map with the last heartbeat received for each device. 如果解决方案未在预计时间内从设备收到检测信号消息,则它假定设备存在问题。If the solution does not receive a heartbeat message within the expected time from the device, it assumes that there is a problem with the device.

更复杂的实现可包含来自 Azure Monitor and Azure Resource Health 的信息,以便识别尝试连接或进行通信但失败的设备,请查阅使用诊断进行监视指南。A more complex implementation could include the information from Azure Monitor and Azure Resource Health to identify devices that are trying to connect or communicate but failing, check Monitor with diagnostics guide. 实施检测信号模式时,请务必查看 IoT 中心配额与限制When you implement the heartbeat pattern, make sure to check IoT Hub Quotas and Throttles.

Note

如果 IoT 解决方案只使用连接状态来决定是否发送云到设备的消息,并且没有把消息广播到大量设备,则考虑使用更简单的较短到期时间 模式。If an IoT solution uses the connection state solely to determine whether to send cloud-to-device messages, and messages are not broadcast to large sets of devices, consider using the simpler short expiry time pattern. 此模式达到的效果与使用检测信号模式维护设备连接状态注册表达到的效果一样,而且更加有效。This pattern achieves the same result as maintaining a device connection state registry using the heartbeat pattern, while being more efficient. 如果请求消息确认,则 IoT 中心可以通知你哪些设备可以接收消息以及哪些设备不能接收。If you request message acknowledgements, IoT Hub can notify you about which devices are able to receive messages and which are not.

设备和模块生命周期通知Device and module lifecycle notifications

创建或删除标识时,IoT 中心可通过发送生命周期通知来通知 IoT 解决方案。IoT Hub can notify your IoT solution when an identity is created or deleted by sending lifecycle notifications. 为此,IoT 解决方案需要创建一个路由,并将“数据源”设置为等于 DeviceLifecycleEventsModuleLifecycleEventsTo do so, your IoT solution needs to create a route and to set the Data Source equal to DeviceLifecycleEvents or ModuleLifecycleEvents. 默认情况下,不会发送生命周期通知,即无此类路由预先存在。By default, no lifecycle notifications are sent, that is, no such routes pre-exist. 通知消息包括属性和正文。The notification message includes properties, and body.

属性:消息系统属性以 $ 符号作为前缀。Properties: Message system properties are prefixed with the $ symbol.

设备的通知消息:Notification message for device:

NameName ValueValue
$content-type$content-type application/jsonapplication/json
$iothub-enqueuedtime$iothub-enqueuedtime 发送通知的时间Time when the notification was sent
$iothub-message-source$iothub-message-source deviceLifecycleEventsdeviceLifecycleEvents
$content-encoding$content-encoding utf-8utf-8
opTypeopType createDeviceIdentitydeleteDeviceIdentitycreateDeviceIdentity or deleteDeviceIdentity
hubNamehubName IoT 中心的名称Name of IoT Hub
deviceIddeviceId 设备 IDID of the device
operationTimestampoperationTimestamp ISO8601 操作时间戳ISO8601 timestamp of operation
iothub-message-schemaiothub-message-schema deviceLifecycleNotificationdeviceLifecycleNotification

正文:本部分采用 JSON 格式,表示创建的设备标识的孪生。Body: This section is in JSON format and represents the twin of the created device identity. 例如,For example,

{
    "deviceId":"11576-ailn-test-0-67333793211",
    "etag":"AAAAAAAAAAE=",
    "properties": {
        "desired": {
            "$metadata": {
                "$lastUpdated": "2016-02-30T16:24:48.789Z"
            },
            "$version": 1
        },
        "reported": {
            "$metadata": {
                "$lastUpdated": "2016-02-30T16:24:48.789Z"
            },
            "$version": 1
        }
    }
}

模块的通知消息:Notification message for module:

NameName ValueValue
$content-type$content-type application/jsonapplication/json
$iothub-enqueuedtime$iothub-enqueuedtime 发送通知的时间Time when the notification was sent
$iothub-message-source$iothub-message-source moduleLifecycleEventsmoduleLifecycleEvents
$content-encoding$content-encoding utf-8utf-8
opTypeopType createModuleIdentitydeleteModuleIdentitycreateModuleIdentity or deleteModuleIdentity
hubNamehubName IoT 中心的名称Name of IoT Hub
moduleIdmoduleId 模块 的 IDID of the module
operationTimestampoperationTimestamp ISO8601 操作时间戳ISO8601 timestamp of operation
iothub-message-schemaiothub-message-schema moduleLifecycleNotificationmoduleLifecycleNotification

正文:本部分采用 JSON 格式,表示创建的模块孪生的标识。Body: This section is in JSON format and represents the twin of the created module identity. 例如,For example,

{
    "deviceId":"11576-ailn-test-0-67333793211",
    "moduleId":"tempSensor",
    "etag":"AAAAAAAAAAE=",
    "properties": {
        "desired": {
            "$metadata": {
                "$lastUpdated": "2016-02-30T16:24:48.789Z"
            },
            "$version": 1
        },
        "reported": {
            "$metadata": {
                "$lastUpdated": "2016-02-30T16:24:48.789Z"
            },
            "$version": 1
        }
    }
}

设备标识属性Device identity properties

设备识别表示为包含以下属性的 JSON 文档:Device identities are represented as JSON documents with the following properties:

属性Property 选项Options 说明Description
deviceIddeviceId 必需,更新时只读required, read-only on updates ASCII 7 位字母数字字符 + 某些特殊字符(- . + % _ # * ? ! ( ) , = @ $ ')的区分大小写字符串(最长为 128 个字符)。A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters plus certain special characters: - . + % _ # * ? ! ( ) , = @ $ '.
generationIdgenerationId 必需,只读required, read-only IoT 中心生成的区分大小写字符串,最长为 128 个字符。An IoT hub-generated, case-sensitive string up to 128 characters long. 在删除并重新创建设备时,此值用于区分具有相同 deviceId的设备。This value is used to distinguish devices with the same deviceId, when they have been deleted and re-created.
etagetag 必需,只读required, read-only 一个字符串,根据 RFC7232 表示设备标识的弱 ETag。A string representing a weak ETag for the device identity, as per RFC7232.
authauth 可选optional 包含身份验证信息和安全材料的复合对象。A composite object containing authentication information and security materials.
auth.symkeyauth.symkey 可选optional 包含主密钥和辅助密钥的复合对象,以 base64 格式存储。A composite object containing a primary and a secondary key, stored in base64 format.
状态status 必填required 访问指示器。An access indicator. 可以是 EnabledDisabledCan be Enabled or Disabled. 如果是 Enabled,则允许设备连接。If Enabled, the device is allowed to connect. 如果是 Disabled,则此设备无法访问任何面向设备的终结点。If Disabled, this device cannot access any device-facing endpoint.
statusReasonstatusReason 可选optional 128 个字符的字符串,用于存储设备标识状态的原因。A 128 character-long string that stores the reason for the device identity status. 允许所有 UTF-8 字符。All UTF-8 characters are allowed.
statusUpdateTimestatusUpdateTime 只读read-only 临时指示器,显示上次状态更新的日期和时间。A temporal indicator, showing the date and time of the last status update.
connectionStateconnectionState 只读read-only 指示连接状态的字段:ConnectedDisconnectedA field indicating connection status: either Connected or Disconnected. 此字段表示设备连接状态的 IoT 中心视图。This field represents the IoT Hub view of the device connection status. 重要说明:此字段仅应当用于开发/调试目的。Important: This field should be used only for development/debugging purposes. 仅使用 MQTT 或 AMQP 的设备才更新连接状态。The connection state is updated only for devices using MQTT or AMQP. 此外,它基于协议级别的 ping(MQTT ping 或 AMQP ping),并且最多只有 5 分钟的延迟。Also, it is based on protocol-level pings (MQTT pings, or AMQP pings), and it can have a maximum delay of only 5 minutes. 出于这些原因,可能会发生误报,例如将设备报告为已连接,但实际上已断开连接。For these reasons, there can be false positives, such as devices reported as connected but that are disconnected.
connectionStateUpdatedTimeconnectionStateUpdatedTime 只读read-only 临时指示器,显示上次更新连接状态的日期和时间。A temporal indicator, showing the date and last time the connection state was updated.
lastActivityTimelastActivityTime 只读read-only 临时指示器,显示设备上次连接、接收或发送消息的日期和时间。A temporal indicator, showing the date and last time the device connected, received, or sent a message.

Note

连接状态只能表示连接状态的 IoT 中心视图。Connection state can only represent the IoT Hub view of the status of the connection. 根据网络状态和配置,可能会延迟此状态的更新。Updates to this state may be delayed, depending on network conditions and configurations.

Note

目前,设备 SDK 不支持在 deviceId 中使用 +# 字符。Currently the device SDKs do not support using the + and # characters in the deviceId.

模块标识属性Module identity properties

模块识别表示为包含以下属性的 JSON 文档:Module identities are represented as JSON documents with the following properties:

属性Property 选项Options 说明Description
deviceIddeviceId 必需,更新时只读required, read-only on updates ASCII 7 位字母数字字符 + 某些特殊字符(- . + % _ # * ? ! ( ) , = @ $ ')的区分大小写字符串(最长为 128 个字符)。A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters plus certain special characters: - . + % _ # * ? ! ( ) , = @ $ '.
moduleIdmoduleId 必需,更新时只读required, read-only on updates ASCII 7 位字母数字字符 + 某些特殊字符(- . + % _ # * ? ! ( ) , = @ $ ')的区分大小写字符串(最长为 128 个字符)。A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters plus certain special characters: - . + % _ # * ? ! ( ) , = @ $ '.
generationIdgenerationId 必需,只读required, read-only IoT 中心生成的区分大小写字符串,最长为 128 个字符。An IoT hub-generated, case-sensitive string up to 128 characters long. 在删除并重新创建设备时,此值用于区分具有相同 deviceId的设备。This value is used to distinguish devices with the same deviceId, when they have been deleted and re-created.
etagetag 必需,只读required, read-only 一个字符串,根据 RFC7232 表示设备标识的弱 ETag。A string representing a weak ETag for the device identity, as per RFC7232.
authauth 可选optional 包含身份验证信息和安全材料的复合对象。A composite object containing authentication information and security materials.
auth.symkeyauth.symkey 可选optional 包含主密钥和辅助密钥的复合对象,以 base64 格式存储。A composite object containing a primary and a secondary key, stored in base64 format.
状态status 必填required 访问指示器。An access indicator. 可以是 EnabledDisabledCan be Enabled or Disabled. 如果是 Enabled,则允许设备连接。If Enabled, the device is allowed to connect. 如果是 Disabled,则此设备无法访问任何面向设备的终结点。If Disabled, this device cannot access any device-facing endpoint.
statusReasonstatusReason 可选optional 128 个字符的字符串,用于存储设备标识状态的原因。A 128 character-long string that stores the reason for the device identity status. 允许所有 UTF-8 字符。All UTF-8 characters are allowed.
statusUpdateTimestatusUpdateTime 只读read-only 临时指示器,显示上次状态更新的日期和时间。A temporal indicator, showing the date and time of the last status update.
connectionStateconnectionState 只读read-only 指示连接状态的字段:ConnectedDisconnectedA field indicating connection status: either Connected or Disconnected. 此字段表示设备连接状态的 IoT 中心视图。This field represents the IoT Hub view of the device connection status. 重要说明:此字段仅应当用于开发/调试目的。Important: This field should be used only for development/debugging purposes. 仅使用 MQTT 或 AMQP 的设备才更新连接状态。The connection state is updated only for devices using MQTT or AMQP. 此外,它基于协议级别的 ping(MQTT ping 或 AMQP ping),并且最多只有 5 分钟的延迟。Also, it is based on protocol-level pings (MQTT pings, or AMQP pings), and it can have a maximum delay of only 5 minutes. 出于这些原因,可能会发生误报,例如将设备报告为已连接,但实际上已断开连接。For these reasons, there can be false positives, such as devices reported as connected but that are disconnected.
connectionStateUpdatedTimeconnectionStateUpdatedTime 只读read-only 临时指示器,显示上次更新连接状态的日期和时间。A temporal indicator, showing the date and last time the connection state was updated.
lastActivityTimelastActivityTime 只读read-only 临时指示器,显示设备上次连接、接收或发送消息的日期和时间。A temporal indicator, showing the date and last time the device connected, received, or sent a message.

Note

目前,设备 SDK 不支持在 deviceIdmoduleId 中使用 +# 字符。Currently the device SDKs do not support using the + and # characters in the deviceId and moduleId.

其他参考资料Additional reference material

IoT 中心开发人员指南中的其他参考主题包括:Other reference topics in the IoT Hub developer guide include:

  • IoT 中心终结点介绍了每个 IoT 中心针对运行时和管理操作公开的各种终结点。IoT Hub endpoints describes the various endpoints that each IoT hub exposes for run-time and management operations.
  • 限制和配额介绍了适用于 IoT 中心服务的配额和限制行为。Throttling and quotas describes the quotas and throttling behaviors that apply to the IoT Hub service.
  • Azure IoT 设备和服务 SDK 列出了开发与 IoT 中心交互的设备和服务应用时可使用的各种语言 SDK。Azure IoT device and service SDKs lists the various language SDKs you can use when you develop both device and service apps that interact with IoT Hub.
  • IoT 中心查询语言介绍了可用来从 IoT 中心检索设备孪生和作业相关信息的查询语言。IoT Hub query language describes the query language you can use to retrieve information from IoT Hub about your device twins and jobs.
  • IoT 中心 MQTT 支持提供了有关 IoT 中心对 MQTT 协议的支持的详细信息。IoT Hub MQTT support provides more information about IoT Hub support for the MQTT protocol.

后续步骤Next steps

了解如何使用 IoT 中心标识注册表后,可以根据兴趣参阅以下 IoT 中心开发人员指南主题:Now that you have learned how to use the IoT Hub identity registry, you may be interested in the following IoT Hub developer guide topics:

要尝试本文中介绍的一些概念,请参阅以下 IoT 中心教程:To try out some of the concepts described in this article, see the following IoT Hub tutorial:

若要了解如何使用 IoT 中心设备预配服务启用零接触实时预配,请参阅:To explore using the IoT Hub Device Provisioning Service to enable zero-touch, just-in-time provisioning, see: