您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

扩建端到端解决方案Build out an end-to-end solution

若要设置由环境中的实时数据驱动的完整端到端解决方案,可以将 Azure 数字孪生实例连接到其他 Azure 服务,以管理设备和数据。To set up a full end-to-end solution driven by live data from your environment, you can connect your Azure Digital Twins instance to other Azure services for management of devices and data.

在本教程中,你将...In this tutorial, you will...

  • 设置 Azure 数字孪生实例Set up an Azure Digital Twins instance
  • 了解示例建筑方案,并实例化预先编写的组件Learn about the sample building scenario and instantiate the pre-written components
  • 使用 Azure Functions 应用将模拟的遥测从 IoT 中心设备路由到数字孪生属性Use an Azure Functions app to route simulated telemetry from an IoT Hub device into digital twin properties
  • 通过使用 Azure Functions、终结点和路由处理数字孪生通知,通过孪生图传播更改Propagate changes through the twin graph, by processing digital twin notifications with Azure Functions, endpoints, and routes

先决条件Prerequisites

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

此外,在开始之前,请在开发计算机上按照 Visual Studio 2019 版本 16.5 或更高版本Also before you start, install Visual Studio 2019, version 16.5 or later on your development machine. 如果已安装了较旧的版本,可以在计算机上打开 Visual Studio 安装程序应用,然后按照提示更新安装。If you have an older version installed already, you can open the Visual Studio Installer app on your machine and follow the prompts to update your installation.

本教程由一个使用 C# 编写的示例项目驱动。The tutorial is driven by a sample project written in C#. 示例如下所示:Azure 数字孪生示例The sample is located here: Azure Digital Twins samples. 导航到示例链接,然后选择标题下方的“下载 ZIP”按钮,在你的计算机上获取示例项目。Get the sample project on your machine by navigating to the sample link, and selecting the Download ZIP button underneath the title.

准备 Azure 数字孪生实例Prepare an Azure Digital Twins instance

要完成本教程,需要一个要对其进行编程的 Azure 数字孪生实例To complete this tutorial, you'll need an Azure Digital Twins instance to program against. 如果已有通过以前的工作设置的 Azure 数字孪生实例,则可以使用该实例,然后跳到下一部分。If you already have an Azure Digital Twins instance set up from previous work, you can use that instance, and skip to the next section.

否则,使用操作方法:设置实例和身份验证中的说明设置实例和身份验证。Otherwise, set up an instance and authentication using the instructions in How-to: Set up an instance and authentication. 说明中还包含用于验证是否已成功完成每个步骤并准备好继续使用新实例的步骤。The instructions also contain steps to verify that you have completed each step successfully and are ready to move on to using your new instance.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 可以将 Bash 或 PowerShell 与 Cloud Shell 配合使用来使用 Azure 服务。You can use either Bash or PowerShell with Cloud Shell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To start Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。Select Try It in the upper-right corner of a code block. 选择“试用”不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell”按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上角菜单栏上的 Cloud Shell 按钮。Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 启动 Cloud Shell。Start Cloud Shell.

  2. 选择代码块上的“复制”按钮以复制代码。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上选择 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上选择 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. 选择 Enter 运行此代码。Select Enter to run the code.

设置 Cloud Shell 会话Set up Cloud Shell session

要在打开的 Azure Cloud Shell 窗口中开始处理 Azure 数字孪生,首先需要登录,并为此会话将 shell 上下文设置为你的订阅。To start working with Azure Digital Twins in an open Azure Cloud Shell window, the first thing to do is log in and set the shell context to your subscription for this session. 在 Cloud Shell 中运行以下命令:Run these commands in your Cloud Shell:

az login
az account set --subscription "<your-Azure-subscription-ID>"

提示

在上面的命令中,还可以使用订阅名称而不使用 ID。You can also use your subscription name instead of the ID in the command above.

如果这是你首次将此订阅与 Azure 数字孪生一起使用,请运行该命令以向 Azure 数字孪生命名空间进行注册。If this is the first time you've used this subscription with Azure Digital Twins, run this command to register with the Azure Digital Twins namespace. (如果不确定,可以再次运行该命令,即使过去某个时候操作过也是如此。)(If you're not sure, it's ok to run it again even if you've done it sometime in the past.)

az provider register --namespace 'Microsoft.DigitalTwins'

接下来,将适用于 Azure CLI 的 Microsoft Azure IoT 扩展添加到 Cloud Shell 以支持用于与 Azure 数字孪生和其他 IoT 服务进行交互的命令。Next you'll add the Microsoft Azure IoT Extension for Azure CLI to your Cloud Shell, to enable commands for interacting with Azure Digital Twins and other IoT services.

首先,运行此命令来查看已安装的所有扩展的列表。First, run this command to see a list of all the extensions you already have installed.

az extension list

输出是你当前拥有的所有扩展的数组。The output is an array of all the extensions you currently have. 查找每个列表项的 "name" 字段,以查看扩展的名称。Look for the "name" field for each list entry to see the names of the extensions.

使用输出确定要为扩展安装程序运行的以下哪个命令(可以运行多个)。Use the output to determine which of the following commands to run for the extension setup (you may run more than one).

  • 如果列表包含 azure-iot:你已拥有该扩展。If the list contains azure-iot: You have the extension already. 运行此命令以确保你拥有最新更新且没有其他更新可用:Run this command to make sure you have the latest update and there are no more updates available:

    az extension update --name azure-iot
    
  • 如果列表不包含 azure-iot:需要安装扩展。If the list does not contain azure-iot: You need to install the extension. 使用此命令:Use this command:

    az extension add --name azure-iot
    
  • 如果列表包含 azure-iot-cli-ext:这是该扩展的旧版本。If the list contains azure-iot-cli-ext: This is the legacy version of the extension. 一次只能安装该扩展的一个版本,因此应卸载旧扩展。Only one version of the extension should be installed at a time, so you should uninstall the legacy extension. 使用此命令:Use this command:

    az extension remove --name azure-cli-iot-ext
    

