通过使用事件网格触发操作来响应 IoT 中心事件React to IoT Hub events by using Event Grid to trigger actions

通过将 Azure IoT 中心与 Azure 事件网格进行集成,使你可以向其他服务发送事件通知,并触发下游流程。Azure IoT Hub integrates with Azure Event Grid so that you can send event notifications to other services and trigger downstream processes. 配置商业应用程序来侦听 IoT 中心事件,以便安全可靠地以可缩放方式响应关键事件。Configure your business applications to listen for IoT Hub events so that you can react to critical events in a reliable, scalable, and secure manner. 例如,生成一个应用程序来更新数据库、创建工作票证,并在每当有新的 IoT 设备注册到 IoT 中心时,发送一封电子邮件通知。 For example, build an application that updates a database, creates a work ticket, and delivers an email notification every time a new IoT device is registered to your IoT hub.

Azure 事件网格是一种完全托管的事件路由服务,使用发布-订阅模型。Azure Event Grid is a fully managed event routing service that uses a publish-subscribe model. 事件网格包含对 Azure 服务(如 Azure Functions 和 Azure 逻辑应用)的内置支持,还可使用 Webhook 向非 Azure 服务传递事件警报。Event Grid has built-in support for Azure services like Azure Functions and Azure Logic Apps, and can deliver event alerts to non-Azure services using webhooks. 有关受事件网格支持的事件处理程序的完整列表,请参阅 Azure 事件网格简介For a complete list of the event handlers that Event Grid supports, see An introduction to Azure Event Grid.

Azure 事件网格体系结构

区域可用性Regional availability

事件网格集成适用于支持事件网格的区域中的 IoT 中心。The Event Grid integration is available for IoT hubs located in the regions where Event Grid is supported. 有关区域的最新列表,请参阅 Azure 事件网格简介For the latest list of regions, see An introduction to Azure Event Grid.

事件类型Event types

IoT 中心将发布以下事件类型:IoT Hub publishes the following event types:

事件类型Event type 说明Description
Microsoft.Devices.DeviceCreatedMicrosoft.Devices.DeviceCreated 当设备注册到 IoT 中心时发布。Published when a device is registered to an IoT hub.
Microsoft.Devices.DeviceDeletedMicrosoft.Devices.DeviceDeleted 当设备从 IoT 中心删除时发布。Published when a device is deleted from an IoT hub.
Microsoft.Devices.DeviceConnectedMicrosoft.Devices.DeviceConnected 当设备连接到 IoT 中心时发布。Published when a device is connected to an IoT hub.
Microsoft.Devices.DeviceDisconnectedMicrosoft.Devices.DeviceDisconnected 当设备与 IoT 中心断开连接时发布。Published when a device is disconnected from an IoT hub.
Microsoft.Devices.DeviceTelemetryMicrosoft.Devices.DeviceTelemetry 将设备遥测消息发送到 IoT 中心时发布。Published when a device telemetry message is sent to an IoT hub

使用 Azure 门户或 Azure CLI 配置从每个 IoT 中心发布的事件。Use either the Azure portal or Azure CLI to configure which events to publish from each IoT hub. 例如,请尝试学习教程使用逻辑应用发送关于 Azure IoT 中心事件的电子邮件通知For an example, try the tutorial Send email notifications about Azure IoT Hub events using Logic Apps.

事件架构Event schema

IoT 中心事件包含响应设备生命周期中更改所需的全部信息。IoT Hub events contain all the information you need to respond to changes in your device lifecycle. 可通过检查 eventType 属性是否以“Microsoft.Devices”开头来标识 IoT 中心事件 。You can identify an IoT Hub event by checking that the eventType property starts with Microsoft.Devices. 有关如何使用事件网格事件属性的详细信息,请参阅事件网格事件架构For more information about how to use Event Grid event properties, see the Event Grid event schema.

设备已连接架构Device connected schema

以下示例显示了设备已连接事件的架构:The following example shows the schema of a device connected event:

[{  
  "id": "f6bbf8f4-d365-520d-a878-17bf7238abd8",
  "topic": "/SUBSCRIPTIONS/<subscription ID>/RESOURCEGROUPS/<resource group name>/PROVIDERS/MICROSOFT.DEVICES/IOTHUBS/<hub name>",
  "subject": "devices/LogicAppTestDevice",
  "eventType": "Microsoft.Devices.DeviceConnected",
  "eventTime": "2018-06-02T19:17:44.4383997Z",
  "data": {
      "deviceConnectionStateEventInfo": {
        "sequenceNumber":
          "000000000000000001D4132452F67CE200000002000000000000000000000001"
      },
    "hubName": "egtesthub1",
    "deviceId": "LogicAppTestDevice",
    "moduleId" : "DeviceModuleID",
  }, 
  "dataVersion": "1",
  "metadataVersion": "1"
}]

设备遥测架构Device Telemetry schema

