教程:使用 Azure PowerShell 配置 IoT 中心消息路由Tutorial: Use Azure PowerShell to configure IoT Hub message routing

消息路由能够将遥测数据从 IoT 设备发送到内置的与事件中心兼容的终结点或自定义终结点,例如,Blob 存储、服务总线队列、服务总线主题和事件中心。Message routing enables sending telemetry data from your IoT devices to built-in Event Hub-compatible endpoints or custom endpoints such as blob storage, Service Bus Queues, Service Bus Topics, and Event Hubs. 若要配置自定义消息路由,请创建路由查询来自定义与特定条件匹配的路由。To configure custom message routing, you create routing queries to customize the route that matches a certain condition. 设置完成后,引入的数据将通过 IoT 中心自动路由到终结点。Once set up, the incoming data is automatically routed to the endpoints by the IoT Hub. 如果某个消息不匹配定义的任何路由查询,它将路由到默认终结点。If a message doesn't match any of the defined routing queries, it is routed to the default endpoint.

本教程包括 2 个部分,介绍如何通过 IoT 中心设置和使用这些自定义路由查询。In this 2-part tutorial, you learn how to set up and use these custom routing queries with IoT Hub. 将消息从 IoT 设备路由到多个终结点中的一个,包括 Blob 存储和服务总线队列。You route messages from an IoT device to one of multiple endpoints, including blob storage and a Service Bus queue. 路由到服务总线队列的消息将由逻辑应用拾取,并通过电子邮件发送。Messages to the Service Bus queue are picked up by a Logic App and sent via e-mail. 未定义自定义消息路由的消息将发送到默认终结点,然后由 Azure 流分析拾取,可在 Power BI 中直观查看。Messages that do not have custom message routing defined are sent to the default endpoint, then picked up by Azure Stream Analytics and viewed in a Power BI visualization.

若要完成本教程的第 1 和第 2 部分,请执行以下任务:To complete Parts 1 and 2 of this tutorial, you perform the following tasks:

第 I 部分:创建资源并设置消息路由Part I: Create resources, set up message routing

  • 创建资源 - IoT 中心、存储帐户、服务总线队列和模拟设备。Create the resources -- an IoT hub, a storage account, a Service Bus queue, and a simulated device. 使用 Azure 门户、Azure 资源管理器模板、Azure CLI 或 Azure PowerShell 即可完成此操作。This can be done using the Azure portal, an Azure Resource Manager template, the Azure CLI, or Azure PowerShell.
  • 在 IoT 中心为存储帐户和服务总线队列配置终结点和消息路由。Configure the endpoints and message routes in IoT Hub for the storage account and Service Bus queue.

第 II 部分:将消息发送到中心并查看路由的结果Part II: Send messages to the hub, view routed results

  • 创建一个逻辑应用,该应用将在消息添加到服务总线队列时触发,并发送电子邮件。Create a Logic App that is triggered and sends e-mail when a message is added to the Service Bus queue.
  • 下载并运行应用,该应用模拟 IoT 设备将消息发送到中心,以获得不同的路由选择。Download and run an app that simulates an IoT Device sending messages to the hub for the different routing options.
  • 为发送至默认终结点的数据创建 Power BI 可视化。Create a Power BI visualization for data sent to the default endpoint.
  • 查看结果...View the results ...
  • ...在服务总线队列和电子邮件中。...in the Service Bus queue and e-mails.
  • ...在存储帐户中。...in the storage account.
  • ...在 Power BI 可视化中。...in the Power BI visualization.

先决条件Prerequisites

  • 对于本教程的第 1 部分:For Part 1 of this tutorial:

    • 必须拥有 Azure 订阅。You must have an Azure subscription. 如果没有 Azure 订阅,可以在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • 对于本教程的第 2 部分:For Part 2 of this tutorial:

    • 必须事先完成本教程的第 1 部分,并保留一些可用的资源。You must have completed Part 1 of this tutorial, and have the resources still available.
    • 安装 Visual StudioInstall Visual Studio.
    • 有权访问用于分析默认终结点的流分析的 Power BI 帐户。Have access to a Power BI account to analyze the default endpoint's stream analytics. 免费试用 Power BI。)(Try Power BI for free.)
    • 提供一个用于发送通知电子邮件的 Office 365 帐户。Have an Office 365 account for sending notification e-mails.