现在 Azure 数字孪生已可在 Cloud Shell 中使用。Now you are ready to work with Azure Digital Twins in the Cloud Shell.

若要验证 Azure 数字孪生在 Cloud Shell 中的就绪性,可以随时运行 az dt -h 查看可用的顶层 Azure 数字孪生命令列表。You can verify this by running az dt -h at any time to see a list of the top-level Azure Digital Twins commands that are available.

配置示例项目Configure the sample project

接下来,设置将与 Azure 数字孪生实例交互的示例客户端应用程序。Next, set up a sample client application that will interact with your Azure Digital Twins instance. 如果尚未下载示例项目,请选择标题下面的“下载 ZIP”按钮,立即从 Azure 数字孪生示例登陆页面中获取。If you haven't already downloaded the sample project, get it now from the Azure Digital Twins samples landing page, by selecting the Download ZIP button underneath the title.

导航到已在计算机上下载的文件,然后将其解压缩。Navigate to the downloaded file on your machine and unzip it.

打开解压缩的文件夹后,导航到 AdtSampleApp/。Once inside the unzipped folder, navigate into AdtSampleApp/. 在 Visual Studio 2019 中打开 AdtE2ESample.sln。Open AdtE2ESample.sln in Visual Studio 2019.

在 Visual Studio 中,使用“解决方案资源管理器”窗格创建 SampleClientApp > serviceConfig.json.TEMPLATE 文件的副本(可使用右键菜单进行复制和粘贴)。In Visual Studio, use the Solution Explorer pane to create a copy of the SampleClientApp > serviceConfig.json.TEMPLATE file (you can use the right-select menus to copy and paste). 重命名副本 serviceConfig.json。Rename the copy serviceConfig.json. 该副本将充当预设置的 JSON 文件,其中包含运行项目所需的配置变量。This will serve as a pre-set JSON file with the necessary configuration variables to run the project.