设备遥测消息必须采用有效的 JSON 格式,并且在消息系统属性中将 contentType 设置为 application/json,将 contentEncoding 设置为 UTF-8Device telemetry message must be in a valid JSON format with the contentType set to application/json and contentEncoding set to UTF-8 in the message system properties. 这两个属性都不区分大小写。Both of these properties are case insensitive. 如果未设置内容编码,则 IoT 中心将以 base 64 编码格式写入消息。If the content encoding is not set, then IoT Hub will write the messages in base 64 encoded format.

在通过选择终结点作为事件网格来将设备遥测事件发布到事件网格之前,你可以扩充设备遥测事件。You can enrich device telemetry events before they are published to Event Grid by selecting the endpoint as Event Grid.

以下示例显示了设备遥测事件的架构:The following example shows the schema of a device telemetry event:

[{  
  "id": "9af86784-8d40-fe2g-8b2a-bab65e106785",
  "topic": "/SUBSCRIPTIONS/<subscription ID>/RESOURCEGROUPS/<resource group name>/PROVIDERS/MICROSOFT.DEVICES/IOTHUBS/<hub name>",
  "subject": "devices/LogicAppTestDevice",
  "eventType": "Microsoft.Devices.DeviceTelemetry",
  "eventTime": "2019-01-07T20:58:30.48Z",
  "data": {
      "body": {
          "Weather": {
              "Temperature": 900
            },
            "Location": "CN"
        },
        "properties": {
            "Status": "Active"
        },
        "systemProperties": {
          "iothub-content-type": "application/json",
          "iothub-content-encoding": "utf-8",
          "iothub-connection-device-id": "d1",
          "iothub-connection-auth-method": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}",
          "iothub-connection-auth-generation-id": "123455432199234570",
          "iothub-enqueuedtime": "2019-01-07T20:58:30.48Z",
          "iothub-message-source": "Telemetry"
        }
  },
  "dataVersion": "",
  "metadataVersion": "1"
}]

设备创建架构Device created schema

以下示例显示了设备创建事件的架构:The following example shows the schema of a device created event:

[{
  "id": "56afc886-767b-d359-d59e-0da7877166b2",
  "topic": "/SUBSCRIPTIONS/<subscription ID>/RESOURCEGROUPS/<resource group name>/PROVIDERS/MICROSOFT.DEVICES/IOTHUBS/<hub name>",
  "subject": "devices/LogicAppTestDevice",
  "eventType": "Microsoft.Devices.DeviceCreated",
  "eventTime": "2018-01-02T19:17:44.4383997Z",
  "data": {
    "twin": {
      "deviceId": "LogicAppTestDevice",
      "etag": "AAAAAAAAAAE=",
      "deviceEtag":"null",
      "status": "enabled",
      "statusUpdateTime": "0001-01-01T00:00:00",
      "connectionState": "Disconnected",
      "lastActivityTime": "0001-01-01T00:00:00",
      "cloudToDeviceMessageCount": 0,
      "authenticationType": "sas",
      "x509Thumbprint": {
        "primaryThumbprint": null,
        "secondaryThumbprint": null
      },
      "version": 2,
      "properties": {
        "desired": {
          "$metadata": {
            "$lastUpdated": "2018-01-02T19:17:44.4383997Z"
          },
          "$version": 1
        },
        "reported": {
          "$metadata": {
            "$lastUpdated": "2018-01-02T19:17:44.4383997Z"
          },
          "$version": 1
        }
      }
    },
    "hubName": "egtesthub1",
    "deviceId": "LogicAppTestDevice"
  },
  "dataVersion": "1",
  "metadataVersion": "1"
}]

有关各属性的详细说明,请参阅 IoT 中心的 Azure 事件网格事件架构For a detailed description of each property, see Azure Event Grid event schema for IoT Hub.

筛选事件Filter events

IoT 中心事件订阅可以根据事件类型、数据内容和使用者(即设备名称)来筛选事件。IoT Hub event subscriptions can filter events based on event type, data content and subject, which is the device name.

事件网格启用了基于事件类型、使用者和数据内容的筛选Event Grid enables filtering on event types, subjects and data content. 创建事件网格订阅时,可以选择订阅所选择的 IoT 事件。While creating the Event Grid subscription, you can choose to subscribe to selected IoT events. 事件网格中的使用者筛选器基于“开头为”(前缀)和“结尾为”(后缀)匹配进行筛选 。Subject filters in Event Grid work based on Begins With (prefix) and Ends With (suffix) matches. 该筛选器使用 AND 运算符,以便将含有与前缀和后缀都匹配的使用者的事件传送给订阅方。The filter uses an AND operator, so events with a subject that match both the prefix and suffix are delivered to the subscriber.

IoT 事件使用者使用的格式:The subject of IoT Events uses the format:

devices/{deviceId}

事件网格还允许基于每个事件的属性(包括数据内容)进行筛选。Event Grid also allows for filtering on attributes of each event, including the data content. 这允许你选择基于遥测消息的内容传送哪些事件。This allows you to choose what events are delivered based contents of the telemetry message. 请参阅高级筛选来查看示例。Please see advanced filtering to view examples. 若要对遥测消息正文进行筛选,必须在消息系统属性中将 contentType 设置为 application/json,将 contentEncoding 设置为 UTF-8For filtering on the telemetry message body, you must set the contentType to application/json and contentEncoding to UTF-8 in the message system properties. 这两个属性都不区分大小写。Both of these properties are case insensitive.

对于非遥测事件,例如 DeviceConnected、DeviceDisconnected、DeviceCreated 和 DeviceDeleted,在创建订阅时,可以使用事件网格筛选。For non-telemetry events like DeviceConnected, DeviceDisconnected, DeviceCreated and DeviceDeleted, the Event Grid filtering can be used when creating the subscription. 对于遥测事件,除了在事件网格中进行筛选之外,用户还可以通过消息路由查询基于设备孪生、消息属性和正文进行筛选。For telemetry events, in addition to the filtering in Event Grid, users can also filter on device twins, message properties and body through the message routing query.

通过事件网格订阅遥测事件时,IoT 中心会创建一个默认的消息路由,用于将数据源类型设备消息发送到事件网格。When you subscribe to telemetry events via Event Grid, IoT Hub creates a default message route to send data source type device messages to Event Grid. 有关消息路由的详细信息,请参阅 IoT 中心消息路由For more information about message routing, see IoT Hub message routing. 该路由会在门户的“IoT 中心”>“消息路由”下显示。This route will be visible in the portal under IoT Hub > Message Routing. 不管为遥测事件创建多少个 EG 订阅,都只会创建一个通往事件网格的路由。Only one route to Event Grid is created regardless of the number of EG subscriptions created for telemetry events. 因此,如果需要多个使用不同筛选器的订阅,可以在同一路由的这些查询中使用 OR 运算符。So, if you need several subscriptions with different filters, you can use the OR operator in these queries on the same route. 通过事件网格订阅遥测事件即可控制路由的创建和删除。The creation and deletion of the route is controlled through subscription of telemetry events via Event Grid. 无法使用 IoT 中心消息路由创建或删除通往事件网格的路由。You cannot create or delete a route to Event Grid using IoT Hub Message Routing.

若要在发送遥测数据之前筛选消息,可以更新你的路由查询To filter messages before telemetry data is sent, you can update your routing query. 请注意,只有当消息正文为 JSON 时,才能将路由查询应用于消息正文。Note that routing query can be applied to the message body only if the body is JSON. 还必须在消息系统属性中将 contentType 设置为 application/json,将 contentEncoding 设置为 UTF-8You must also set the contentType to application/json and contentEncoding to UTF-8 in the message system properties.

设备已连接和设备已断开连接事件的限制Limitations for device connected and device disconnected events

若要接收设备已连接和设备已断开连接事件,必须为设备打开 D2C 链路或 C2D 链路。To receive device connected and device disconnected events, you must open the D2C link or C2D link for your device. 如果设备使用的是 MQTT 协议,IoT 中心将保持 C2D 链路打开。If your device is using MQTT protocol, IoT Hub will keep the C2D link open. 对于 AMQP,可以通过调用接收异步 API 来打开 C2D 链路。For AMQP, you can open the C2D link by calling the Receive Async API.

如果正在发送遥测数据,则 D2C 链路是打开的。The D2C link is open if you are sending telemetry.

如果设备连接闪烁,则意味着设备频繁连接和断开连接,我们不会发送每个连接状态,但会发布最后的连接状态,该状态最终是一致的。 If the device connection is flickering, which mean the device connects and disconnects frequently, we will not send every single connection state, but will publish the last connection state, which is eventually consistent. 例如,如果设备一开始一直处于连接状态,然后连接闪烁了几秒钟,接着回到连接状态,For example, if your device has been in the connected state initially, then connectivity flickers for a few seconds, and then it's back in connected state. 则不会发布新的设备连接状态事件(自初始连接状态以后)。No new device connection state events will be published since the initial connection state.

如果 IoT 中心发生服务中断,我们将在服务中断结束后立即发布设备连接状态。In case of an IoT Hub outage, we will publish the device connection state as soon as the outage is over. 如果设备在服务中断期间断开连接,则设备已断开连接事件将在 10 分钟内发布。If the device disconnects during that outage, the device disconnected event will be published within 10 minutes.

使用事件的提示Tips for consuming events

处理 IoT 中心事件的应用程序应遵循以下建议的操作:Applications that handle IoT Hub events should follow these suggested practices:

  • 可以配置多个订阅将事件路由至同一事件处理程序,因此不可假定事件均来自某个特定的源。Multiple subscriptions can be configured to route events to the same event handler, so don't assume that events are from a particular source. 始终通过检查消息主题,保证事件来自预期的 IoT 中心。Always check the message topic to ensure that it comes from the IoT hub that you expect.

  • 请勿假定所接收的事件均为预期的类型。Don't assume that all events you receive are the types that you expect. 在处理消息前,总是先检查 eventType。Always check the eventType before processing the message.

  • 消息可能不按顺序到达,或者延迟达到。Messages can arrive out of order or after a delay. 对于设备已创建或设备已删除事件,请使用 ETag 字段来了解对象的信息是否是最新的。Use the etag field to understand if your information about objects is up-to-date for device created or device deleted events.

后续步骤Next steps