创建基础资源Create base resources

在配置消息路由之前,需创建 IoT 中心、存储帐户和服务总线队列。Before you can configure the message routing, you need to create an IoT hub, a storage account, and a Service Bus queue. 可以参阅适用于本教程第 1 部分的四篇文章中的一篇来创建这些资源:Azure门户、Azure 资源管理器模板、Azure CLI 或 Azure PowerShell。These resources can be created using one of the four articles that are available for Part 1 of this tutorial: the Azure portal, an Azure Resource Manager template, the Azure CLI, or Azure PowerShell.

为所有资源使用相同的资源组和位置。Use the same resource group and location for all of the resources. 在本教程结束后,可以通过删除资源组一次性删除所有资源。Then at the end, you can remove all of the resources in one step by deleting the resource group.

下面是将在以下部分中执行的步骤摘要:Below is a summary of the steps to be performed in the following sections:

  1. 创建资源组Create a resource group.

  2. 在 S1 层级中创建 IoT 中心。Create an IoT hub in the S1 tier. 将使用者组添加到 IoT 中心。Add a consumer group to your IoT hub. 检索数据时,Azure 流分析使用使用者组。The consumer group is used by the Azure Stream Analytics when retrieving data.

    备注

    必须使用付费层中的 IoT 中心来完成本教程。You must use an Iot hub in a paid tier to complete this tutorial. 免费层只允许设置一个终结点,但本教程需要多个终结点。The free tier only allows you to set up one endpoint, and this tutorial requires multiple endpoints.

  3. 使用 Standard_LRS 副本创建标准 V1 存储帐户。Create a standard V1 storage account with Standard_LRS replication.

  4. 创建服务总线命名空间和队列。Create a Service Bus namespace and queue.

  5. 为发送消息到中心的模拟设备创建设备标识。Create a device identity for the simulated device that sends messages to your hub. 保存测试阶段的密钥。Save the key for the testing phase. (如果创建资源管理器模板,则会在部署模板后执行此操作。)(If creating a Resource Manager template, this is done after deploying the template.)

下载脚本(可选)Download the script (optional)

在本教程的第二部分,我们将下载并运行一个 Visual Studio 应用程序,以将消息发送到 IoT 中心。For the second part of this tutorial, you download and run a Visual Studio application to send messages to the IoT Hub. 下载内容的某个文件夹中包含 Azure 资源管理器模板和参数文件,以及 Azure CLI 和 PowerShell 脚本。There is a folder in the download that contains the Azure Resource Manager template and parameters file, as well as the Azure CLI and PowerShell scripts.

若要查看已完成的脚本,请下载 Azure IoT C# 示例If you want to view the finished script, download the Azure IoT C# Samples. 解压缩 master.zip 文件。Unzip the master.zip file. Azure CLI 脚本位于 /iot-hub/Tutorials/Routing/SimulatedDevice/resources/ 中,其文件名为 iothub_routing_psh.ps1The Azure CLI script is in /iot-hub/Tutorials/Routing/SimulatedDevice/resources/ as iothub_routing_psh.ps1.

创建资源Create your resources

首先使用 PowerShell 创建资源。Start by creating the resources with PowerShell.

使用 PowerShell 创建基本资源Use PowerShell to create your base resources

复制并粘贴以下脚本,然后按 Enter。Copy and paste the script below and press Enter. 系统每次运行脚本中的一行。It runs the script one line at a time. 该脚本的第一节将创建本教程所需的基本资源,包括存储帐户、IoT 中心、服务总线命名空间和服务总线队列。This first section of the script will create the base resources for this tutorial, including the storage account, IoT Hub, Service Bus Namespace, and Service Bus queue. 在学习本教程的过程中,请复制并粘贴每个脚本块,以运行该块。As you go through the tutorial, copy each block of script and paste it to run.

有几个资源名称必须全局唯一,例如 IoT 中心名称和存储帐户名称。There are several resource names that must be globally unique, such as the IoT Hub name and the storage account name. 为方便进行标识,这些资源名称的后面追加了名为 randomValue 的随机字母数字值。To make this easier, those resource names are appended with a random alphanumeric value called randomValue. randomValue 在脚本的顶部生成一次,并根据需要追加到整个脚本中的资源名称。The randomValue is generated once at the top of the script and appended to the resource names as needed throughout the script. 如果不想要使用随机后缀,可将其设置为空字符串或特定值。If you don't want it to be random, you can set it to an empty string or to a specific value.

重要

路由脚本也会使用初始脚本中设置的变量,因此,请在同一会话中运行所有脚本。The variables set in the initial script are also used by the routing script, so run all of the script in the same session. 如果打开新的会话来运行用于设置路由的脚本,则多个变量将会缺少值。If you open a new session to run the script for setting up the routing, several of the variables will be missing values.

# This command retrieves the subscription id of the current Azure account.
# This field is used when setting up the routing queries.
$subscriptionID = (Get-AzContext).Subscription.Id

# Concatenate this number onto the resources that have to be globally unique.
# You can set this to "" or to a specific value if you don't want it to be random.
# This retrieves the first 6 digits of a random value.
$randomValue = "$(Get-Random)".Substring(0,6)

# Set the values for the resource names that don't have to be globally unique.
$location = "China East"
$resourceGroup = "ContosoResources"
$iotHubConsumerGroup = "ContosoConsumers"
$containerName = "contosoresults"

# Create the resource group to be used 
#   for all resources for this tutorial.
New-AzResourceGroup -Name $resourceGroup -Location $location

# The IoT hub name must be globally unique, 
#   so add a random value to the end.
$iotHubName = "ContosoTestHub" + $randomValue
Write-Host "IoT hub name is " $iotHubName

# Create the IoT hub.
New-AzIotHub -ResourceGroupName $resourceGroup `
    -Name $iotHubName `
    -SkuName "S1" `
    -Location $location `
    -Units 1 

# Add a consumer group to the IoT hub for the 'events' endpoint.
Add-AzIotHubEventHubConsumerGroup -ResourceGroupName $resourceGroup `
  -Name $iotHubName `
  -EventHubConsumerGroupName $iotHubConsumerGroup `
  -EventHubEndpointName "events"

# The storage account name must be globally unique, so add a random value to the end.
$storageAccountName = "contosostorage" + $randomValue
Write-Host "storage account name is " $storageAccountName

# Create the storage account to be used as a routing destination.
# Save the context for the storage account 
#   to be used when creating a container.
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup `
    -Name $storageAccountName `
    -Location $location `
    -SkuName Standard_LRS `
    -Kind Storage
# Retrieve the connection string from the context. 
$storageConnectionString = $storageAccount.Context.ConnectionString
Write-Host "storage connection string = " $storageConnectionString 

# Create the container in the storage account.
New-AzStorageContainer -Name $containerName `
    -Context $storageAccount.Context

# The Service Bus namespace must be globally unique,
#   so add a random value to the end.
$serviceBusNamespace = "ContosoSBNamespace" + $randomValue
Write-Host "Service Bus namespace is " $serviceBusNamespace

# Create the Service Bus namespace.
New-AzServiceBusNamespace -ResourceGroupName $resourceGroup `
    -Location $location `
    -Name $serviceBusNamespace 

# The Service Bus queue name must be globally unique,
#  so add a random value to the end.
$serviceBusQueueName  = "ContosoSBQueue" + $randomValue
Write-Host "Service Bus queue name is " $serviceBusQueueName 