选择 serviceConfig.json 文件,在编辑窗口中将其打开。Select the serviceConfig.json file to open it in the editing window. tenantId 更改为目录 ID,将 clientId 更改为应用程序 ID,并将 instanceUrl 更改为 Azure 数字孪生实例 hostName URL(以 https:// 开头,如下所示) 。Change the tenantId to your Directory ID, clientId to your Application ID, and instanceUrl to your Azure Digital Twins instance hostName URL (with https:// in front of it as shown below).

{
  "tenantId": "<your-directory-ID>",
  "clientId": "<your-application-ID>",
  "instanceUrl": "https://<your-Azure-Digital-Twins-instance-hostName>"
}

保存并关闭该文件。Save and close the file.

接下来,配置 serviceConfig 文件,在生成 SampleClientApp 时将其复制到输出目录 。Next, configure the serviceConfig.json file to be copied to the output directory when you build the SampleClientApp. 为此,请右键单击 serviceConfig.json 文件,然后选择“属性” 。To do this, right-select the serviceConfig.json file, and choose Properties. 在“属性”检查器中,将“复制到输出目录”属性的值更改为“如果较新则复制” 。In the Properties inspector, change the value of the Copy to Output Directory property to Copy if newer.

Visual Studio 窗口的摘录,其中显示了“解决方案资源管理器”窗格(该窗格中突出显示了 serviceConfig.json)和“属性”窗格(该窗格中将“复制到输出目录”属性设置为“如果较新则复制”)

在 Visual Studio 中将 AdtE2ESample 项目保持在打开状态,以便在本教程中继续使用该项目。Keep the AdtE2ESample project open in Visual Studio to continue using it in the tutorial.

开始使用建筑方案Get started with the building scenario

本教程中使用的示例项目代表真实的建筑方案,包含楼层、房间和温控设备。The sample project used in this tutorial represents a real-world building scenario, containing a floor, a room, and a thermostat device. Azure 数字孪生实例将以数字形式表示这些组件,然后连接到 IoT 中心事件网格和两个 Azure 函数以加快数据移动。These components will be digitally represented in an Azure Digital Twins instance, which will then be connected to IoT Hub, Event Grid, and two Azure functions to facilitate movement of data.

下面是表示完整方案的关系图。Below is a diagram representing the full scenario.

首先,你将创建 Azure 数字孪生实例(图中的 A 部分),然后设置传入数字孪生的遥测数据流(箭头 B),再设置通过孪生图进行的数据传播(箭头 C) 。You will first create the Azure Digital Twins instance (section A in the diagram), then set up the telemetry data flow into the digital twins (arrow B), then set up the data propagation through the twin graph (arrow C).

完整的建筑方案图。描绘了从设备流向 IoT 中心的数据,该数据通过 Azure 函数(箭头 B)传到 Azure 数字孪生实例(A 部分),然后通过事件网格传到另一个 Azure 函数进行处理(箭头 C)

为逐步完成此方案,需要与先前下载的预先编写的示例应用程的组件进行交互。To work through the scenario, you will interact with components of the pre-written sample app you downloaded earlier.

下面是建筑方案 AdtSampleApp 示例应用实现的组件:Here are the components implemented by the building scenario AdtSampleApp sample app:

  • 设备身份验证Device authentication
  • .NET (C#) SDK 用法示例(参见 CommandLoop.cs).NET (C#) SDK usage examples (found in CommandLoop.cs)
  • 调用 Azure 数字孪生 API 的控制台接口Console interface to call the Azure Digital Twins API
  • SampleClientApp - Azure 数字孪生解决方案示例SampleClientApp - A sample Azure Digital Twins solution
  • SampleFunctionsApp - Azure Functions 应用,可将 Azure 数字孪生图更新为来自 IoT 中心和 Azure 数字孪生事件的遥测结果SampleFunctionsApp - An Azure Functions app that updates your Azure Digital Twins graph as a result of telemetry from IoT Hub and Azure Digital Twins events

示例项目还包含交互式授权组件。The sample project also contains an interactive authorization component. 每次启动项目时,浏览器窗口都会随即打开,提示你使用 Azure 帐户登录。Every time you start up the project, a browser window will open, prompting you to log in with your Azure account.

实例化预先创建的孪生图Instantiate the pre-created twin graph

首先,你将使用示例项目中的 AdtSampleApp 解决方案构建端到端方案的 Azure 数字孪生部分(A 部分):First, you'll use the AdtSampleApp solution from the sample project to build the Azure Digital Twins piece of the end-to-end scenario (section A):

完整建筑方案图的摘录,其中突出显示了 A 部分(Azure 数字孪生实例)

在打开 AdtE2ESample 项目的 Visual Studio 窗口中,使用工具栏中的此按钮运行该项目:In your Visual Studio window where the AdtE2ESample project is open, run the project with this button in the toolbar:

Visual Studio 开始按钮(SampleClientApp 项目)

控制台窗口随即打开,执行身份验证,然后等待命令。A console window will open, carry out authentication, and wait for a command. 在此控制台中,运行下一个命令来实例化示例 Azure 数字孪生解决方案。In this console, run the next command to instantiate the sample Azure Digital Twins solution.

重要

如果 Azure 数字孪生实例中已经有数字孪生和关系,运行此命令会将其删除,并替换为示例方案的孪生和关系。If you already have digital twins and relationships in your Azure Digital Twins instance, running this command will delete them and replace them with the twins and relationships for the sample scenario.

SetupBuildingScenario

此命令的输出是一系列确认消息,因为 Azure 数字孪生实例中创建和连接了三个数字孪生:名为 floor1 的楼层、名为 room21 的房间和名为 thermostat67 的温度传感器 。The output of this command is a series of confirmation messages as three digital twins are created and connected in your Azure Digital Twins instance: a floor named floor1, a room named room21, and a temperature sensor named thermostat67. 这些数字孪生表示真实环境中可能存在的实体。These digital twins represent the entities that would exist in a real-world environment.

它们通过关系连接到以下孪生图They are connected via relationships into the following twin graph. 孪生图表示整个环境,包括实体之间的交互和关联方式。The twin graph represents the environment as a whole, including how the entities interact with and relate to each other.

该图显示 floor1 包含 room21 且 room21 包含 thermostat67

通过运行以下命令可以验证孪生是否已创建,这样会查询已连接的 Azure 数字孪生实例中所包含的所有数字孪生:You can verify the twins that were created by running the following command, which queries the connected Azure Digital Twins instance for all the digital twins it contains:

Query

此后,就可以停止运行该项目。After this, you can stop running the project. 不过,请在 Visual Studio 中使解决方案保持打开状态,因为本教程还将继续使用它。Keep the solution open in Visual Studio, though, as you'll continue using it throughout the tutorial.

设置示例函数应用Set up the sample function app

下一步是设置将在本教程中用来处理数据的 Azure Functions 应用The next step is setting up an Azure Functions app that will be used throughout this tutorial to process data. 函数应用 SampleFunctionsApp 包含两个函数:The function app, SampleFunctionsApp, contains two functions:

  • ProcessHubToDTEvents:处理传入的 IoT 中心数据,并相应地更新 Azure 数字孪生ProcessHubToDTEvents: processes incoming IoT Hub data and updates Azure Digital Twins accordingly
  • ProcessDTRoutedData:处理来自数字孪生的数据,并相应地更新 Azure 数字孪生中的父级孪生ProcessDTRoutedData: processes data from digital twins, and updates the parent twins in Azure Digital Twins accordingly

在本部分中,你将发布预先编写的函数应用,并确保该函数应用可通过向其分配 Azure Active Directory (Azure AD) 标识来访问 Azure 数字孪生。In this section, you will publish the pre-written function app, and ensure the function app can access Azure Digital Twins by assigning it an Azure Active Directory (Azure AD) identity. 完成这些步骤后,本教程的其余部分即可使用函数应用中的函数。Completing these steps will allow the rest of the tutorial to use the functions inside the function app.

发布应用Publish the app

返回到打开 AdtE2ESample 项目的 Visual Studio 窗口中,从“解决方案资源管理器”窗格中,右键选择 SampleFunctionsApp 项目文件,然后点击“发布” 。Back in your Visual Studio window where the AdtE2ESample project is open, from the Solution Explorer pane, right-select the SampleFunctionsApp project file and hit Publish.

Visual Studio:发布项目

在接下来的“发布”页中,保留选择的默认 Azure 目标,然后点击“下一步”。In the Publish page that follows, leave the default target selection of Azure and hit Next.

对于特定目标,请选择“Azure 函数应用(Windows)”,然后点击“下一步”。For a specific target, choose Azure Function App (Windows) and hit Next.

在 Visual Studio 中发布 Azure 函数:特定目标

在“Functions 实例”页上,选择你的订阅。On the Functions instance page, choose your subscription. 这应该会使订阅中资源组填入方框。This should populate a box with the resource groups in your subscription.

选择实例的资源组,然后点击“+ 创建新的 Azure 函数…”。Select your instance's resource group and hit + Create a new Azure Function....

在 Visual Studio 中发布 Azure 函数:Functions 实例(在函数应用之前)

在“函数应用(Windows) - 新建”窗口中,按如下所示填写字段:In the Function App (Windows) - Create new window, fill in the fields as follows:

  • “名称”是 Azure 将用于托管 Azure Functions 应用的消耗计划的名称。Name is the name of the consumption plan that Azure will use to host your Azure Functions app. 这也将成为保存实际函数的函数应用的名称。This will also become the name of the function app that holds your actual function. 你可以选择自己的唯一值,也可以保留默认建议。You can choose your own unique value or leave the default suggestion.
  • 确保“订阅”与要使用的订阅匹配Make sure the Subscription matches the subscription you want to use
  • 确保“资源组”是你想要使用的资源组Make sure the Resource group to the resource group you want to use
  • 将“计划类型”保留为“消耗”Leave the Plan type as Consumption
  • 在“位置”中,选择符合资源组位置的位置Select the Location that matches the location of your resource group
  • 使用“新建…”链接创建新的 Azure 存储资源。Create a new Azure Storage resource using the New... link. 设置与资源组相匹配的位置,使用其他默认值,然后点击“确定”。Set the location to match your resource group, use the other default values, and hit "Ok".

在 Visual Studio 中发布 Azure 函数:函数应用(Windows) - 新建

然后选择“创建”。Then, select Create.

这会使你返回到“Functions 实例”页,此时新函数应用会显示在资源组下。This should bring you back to the Functions instance page, where your new function app is now visible underneath your resource group. 点击“完成”。Hit Finish.

在 Visual Studio 中发布 Azure 函数:Functions 实例(在函数应用之后)

在 Visual Studio 主窗口重新打开的“发布”窗格中,检查所有信息是否都正确无误,然后选择“发布”。On the Publish pane that opens back in the main Visual Studio window, check that all the information looks correct and select Publish.

在 Visual Studio 中发布 Azure 函数:发布

备注

你可能会看到如下所示的弹出窗口:在 Visual Studio 中发布 Azure 函数:发布凭据 如果出现弹出窗口,请依次选择“尝试从 Azure 检索凭据”和“保存” 。If so, select Attempt to retrieve credentials from Azure and Save.

若看到“你的 Functions 运行时版本与在 Azure中运行的版本不匹配”警告,请按照提示升级到最新的 Azure Functions 运行时版本。If you see a warning that Your version of the functions runtime does not match the version running in Azure, follow the prompts to upgrade to the latest Azure Functions runtime version. 若使用旧版本的 Visual Studio 而不是本教程开头的“先决条件”部分中推荐的版本,则可能出现此问题。This issue might occur if you're using an older version of Visual Studio than the one recommended in the Prerequisites section at the start of this tutorial.

向函数应用分配权限Assign permissions to the function app

为了使函数应用能够访问 Azure 数字孪生,下一步是配置应用设置,为应用分配系统管理的 Azure AD 标识,并为此标识授予 Azure 数字孪生实例的“所有者”权限。To enable the function app to access Azure Digital Twins, the next step is to configure an app setting, assign the app a system-managed Azure AD identity, and give this identity owner permissions in the Azure Digital Twins instance.

在 Azure Cloud Shell 中,使用以下命令设置一个应用程序设置,供函数应用用来引用数字孪生实例。In Azure Cloud Shell, use the following command to set an application setting which your function app will use to reference your digital twins instance.

az functionapp config appsettings set -g <your-resource-group> -n <your-App-Service-(function-app)-name> --settings "ADT_SERVICE_URL=<your-digital-twin-instance-URL>"

使用以下命令创建系统管理的标识。Use the following command to create the system-managed identity. 记下输出中的 principalId 字段。Take note of the principalId field in the output.

az functionapp identity assign -g <your-resource-group> -n <your-App-Service-(function-app)-name>

在以下命令中,使用 principalId 值将函数应用的标识分配给 Azure 数字孪生实例的“所有者”角色 :Use the principalId value in the following command to assign the function app's identity to the owner role for your Azure Digital Twins instance:

az dt role-assignment create --dt-name <your-Azure-Digital-Twins-instance> --assignee "<principal-ID>" --role "Azure Digital Twins Owner (Preview)"

此命令的结果是已创建的角色分配的输出信息。The result of this command is outputted information about the role assignment you've created. 函数应用现在有权访问 Azure 数字孪生实例。The function app now has permissions to access your Azure Digital Twins instance.

处理来自 IoT 中心设备的模拟遥测数据Process simulated telemetry from an IoT Hub device

Azure 数字孪生图将由真实设备的遥测驱动。An Azure Digital Twins graph is meant to be driven by telemetry from real devices.

在此步骤中,需要将在 IoT 中心内注册的模拟温控设备连接到在 Azure 数字孪生中表示它的数字孪生。In this step, you will connect a simulated thermostat device registered in IoT Hub to the digital twin that represents it in Azure Digital Twins. 当模拟设备发出遥测时,系统将通过可触发数字孪生中相应更新的 ProcessHubToDTEvents Azure 函数定向数据。As the simulated device emits telemetry, the data will be directed through the ProcessHubToDTEvents Azure function that triggers a corresponding update in the digital twin. 通过这种方式,数字孪生就可与真实设备的数据保持一致。In this way, the digital twin stays up to date with the real device's data. 在 Azure 数字孪生中,将事件数据从一个位置定向到另一个位置的过程称为路由事件In Azure Digital Twins, the process of directing events data from one place to another is called routing events.

该过程发生在端到端方案的这一部分(箭头 B):This happens in this part of the end-to-end scenario (arrow B):

完整建筑方案图的摘录,其中突出显示了箭头 B(Azure 数字孪生前的元素:设备、IoT 中心和第一个 Azure 函数)

下面是设置此设备连接需要完成的操作:Here are the actions you will complete to set up this device connection:

  1. 创建将管理模拟设备的 IoT 中心Create an IoT hub that will manage the simulated device
  2. 设置事件订阅,将 IoT 中心连接到相应的 Azure 函数Connect the IoT hub to the appropriate Azure function by setting up an event subscription
  3. 在 IoT 中心注册模拟设备Register the simulated device in IoT hub
  4. 运行模拟设备并生成遥测Run the simulated device and generate telemetry
  5. 查询 Azure 数字孪生以查看实时结果Query Azure Digital Twins to see the live results

创建 IoT 中心实例Create an IoT Hub instance

Azure 数字孪生旨在搭配 IoT 中心使用,后者是用于管理设备及其数据的 Azure 服务。Azure Digital Twins is designed to work alongside IoT Hub, an Azure service for managing devices and their data. 在此步骤中,你将设置一个 IoT 中心,用于管理本教程中的示例设备。In this step, you will set up an IoT hub that will manage the sample device in this tutorial.

在 Azure Cloud Shell 中,使用此命令创建新的 IoT 中心:In Azure Cloud Shell, use this command to create a new IoT hub:

az iot hub create --name <name-for-your-IoT-hub> -g <your-resource-group> --sku S1

此命令的输出是有关已创建的 IoT 中心的信息。The output of this command is information about the IoT hub that was created.

保存提供给 IoT 中心的名称。Save the name that you gave to your IoT hub. 稍后将使用它。You will use it later.

将 IoT 中心连接到 Azure 函数Connect the IoT hub to the Azure function

接下来,将 IoT 中心连接到之前在函数应用中发布的 ProcessHubToDTEvents Azure 函数,让数据可以通过函数从设备流入 IoT 中心,这一操作将更新 Azure 数字孪生。Next, connect your IoT hub to the ProcessHubToDTEvents Azure function in the function app you published earlier, so that data can flow from the device in IoT Hub through the function, which updates Azure Digital Twins.

为此,需要在 IoT 中心创建一个事件订阅,并将 Azure 函数作为终结点。To do this, you'll create an Event Subscription on your IoT Hub, with the Azure function as an endpoint. 这会将函数“订阅”到 IoT 中心发生的事件。This "subscribes" the function to events happening in IoT Hub.

Azure 门户中,导航到新创建的 IoT 中心,方法是在顶部搜索栏中搜索其名称。In the Azure portal, navigate to your newly-created IoT hub by searching for its name in the top search bar. 从中心菜单中选择“事件”,然后选择“+ 事件订阅” 。Select Events from the hub menu, and select + Event Subscription.

Azure 门户:IoT 中心事件订阅

此时将显示“创建事件订阅”页。This will bring up the Create Event Subscription page.

Azure 门户:创建事件订阅

按如下所示填写字段(默认填充的字段未提及):Fill in the fields as follows (fields filled by default are not mentioned):

  • “事件订阅详细信息” > “名称”:为事件订阅指定名称。EVENT SUBSCRIPTION DETAILS > Name: Give a name to your event subscription.
  • “主题详细信息” > “系统主题名称”:为系统主题提供一个名称。TOPIC DETAILS > System Topic Name: Give a name to use for the system topic.
  • “事件类型” > “筛选事件类型”:从菜单选项中选择“设备遥测”。EVENT TYPES > Filter to Event Types: Select Device Telemetry from the menu options.
  • “终结点详细信息” > “终结点类型”:从菜单选项中选择“Azure 函数”。ENDPOINT DETAILS > Endpoint Type: Select Azure Function from the menu options.
  • “终结点详细信息” > “终结点”:点击“选择终结点”链接。ENDPOINT DETAILS > Endpoint: Hit the Select an endpoint link. 这会打开“选择 Azure 函数”窗口:Azure 门户事件订阅:选择 Azure 函数
    • 填写“订阅”、“资源组”、“函数应用”和“函数”(ProcessHubToDTEvents) 。Fill in your Subscription, Resource group, Function app and Function (ProcessHubToDTEvents). 在选择订阅后,其中一些可能会自动填充。Some of these may auto-populate after selecting the subscription.
    • 点击“确认所选内容”。Hit Confirm Selection.

返回“创建事件订阅”页,点击“创建”。Back on the Create Event Subscription page, hit Create.

在 IoT 中心注册模拟设备Register the simulated device with IoT Hub

本部分在 ID 为 thermostat67 的 IoT 中心内创建设备表示形式。This section creates a device representation in IoT Hub with the ID thermostat67. 模拟设备将与其连接,这也是遥测事件从设备进入 IoT 中心的方式,在 IoT 中心中,上一步订阅的 Azure 函数正在侦听,准备获取事件并继续处理。The simulated device will connect into this, and this is how telemetry events will go from the device into IoT Hub, where the subscribed Azure function from the previous step is listening, ready to pick up the events and continue processing.

在 Azure Cloud Shell 中,使用以下命令在 IoT 中心创建设备:In Azure Cloud Shell, create a device in IoT Hub with the following command:

az iot hub device-identity create --device-id thermostat67 --hub-name <your-IoT-hub-name> -g <your-resource-group>

输出是已创建设备的相关信息。The output is information about the device that was created.

配置和运行模拟Configure and run the simulation

接下来,配置设备模拟器以将数据发送到 IoT 中心实例。Next, configure the device simulator to send data to your IoT Hub instance.

首先,使用以下命令获取 IoT 中心连接字符串:Begin by getting the IoT hub connection string with this command:

az iot hub show-connection-string -n <your-IoT-hub-name>

然后,使用此命令获取设备连接字符串:Then, get the device connection string with this command:

az iot hub device-identity show-connection-string --device-id thermostat67 --hub-name <your-IoT-hub-name>

将这些值插入本地项目中的设备模拟器代码中,以将模拟器连接到此 IoT 中心和 IoT 中心设备。You'll plug these values into the device simulator code in your local project to connect the simulator into this IoT hub and IoT hub device.

在新的 Visual Studio 窗口中,(从下载的解决方案文件夹)打开“设备模拟器”>“DeviceSimulator.sln”。In a new Visual Studio window, open (from the downloaded solution folder) Device Simulator > DeviceSimulator.sln.

备注

你现在应该有两个 Visual Studio 窗口,一个是 DeviceSimulator.sln,另一个是 AdtE2ESample.sln 。You should now have two Visual Studio windows, one with DeviceSimulator.sln and one from earlier with AdtE2ESample.sln.

在这个新 Visual Studio 窗口的“解决方案资源管理器”窗格中,选择“DeviceSimulator/AzureIoTHub.cs”,在编辑窗口中将其打开。From the Solution Explorer pane in this new Visual Studio window, select DeviceSimulator/AzureIoTHub.cs to open it in the editing window. 将以下连接字符串值更改为前面收集的值:Change the following connection string values to the values you gathered above:

connectionString = <Iot-hub-connection-string>
deviceConnectionString = <device-connection-string>

保存文件。Save the file.

现在,要查看已设置的数据模拟结果,请在工具栏中用此按钮运行 DeviceSimulator 项目:Now, to see the results of the data simulation that you've set up, run the DeviceSimulator project with this button in the toolbar:

Visual Studio 开始按钮(DeviceSimulator 项目)

控制台窗口将打开并显示模拟的温度遥测消息。A console window will open and display simulated temperature telemetry messages. 这些消息将发送到 IoT 中心,由 Azure 函数选取并处理。These are being sent to IoT Hub, where they are then picked up and processed by the Azure function.

设备模拟器的控制台输出,其中显示了正在发送的温度遥测

你无需此控制台中执行任何其他操作,但在完成后续步骤时,需要让其保持运行状态。You don't need to do anything else in this console, but leave it running while you complete the next steps.

查看 Azure 数字孪生中的结果See the results in Azure Digital Twins

之前发布的 ProcessHubToDTEvents 函数会侦听 IoT 中心数据,并调用 Azure 数字孪生 API 来更新 thermostat67 孪生上的“温度”属性 。The ProcessHubToDTEvents function you published earlier listens to the IoT Hub data, and calls an Azure Digital Twins API to update the Temperature property on the thermostat67 twin.

要查看 Azure 数字孪生端的数据,请转到打开 AdtE2ESample 项目的 Visual Studio 窗口,并运行该项目。To see the data from the Azure Digital Twins side, go to your Visual Studio window where the AdtE2ESample project is open and run the project.

在打开的项目控制台窗口中运行以下命令,以获取数字孪生 thermostat67 所报告的温度:In the project console window that opens, run the following command to get the temperatures being reported by the digital twin thermostat67:

ObserveProperties thermostat67 Temperature

你应该会看到来自 Azure 数字孪生实例的实时更新温度正在每隔 10 秒就记录到控制台中。You should see the live updated temperatures from your Azure Digital Twins instance being logged to the console every 10 seconds.

控制台输出,其中显示来自数字孪生 thermostat67 的温度消息日志

验证此操作成功后,就可以停止运行这两个项目。Once you've verified this is working successfully, you can stop running both projects. 让 Visual Studio 窗口保持打开状态,因为在本教程的其余部分将继续使用它们。Keep the Visual Studio windows open, as you'll continue using them in the rest of the tutorial.

通过图形传播 Azure 数字孪生事件Propagate Azure Digital Twins events through the graph

到本教程的此阶段,你已了解如何通过外部设备数据更新 Azure 数字孪生。So far in this tutorial, you've seen how Azure Digital Twins can be updated from external device data. 接下来,你将了解如何通过 Azure 数字孪生图传播对某个数字孪生的更改,换句话说,就是如何从服务内部数据更新孪生。Next, you'll see how changes to one digital twin can propagate through the Azure Digital Twins graph—in other words, how to update twins from service-internal data.

为此,在更新已连接的 Thermostat 孪生时,你将使用 ProcessDTRoutedData Azure 函数来更新 Room 孪生 。To do this, you'll use the ProcessDTRoutedData Azure function to update a Room twin when the connected Thermostat twin is updated. 该过程发生在端到端方案的这一部分(箭头 C):This happens in this part of the end-to-end scenario (arrow C):

完整建筑方案图的摘录,其中突出显示了箭头 C(Azure 数字孪生后的元素:事件网格和第二个 Azure 函数)

下面是设置此数据流需要完成的操作:Here are the actions you will complete to set up this data flow:

  1. 创建一个将实例连接到事件网格的 Azure 数字孪生终结点Create an Azure Digital Twins endpoint that connects the instance to Event Grid
  2. 在 Azure 数字孪生中设置路由,将孪生属性更改事件发送到终结点Set up a route within Azure Digital Twins to send twin property change events to the endpoint
  3. 部署在终结点上(通过事件网格)侦听的 Azure Functions 应用,并相应地更新其他孪生Deploy an Azure Functions app that listens (through Event Grid) on the endpoint, and updates other twins accordingly
  4. 运行模拟设备并查询 Azure 数字孪生,以查看实时结果Run the simulated device and query Azure Digital Twins to see the live results

设置终结点Set up endpoint

事件网格是一项 Azure 服务,可帮助你将来自 Azure 服务的事件路由和传递到 Azure 中的其他位置。Event Grid is an Azure service that helps you route and deliver events coming from Azure Services to other places within Azure. 你可以创建一个事件网格主题从源收集特定事件,然后订阅者可以侦听该主题,以便在事件送达时接收事件。You can create an event grid topic to collect certain events from a source, and then subscribers can listen on the topic to receive the events as they come through.

在本部分中,你将创建一个事件网格主题,然后在 Azure 数字孪生内创建一个指向(将事件传送至)该主题的终结点。In this section, you create an event grid topic, and then create an endpoint within Azure Digital Twins that points (sends events) to that topic.

在 Azure Cloud Shell 中运行以下命令,以创建事件网格主题:In Azure Cloud Shell, run the following command to create an event grid topic:

az eventgrid topic create -g <your-resource-group> --name <name-for-your-event-grid-topic> -l <region>

提示

要输出可传递到 Azure CLI 命令中的 Azure 区域名称的列表,请运行以下命令:To output a list of Azure region names that can be passed into commands in the Azure CLI, run this command:

az account list-locations -o table

此命令的输出是已创建的事件网格主题的相关信息。The output from this command is information about the event grid topic you've created.

接下来,创建一个指向事件网格主题的 Azure 数字孪生终结点。Next, create an Azure Digital Twins endpoint pointing to your event grid topic. 使用下面的命令,根据需要填写占位符字段:Use the command below, filling in the placeholder fields as necessary:

az dt endpoint create eventgrid --dt-name <your-Azure-Digital-Twins-instance> --eventgrid-resource-group <your-resource-group> --eventgrid-topic <your-event-grid-topic> --endpoint-name <name-for-your-Azure-Digital-Twins-endpoint>

此命令的输出是已创建的终结点的相关信息。The output from this command is information about the endpoint you've created.

你也可以执行以下命令在 Azure 数字孪生实例中查询此终结点,从而验证是否成功创建终结点:You can also verify that the endpoint creation succeeded by running the following command to query your Azure Digital Twins instance for this endpoint:

az dt endpoint show --dt-name <your-Azure-Digital-Twins-instance> --endpoint-name <your-Azure-Digital-Twins-endpoint> 

在输出中查找 provisioningState 字段,检查其值是否为“Succeeded”。Look for the provisioningState field in the output, and check that the value is "Succeeded".

终结点的查询结果,其中显示 provisioningState 为 Succeeded

保存提供给事件网格主题和 Azure 数字孪生终结点的名称。Save the names that you gave to your event grid topic and your Azure Digital Twins endpoint. 稍后你将用到它们。You will use them later.

设置路由Set up route

接下来,创建 Azure 数字孪生路由,将事件发送到刚刚创建的 Azure 数字孪生终结点。Next, create an Azure Digital Twins route that sends events to the Azure Digital Twins endpoint you just created.

az dt route create --dt-name <your-Azure-Digital-Twins-instance> --endpoint-name <your-Azure-Digital-Twins-endpoint> --route-name <name-for-your-Azure-Digital-Twins-route>

此命令的输出是一些有关已创建的路由的信息。The output from this command is some information about the route you've created.

将函数连接到事件网格Connect the function to Event Grid

接下来,请将 ProcessDTRoutedData Azure 函数订阅到前面创建的事件网格主题,让遥测数据可以通过事件网格主题从 thermostat67 孪生流向该函数,该函数会返回到 Azure 数字孪生并相应地更新 room21 。Next, subscribe the ProcessDTRoutedData Azure function to the event grid topic you created earlier, so that telemetry data can flow from the thermostat67 twin through the event grid topic to the function, which goes back into Azure Digital Twins and updates the room21 twin accordingly.

为此,你需要从事件网格主题中创建对 ProcessDTRoutedData Azure 函数的订阅作为终结点。To do this, you'll create an Event Grid subscription from your event grid topic to your ProcessDTRoutedData Azure function as an endpoint.

Azure 门户中,导航到事件网格主题,方法是在顶部搜索栏中搜索其名称。In the Azure portal, navigate to your event grid topic by searching for its name in the top search bar. 选择“+ 事件订阅”。Select + Event Subscription.

Azure 门户:事件网格事件订阅

创建此事件订阅的步骤与之前在本教程中将第一个 Azure 函数订阅到 IoT 中心的步骤类似。The steps to create this event subscription are similar to when you subscribed the first Azure function to IoT Hub earlier in this tutorial. 这次不需要将设备遥测指定为要侦听的事件类型,而且会连接到其他 Azure 函数。This time, you don't need to specify Device Telemetry as the event type to listen for, and you'll connect to a different Azure function.

在“创建事件订阅”页,按如下所示填写字段(默认填充的字段未提及):On the Create Event Subscription page, fill in the fields as follows (fields filled by default are not mentioned):

  • “事件订阅详细信息” > “名称”:为事件订阅指定名称。EVENT SUBSCRIPTION DETAILS > Name: Give a name to your event subscription.
  • “终结点详细信息” > “终结点类型”:从菜单选项中选择“Azure 函数”。ENDPOINT DETAILS > Endpoint Type: Select Azure Function from the menu options.
  • “终结点详细信息” > “终结点”:点击“选择终结点”链接。ENDPOINT DETAILS > Endpoint: Hit the Select an endpoint link. 这会打开“选择 Azure 函数”窗口:This will open a Select Azure Function window:
    • 填写“订阅”、“资源组”、“函数应用”和“函数”(ProcessDTRoutedData) 。Fill in your Subscription, Resource group, Function app and Function (ProcessDTRoutedData). 在选择订阅后,其中一些可能会自动填充。Some of these may auto-populate after selecting the subscription.
    • 点击“确认所选内容”。Hit Confirm Selection.

返回“创建事件订阅”页,点击“创建”。Back on the Create Event Subscription page, hit Create.

运行模拟并查看结果Run the simulation and see the results

现在你可以运行设备模拟器,启动已设置的新事件流。Now you can run the device simulator to kick off the new event flow you've set up. 转到打开 DeviceSimulator 项目的 Visual Studio 窗口,然后运行该项目。Go to your Visual Studio window where the DeviceSimulator project is open, and run the project.

与之前运行设备模拟器一样,控制台窗口将打开并显示模拟温度遥测消息。Like when you ran the device simulator earlier, a console window will open and display simulated temperature telemetry messages. 这些事件将经过之前设置的流来更新 thermostat67 孪生,然后经过最近设置的流来更新 room21 孪生以进行匹配 。These events are going through the flow you set up earlier to update the thermostat67 twin, and then going through the flow you set up recently to update the room21 twin to match.

设备模拟器的控制台输出,其中显示了正在发送的温度遥测

你无需此控制台中执行任何其他操作,但在完成后续步骤时,需要让其保持运行状态。You don't need to do anything else in this console, but leave it running while you complete the next steps.

若要查看 Azure 数字孪生端的数据,请转到打开 AdtE2ESample 项目的 Visual Studio 窗口,并运行该项目。To see the data from the Azure Digital Twins side, go to your Visual Studio window where the AdtE2ESample project is open, and run the project.

在打开的项目控制台窗口中运行以下命令,以获取 thermostat67 和 room21 这两个数字孪生所报告的温度 。In the project console window that opens, run the following command to get the temperatures being reported by both the digital twin thermostat67 and the digital twin room21.

ObserveProperties thermostat67 Temperature room21 Temperature

你应该会看到来自 Azure 数字孪生实例的实时更新温度正在每隔 10 秒就记录到控制台中。You should see the live updated temperatures from your Azure Digital Twins instance being logged to the console every 10 seconds. 注意,room21 的温度正在更新,以匹配 thermostat67 的更新 。Notice that the temperature for room21 is being updated to match the updates to thermostat67.

控制台输出,其中显示来自温控设备和房间的温度消息日志

验证此操作成功后,就可以停止运行这两个项目。Once you've verified this is working successfully, you can stop running both projects. 你也可以关闭 Visual Studio 窗口,因为本教程现已完成。You can also close the Visual Studio windows, as the tutorial is now complete.

审阅Review

下面回顾了在本教程中扩建的方案。Here is a review of the scenario that you built out in this tutorial.

  1. Azure 数字孪生实例以数字方式表示楼层、房间和温控设备(如下图中 A 部分所示)An Azure Digital Twins instance digitally represents a floor, a room, and a thermostat (represented by section A in the diagram below)
  2. 模拟设备遥测发送到 IoT 中心,其中 ProcessHubToDTEvents Azure 函数正在侦听遥测事件。Simulated device telemetry is sent to IoT Hub, where the ProcessHubToDTEvents Azure function is listening for telemetry events. ProcessHubToDTEvents Azure 函数使用这些事件中的信息来设置 thermostat67(图中箭头 B)的“温度”属性 。The ProcessHubToDTEvents Azure function uses the information in these events to set the Temperature property on thermostat67 (arrow B in the diagram).
  3. Azure 数字孪生的属性更改事件会路由到事件网格主题,其中 ProcessDTRoutedData Azure 函数正在侦听事件。Property change events in Azure Digital Twins are routed to an event grid topic, where the ProcessDTRoutedData Azure function is listening for events. ProcessDTRoutedData Azure 函数使用这些事件中的信息来设置 room21(图中箭头 C)的“温度”属性 。The ProcessDTRoutedData Azure function uses the information in these events to set the Temperature property on room21 (arrow C in the diagram).

完整的建筑方案图。描绘了从设备流向 IoT 中心的数据,该数据通过 Azure 函数(箭头 B)传到 Azure 数字孪生实例(A 部分),然后通过事件网格传到另一个 Azure 函数进行处理(箭头 C)

清理资源Clean up resources

如果不再需要本教程中创建的资源,请按照以下步骤将其删除。If you no longer need the resources created in this tutorial, follow these steps to delete them.

利用 Azure Cloud Shell,你可以使用 az group delete 命令删除资源组中的所有 Azure 资源。Using the Azure Cloud Shell, you can delete all Azure resources in a resource group with the az group delete command. 这会删除资源组;Azure 数字孪生实例;IoT 中心和中心设备注册;事件网格主题和关联的订阅;以及两个 Azure Functions 应用,包括存储等关联资源。This removes the resource group; the Azure Digital Twins instance; the IoT hub and the hub device registration; the event grid topic and associated subscriptions; and both Azure Functions apps, including associated resources like storage.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 资源组以及包含在其中的所有资源将被永久删除。The resource group and all the resources contained in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources.

az group delete --name <your-resource-group>

接下来,使用以下命令删除为客户端应用创建的 Azure AD 应用注册:Next, delete the Azure AD app registration you created for your client app with this command:

az ad app delete --id <your-application-ID>

最后,删除从本地计算机下载的项目示例文件夹。Finally, delete the project sample folder you downloaded from your local machine.

后续步骤Next steps

在本教程中,你创建了一个端到端方案,它显示了由实时设备数据驱动的 Azure 数字孪生。In this tutorial, you created an end-to-end scenario that shows Azure Digital Twins being driven by live device data.

接下来,请开始查看概念文档,详细了解本教程中所用的元素:Next, start looking at the concept documentation to learn more about elements you worked with in the tutorial:

或者,你也可以先查看操作方法文章,更深入的了解本教程中的过程:Or, go more in-depth on the processes in this tutorial by starting the how-to articles: