教程:使用事件网格和逻辑应用发送有关 Azure IoT 中心事件的电子邮件通知Tutorial: Send email notifications about Azure IoT Hub events using Event Grid and Logic Apps

使用 Azure 事件网格可以通过在下游业务应用程序中触发操作,对 IoT 中心内的事件做出反应。Azure Event Grid enables you to react to events in IoT Hub by triggering actions in your downstream business applications.

本文逐步讲解一个使用 IoT 中心和事件网格的示例配置。This article walks through a sample configuration that uses IoT Hub and Event Grid. 在本文末尾,我们将设置一个 Azure 逻辑应用,使其在每次将设备连接到 IoT 中心或与其断开连接时,都会发送一封通知电子邮件。At the end, you have an Azure logic app set up to send a notification email every time a device connects or disconnects to your IoT hub. 事件网格可用于及时通知关键设备断开连接。Event Grid can be used to get timely notification about critical devices disconnecting. 指标和诊断可能需要几分钟(即 20 分钟或更长时间 -- 尽管我们不想给它加数字)才会在日志/警报中显示。Metrics and Diagnostics can take several (i.e. 20 or more -- though we don't want to put a number on it) minutes to show up in logs/alerts. 对于关键基础结构,这可能是不可接受的。That might be unacceptable for critical infrastructure.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

  • Azure 逻辑应用支持的任何电子邮件提供程序(例如 Office 365 Outlook 或 Outlook.com)中的电子邮件帐户。An email account from any email provider that is supported by Azure Logic Apps, such as Office 365 Outlook or Outlook.com. 此电子邮件帐户用于发送事件通知。This email account is used to send the event notifications.

创建 IoT 中心Create an IoT hub

可以使用 Azure CLI 快速创建新的 IoT 中心。You can quickly create a new IoT hub using Azure CLI.

  1. 运行以下命令来创建新资源组:Run the following command to create a new resource group:

    az group create --name {your resource group name} --location chinanorth
    
  2. 运行以下命令创建 IoT 中心:Run the following command to create an IoT hub:

    az iot hub create --name {your iot hub name} --resource-group {your resource group name} --sku S1 
    

创建逻辑应用Create a logic app

接下来创建一个逻辑应用,并添加一个 HTTP 事件网格触发器来处理来自 IoT 中心的请求。Next, create a logic app and add an HTTP event grid trigger that processes requests from IoT hub.

创建逻辑应用资源Create a logic app resource

  1. Azure 门户中,选择“创建资源”,然后在搜索框中键入“逻辑应用”并选择“返回”。In the Azure portal, select Create a resource, then type "logic app" in the search box and select return. 从结果中选择“逻辑应用”。Select Logic App from the results.

    创建逻辑应用

  2. 在下一个屏幕上选择“创建”。On the next screen, select Create.

  3. 为逻辑应用指定一个在订阅中唯一的名称,然后选择 IoT 中心所在的同一订阅、资源组和位置。Give your logic app a name that's unique in your subscription, then select the same subscription, resource group, and location as your IoT hub.

    用于创建逻辑应用的字段

  4. 选择“查看 + 创建”。Select Review + create.

  5. 验证设置,然后选择“创建”。Verify your settings and then select Create.

  6. 创建资源后,选择“转到资源”。Once the resource is created, select Go to resource.

  7. 在“逻辑应用设计器”中,下滑页面查看“模板”。In the Logic Apps Designer, page down to see Templates. 选择“空白逻辑应用”,以便可以从头开始构建逻辑应用。Choose Blank Logic App so that you can build your logic app from scratch.

选择触发器Select a trigger

触发器是启动逻辑应用的特定事件。A trigger is a specific event that starts your logic app. 在本教程中,触发工作流的触发器通过 HTTP 接收请求。For this tutorial, the trigger that sets off the workflow is receiving a request over HTTP.

  1. 在连接器和触发器搜索栏中,键入 HTTPIn the connectors and triggers search bar, type HTTP.

  2. 滚动浏览结果并选择“请求 - 当收到 HTTP 请求时”作为触发器。Scroll through the results and select Request - When an HTTP request is received as the trigger.

    选择 HTTP 请求触发器

  3. 选择“使用示例有效负载生成架构”。Select Use sample payload to generate schema.

    使用示例有效负载

  4. 将“设备已连接事件架构”JSON 粘贴到文本框中,然后选择“完成”:Paste the Device connected event schema JSON into the text box, then select Done:

      [{  
       "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"
     }]
    

    当设备连接到 IoT 中心时发布此事件。This event publishes when a device is connected to an IoT hub.

备注

可能会收到一条弹出通知,其中指出,“请记住要在请求中包含设为 application/json 的内容类型标头”。You may receive a pop-up notification that says, Remember to include a Content-Type header set to application/json in your request. 可以放心忽略此建议,并转到下一部分。You can safely ignore this suggestion, and move on to the next section.

创建操作Create an action

操作是在触发器启动逻辑应用工作流之后发生的任何步骤。Actions are any steps that occur after the trigger starts the logic app workflow. 在本教程中,操作是从电子邮件提供程序发送电子邮件通知。For this tutorial, the action is to send an email notification from your email provider.

  1. 选择“新建步骤”。Select New step. 随即会打开一个窗口,供用户“选择操作”。This opens a window to Choose an action.

  2. 搜索“Outlook”。Search for Outlook.

  3. 根据你的电子邮件提供程序,找到并选择匹配的连接器。Based on your email provider, find and select the matching connector. 本教程使用 Outlook.com。This tutorial uses Outlook.com. 使用其他电子邮件提供程序时执行的步骤类似。The steps for other email providers are similar.

    选择电子邮件提供程序连接器

  4. 选择“发送电子邮件 (V2)”操作。Select the Send an email (V2) action.

  5. 选择“登录”并登录到你的电子邮件帐户。Select Sign in and sign in to your email account. 选择“是”,允许应用访问你的信息。Select Yes to let the app access your info.

  6. 生成电子邮件模板。Build your email template.

    • 收件人:输入接收通知电子邮件的电子邮件地址。To: Enter the email address to receive the notification emails. 对于本教程,请使用你可以访问的电子邮件帐户进行测试。For this tutorial, use an email account that you can access for testing.

    • 使用者:填写主题文本。Subject: Fill in the text for the subject. 单击“主题”文本框时,可以选择要包含的动态内容。When you click on the Subject text box, you can select dynamic content to include. 例如,本教程使用 IoT Hub alert: {eventType}For example, this tutorial uses IoT Hub alert: {eventType}. 如果未看到“动态内容”,请选择“添加动态内容”超链接,该操作可以开启和关闭此超链接。If you can't see Dynamic content, select the Add dynamic content hyperlink -- this toggles it on and off.

    • 正文:编写电子邮件的文本。Body: Write the text for your email. 在选择器工具中选择 JSON 属性,以包含基于事件数据的动态内容。Select JSON properties from the selector tool to include dynamic content based on event data. 如果未看到“动态内容”,请选择“正文”文本框下的“添加动态内容”超链接 。If you can't see the Dynamic content, select the Add dynamic content hyperlink under the Body text box. 如果未看到所需字段,单击“动态内容”屏幕中的“更多”,以包含上一个操作中的字段。If it doesn't show you the fields you want, click more in the Dynamic content screen to include the fields from the previous action.

    电子邮件模板可能如以下示例所示:Your email template may look like this example:

    填写电子邮件信息

  7. 在逻辑应用设计器中选择“保存”。Select Save in the Logic Apps Designer.

复制 HTTP URLCopy the HTTP URL

在退出逻辑应用设计器之前,请复制逻辑应用要侦听的触发器 URL。Before you leave the Logic Apps Designer, copy the URL that your logic apps is listening to for a trigger. 稍后要使用此 URL 来配置事件网格。You use this URL to configure Event Grid.

  1. 单击“当收到 HTTP 请求时”触发器配置框将其展开。Expand the When a HTTP request is received trigger configuration box by clicking on it.

  2. 选择“HTTP POST URL”旁边的复制按钮复制其值。Copy the value of HTTP POST URL by selecting the copy button next to it.

    复制 HTTP POST URL

  3. 保存此 URL,以便在下一部分可以引用它。Save this URL so that you can refer to it in the next section.

为 IoT 中心事件配置订阅Configure subscription for IoT Hub events

本部分将 IoT 中心配置为在发生事件时发布事件。In this section, you configure your IoT Hub to publish events as they occur.

  1. 在 Azure 门户中导航到 IoT 中心。In the Azure portal, navigate to your IoT hub. 为此,可以选择“资源组”,然后选择本教程中的资源组,接着从资源列表中选择 IoT 中心。You can do this by selecting Resource groups, then select the resource group for this tutorial, and then select your IoT hub from the list of resources.

  2. 选择“事件”。Select Events.

    打开事件网格详细信息

  3. 选择“事件订阅”。Select Event subscription.

    创建新的事件订阅

  4. 使用以下值创建事件订阅:Create the event subscription with the following values:

    1. 在“事件订阅详细信息”部分:In the EVENT SUBSCRIPTION DETAILS section:

      1. 为事件订阅提供一个名称。Provide a name for the event subscription.
      2. 对于“事件架构”,请选择“事件网格架构” 。Select Event Grid Schema for Event Schema.
    2. 在“主题详细信息”部分:In the TOPIC DETAILS section:

      1. 确认“主题类型”是否设置为“IoT 中心” 。Confirm that the Topic type is set to IoT Hub.
      2. 确认 IoT 中心的名称是否设置为“源资源”字段的值。Confirm that the name of the IoT hub is set as the value for the Source Resource field.
      3. 输入将创建的“系统主题”的名称。Enter a name for the system topic that will be created for you. 要了解系统主题,请参阅系统主题的概述To learn about system topics, see Overview of system topics.
    3. 在“事件类型”部分:In the EVENT TYPES section:

      1. 选择“筛选到事件类型”下拉列表。Select the Filter to Event Types drop-down.

      2. 取消选择“设备已创建”和“设备已删除”复选框,仅保留选中“连接已设备”和“设备已断开连接”复选框 。Deselect the Device Created and Device Deleted checkboxes, leaving only the Device Connected and Device Disconnected checkboxes selected.

        选择订阅事件类型

    4. 在“终结点详细信息”部分:In the ENDPOINT DETAILS section:

      1. 选择“终结点类型”作为“Web Hook” 。Select Endpoint Type as Web Hook.
      2. 单击“选择终结点”,粘贴从逻辑应用复制的 URL,然后确认选择。Click select an endpoint, paste the URL that you copied from your logic app, and confirm selection.

      选择终结点 URL

      完成后,窗格应如以下示例所示:When you're done, the pane should look like the following example:

      示例事件订阅窗体

  5. 选择“创建”。Select Create.

模拟新设备连接并发送遥测数据Simulate a new device connecting and sending telemetry

使用 Azure CLI 快速模拟设备连接来测试逻辑应用。Test your logic app by quickly simulating a device connection using Azure CLI.

  1. 运行以下命令创建模拟设备标识:Run the following command to create a simulated device identity:

    az iot hub device-identity create --device-id simDevice --hub-name {YourIoTHubName}
    
  2. 运行以下命令以模拟将设备连接到 IoT 中心并发送遥测数据:Run the following command to simulate connecting your device to IoT Hub and sending telemetry:

    az iot device simulate -d simDevice -n {YourIoTHubName}
    
  3. 当模拟设备连接到 IoT 中心时,你将收到一封电子邮件,通知你“DeviceConnected”事件。When the simulated device connects to IoT Hub, you will receive an email notifying you of a "DeviceConnected" event.

  4. 当模拟完成时,你将收到一封电子邮件,通知你“DeviceDisconnected”事件。When the simulation completes, you will receive an email notifying you of a "DeviceDisconnected" event.

    示例警报邮件

清理资源Clean up resources

本教程使用的资源会在 Azure 订阅中产生费用。This tutorial used resources that incur charges on your Azure subscription. 学习完本教程并测试结果后,请禁用或删除不再想要保留的资源。When you're finished trying out the tutorial and testing your results, disable or delete resources that you don't want to keep.

若要删除在本教程中创建的所有资源,请删除资源组。To delete all of the resources created in this tutorial, delete the resource group.

  1. 选择“资源组”,然后选择本教程中创建的资源组。Select Resource groups, then select the resource group you created for this tutorial.

  2. 在“资源组”页上,选择“删除资源组”。On the Resource group pane, select Delete resource group. 系统将提示输入资源组名称,然后你可以将其删除。You are prompted to enter the resource group name, and then you can delete it. 同时会删除其中包含的所有资源。All of the resources contained therein are also removed.

后续步骤Next steps

有关支持的逻辑应用连接器的完整列表,请参阅连接器概述For a complete list of supported Logic App connectors, see the Connectors overview.