# Create the Service Bus queue to be used as a routing destination.
New-AzServiceBusQueue -ResourceGroupName $resourceGroup `
    -Namespace $serviceBusNamespace `
    -Name $serviceBusQueueName  `
    -EnablePartitioning $False 

创建模拟设备Create a simulated device

接下来,创建设备标识并保存其密钥供之后使用。Next, create a device identity and save its key for later use. 此设备标识由模拟应用程序用来发送消息到 IoT 中心。This device identity is used by the simulation application to send messages to the IoT hub. 此功能在 PowerShell 中不可用,在使用 Azure 资源管理器模板时也不可用。This capability is not available in PowerShell or when using an Azure Resource Manager template. 以下步骤介绍如何使用 Azure 门户创建模拟设备。The following steps tell you how to create the simulated device using the Azure portal.

  1. 打开 Azure 门户并登录到 Azure 帐户。Open the Azure portal and log into your Azure account.

  2. 选择“资源组”,然后选择你的资源组 。Select Resource groups and then choose your resource group. 本教程使用 ContosoResources 。This tutorial uses ContosoResources.

  3. 在资源列表中,选择 IoT 中心。In the list of resources, select your IoT hub. 本教程使用 ContosoTestHub 。This tutorial uses ContosoTestHub. 从中心窗格选择“IoT 设备” 。Select IoT Devices from the Hub pane.

  4. 选择“+ 添加” 。Select + Add. 在添加设备窗格中,填写设备 ID。On the Add Device pane, fill in the device ID. 本教程使用 Contoso-Test-Device 。This tutorial uses Contoso-Test-Device. 将密钥留空,勾选“自动生成密钥” 。Leave the keys empty, and check Auto Generate Keys. 确保已启用“将设备连接到 IoT 中心” 。Make sure Connect device to IoT hub is enabled. 选择“保存” 。Select Save.

    “添加设备”屏幕

  5. 创建设备后,即可选择它来查看生成的密钥。Now that it's been created, select the device to see the generated keys. 选择主密钥上的“复制”图标,将其保存在某个位置(如记事本)供本教程的测试阶段使用。Select the Copy icon on the Primary key and save it somewhere such as Notepad for the testing phase of this tutorial.

    设备详细信息(包括密钥)

设置基本资源后,可以配置消息路由。Now that the base resources are set up, you can configure the message routing.

设置消息路由Set up message routing

根据模拟设备附加到消息的属性将消息路由到不同资源。You are going to route messages to different resources based on properties attached to the message by the simulated device. 未自定义路由的消息将发送到默认终结点(消息/事件)。Messages that are not custom routed are sent to the default endpoint (messages/events). 在下一教程中,我们会将消息发送到 IoT 中心,看其如何路由到不同的目标。In the next tutorial, you send messages to the IoT Hub and see them routed to the different destinations.

ValueValue 结果Result
级别=“storage”level="storage" 写入到 Azure 存储。Write to Azure Storage.
级别=“critical”level="critical" 写入服务总线队列。Write to a Service Bus queue. 逻辑应用从队列检索消息并使用 Office 365 通过电子邮件发送该消息。A Logic App retrieves the message from the queue and uses Office 365 to e-mail the message.
默认值default 使用 Power BI 显示此数据。Display this data using Power BI.

第一步是设置终结点,以便将数据路由到其中。The first step is to set up the endpoint to which the data will be routed. 第二步是设置使用该终结点的消息路由。The second step is to set up the message route that uses that endpoint. 设置路由后,即可在门户中查看终结点和消息路由。After setting up the routing, you can view the endpoints and message routes in the portal.

若要创建路由终结点,请使用 Add-AzIotHubRoutingEndpointTo create a routing endpoint, use Add-AzIotHubRoutingEndpoint. 若要创建终结点的消息路由,请使用 Add-AzIotHubRouteTo create the messaging route for the endpoint, use Add-AzIotHubRoute.

路由到存储帐户Route to a storage account

首先设置存储帐户的终结点,然后创建消息路由。First, set up the endpoint for the storage account, then create the message route.

备注

可以将数据以 Apache Avro 格式(默认)或 JSON 格式(预览版)写入 Blob 存储。The data can be written to blob storage in either the Apache Avro format, which is the default, or JSON (preview).

JSON 格式编码的功能现处于预览版状态,IoT 中心可在任意区域使用(美国东部、美国西部和欧洲西部除外)。The capability to encode JSON format is in preview in all regions in which IoT Hub is available, except East US, West US and West Europe. 编码格式只能在配置 Blob 存储终结点时设置。The encoding format can be only set at the time the blob storage endpoint is configured. 不能更改已设置的终结点的格式。The format cannot be changed for an endpoint that has already been set up. 使用 JSON 编码时,必须在消息系统属性中将 contentType 设置为 JSON,将 contentEncoding 设置为 UTF-8。When using JSON encoding, you must set the contentType to JSON and the contentEncoding to UTF-8 in the message system properties.

若要更详细地了解如何使用 Blob 存储终结点,请参阅有关如何路由到存储的指南For more detailed information about using a blob storage endpoint, please see guidance on routing to storage.

以下是脚本使用的变量,必须进行设置:These are the variables used by the script that must be set:

resourceGroup:此字段会在两个位置出现 - 请将两者设置为你的资源组。resourceGroup: There are two occurrences of this field -- set both of them to your resource group.

name:此字段是要应用路由的 IoT 中心的名称。name: This field is the name of the IoT Hub to which the routing will apply.

endpointName:此字段是用于标识终结点的名称。endpointName: This field is the name identifying the endpoint.

endpointType:此字段是终结点的类型。endpointType: This field is the type of endpoint. 此值必须设置为 azurestoragecontainereventhubservicebusqueueservicebustopicThis value must be set to azurestoragecontainer, eventhub, servicebusqueue, or servicebustopic. 在本文中,请将其设置为 azurestoragecontainerFor your purposes here, set it to azurestoragecontainer.

subscriptionID:此字段设置为你的 Azure 帐户的 subscriptionID。subscriptionID: This field is set to the subscriptionID for your Azure account.

storageConnectionString:此值是从前述脚本设置的存储帐户中检索的。storageConnectionString: This value is retrieved from the storage account set up in the previous script. 路由使用此值来访问存储帐户。It is used by the routing to access the storage account.

containerName:此字段是存储帐户中要将数据写入到的容器的名称。containerName: This field is the name of the container in the storage account to which data will be written.

Encoding:请将此字段设置为 AVROJSONEncoding: Set this field to either AVRO or JSON. 这会指定存储数据的格式。This designates the format of the stored data. 默认值为 AVRO。The default is AVRO.

routeName:此字段是要设置的路由的名称。routeName: This field is the name of the route you are setting up.

condition:此字段是用于筛选发送到此终结点的消息的查询。condition: This field is the query used to filter for the messages sent to this endpoint. 路由到存储的消息的查询条件是 level="storage"The query condition for the messages being routed to storage is level="storage".

enabled:此字段默认为 true,指示消息路由应在创建后启用。enabled: This field defaults to true, indicating that the message route should be enabled after being created.

请复制此脚本,并将其粘贴到命令行窗口中。Copy this script and paste it into your terminal window.

##### ROUTING FOR STORAGE #####

$endpointName = "ContosoStorageEndpoint"
$endpointType = "azurestoragecontainer"
$routeName = "ContosoStorageRoute"
$condition = 'level="storage"'

下一步是为存储帐户创建路由终结点。The next step is to create the routing endpoint for the storage account. 还可以指定用于存储结果的容器。You also specify the container in which the results will be stored. 创建存储帐户时已创建该容器。The container was created when the storage account was created.

# Create the routing endpoint for storage.
# Specify 'AVRO' or 'JSON' for the encoding of the data.
Add-AzIotHubRoutingEndpoint `
  -ResourceGroupName $resourceGroup `
  -Name $iotHubName `
  -EndpointName $endpointName `
  -EndpointType $endpointType `
  -EndpointResourceGroup $resourceGroup `
  -EndpointSubscriptionId $subscriptionId `
  -ConnectionString $storageConnectionString  `
  -ContainerName $containerName `
  -Encoding AVRO

接下来,为存储终结点创建消息路由。Next, create the message route for the storage endpoint. 消息路由根据查询规范指定要将消息发送到何处。The message route designates where to send the messages that meet the query specification.

# Create the route for the storage endpoint.
Add-AzIotHubRoute `
   -ResourceGroupName $resourceGroup `
   -Name $iotHubName `
   -RouteName $routeName `
   -Source DeviceMessages `
   -EndpointName $endpointName `
   -Condition $condition `
   -Enabled 

路由到服务总线队列Route to a Service Bus queue

现在为服务总线队列设置路由。Now set up the routing for the Service Bus queue. 若要检索服务总线队列的连接字符串,必须创建一个定义了正确权限的授权规则。To retrieve the connection string for the Service Bus queue, you must create an authorization rule that has the correct rights defined. 以下脚本为服务总线队列创建名为 sbauthrule 的授权规则,并将权限设置为 Listen Manage SendThe following script creates an authorization rule for the Service Bus queue called sbauthrule, and sets the rights to Listen Manage Send. 设置此授权规则后,可以使用它来检索队列的连接字符串。Once this authorization rule is set up, you can use it to retrieve the connection string for the queue.

##### ROUTING FOR SERVICE BUS QUEUE #####

# Create the authorization rule for the Service Bus queue.
New-AzServiceBusAuthorizationRule `
  -ResourceGroupName $resourceGroup `
  -NamespaceName $serviceBusNamespace `
  -Queue $serviceBusQueueName `
  -Name "sbauthrule" `
  -Rights @("Manage","Listen","Send")

现在,使用该授权规则来检索服务总线队列密钥。Now use the authorization rule to retrieve the Service Bus queue key. 稍后将在脚本中使用此授权规则来检索连接字符串。This authorization rule will be used to retrieve the connection string later in the script.

$sbqkey = Get-AzServiceBusKey `
    -ResourceGroupName $resourceGroup `
    -NamespaceName $serviceBusNamespace `
    -Queue $servicebusQueueName `
    -Name "sbauthrule"

现在,为服务总线队列设置路由终结点和消息路由。Now set up the routing endpoint and the message route for the Service Bus queue. 以下是脚本使用的变量,必须进行设置:These are the variables used by the script that must be set:

endpointName:此字段是用于标识终结点的名称。endpointName: This field is the name identifying the endpoint.

endpointType:此字段是终结点的类型。endpointType: This field is the type of endpoint. 此值必须设置为 azurestoragecontainereventhubservicebusqueueservicebustopicThis value must be set to azurestoragecontainer, eventhub, servicebusqueue, or servicebustopic. 在本文中,请将其设置为 servicebusqueueFor your purposes here, set it to servicebusqueue.

routeName:此字段是要设置的路由的名称。routeName: This field is the name of the route you are setting up.

condition:此字段是用于筛选发送到此终结点的消息的查询。condition: This field is the query used to filter for the messages sent to this endpoint. 路由到服务总线队列的消息的查询条件是 level="critical"The query condition for the messages being routed to the Service Bus queue is level="critical".

下面是服务总线队列的消息路由的 Azure PowerShell。Here is the Azure PowerShell for the message routing for the Service Bus queue.

$endpointName = "ContosoSBQueueEndpoint"
$endpointType = "servicebusqueue"
$routeName = "ContosoSBQueueRoute"
$condition = 'level="critical"'

# Add the routing endpoint, using the connection string property from the key.
Add-AzIotHubRoutingEndpoint `
  -ResourceGroupName $resourceGroup `
  -Name $iotHubName `
  -EndpointName $endpointName `
  -EndpointType $endpointType `
  -EndpointResourceGroup $resourceGroup `
  -EndpointSubscriptionId $subscriptionId `
  -ConnectionString $sbqkey.PrimaryConnectionString

# Set up the message route for the Service Bus queue endpoint.
Add-AzIotHubRoute `
   -ResourceGroupName $resourceGroup `
   -Name $iotHubName `
   -RouteName $routeName `
   -Source DeviceMessages `
   -EndpointName $endpointName `
   -Condition $condition `
   -Enabled 

在门户中查看消息路由View message routing in the portal

设置终结点和消息路由以后,即可在门户中查看其配置。Now that your endpoints and message routes are set up, you can view their configuration in the portal. 登录 Azure 门户,转到“资源组”。 Sign in to the Azure portal and go to Resource Groups. 接下来选择你的资源组,然后选择中心(在本教程中,中心名称以 ContosoTestHub 开头)。Next, select your resource group, then select your hub (the hub name starts with ContosoTestHub in this tutorial). 此时会看到“IoT 中心”窗格。You see the IoT Hub pane.

IoT 中心属性平面

在适用于 IoT 中心的选项中,选择“消息路由”。 In the options for the IoT Hub, select Message Routing. 此时会显示已成功设置的路由。The routes you have set up successfully are displayed.

已设置的路由

在“消息路由”屏幕上 选择“自定义终结点” ,查看为路由定义的终结点。On the Message routing screen, select Custom Endpoints to see the endpoints you have defined for the routes.

为路由设置的终结点

后续步骤Next steps

设置资源并配置消息路由后,请继续学习下一篇教程,了解如何将消息发送到 IoT 中心,并查看其如何路由到不同的目标。Now that you have the resources set up and the message routes configured, advance to the next tutorial to learn how to send messages to the IoT hub and see them be routed to the different destinations.