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

教程:部署 Azure 数字孪生并配置空间图Tutorial: Deploy Azure Digital Twins and configure a spatial graph

可以使用 Azure 数字孪生服务将人员、地点和设备规整到一个一致的空间系统中。You can use the Azure Digital Twins service to bring together people, places, and devices in a coherent spatial system. 本系列教程演示如何使用 Azure 数字孪生来检测温度和空气质量达到理想化条件时的房间占用情况。This series of tutorials demonstrates how to use Azure Digital Twins to detect room occupancy with optimal conditions of temperature and air quality.

这些教程演示如何通过 .NET 控制台应用程序生成一个涉及一栋办公大楼的方案,These tutorials will walk you through a .NET console application to build a scenario of an office building. 该楼有多个楼层,每个楼层有多个房间。The building has multiple floors and rooms within each floor. 房间包含设备,通过附加的传感器来检测移动、环境温度和空气质量。The rooms contain devices with attached sensors that detect motion, ambient temperature, and air quality.

本系列教程会介绍如何通过 Azure 数字孪生服务将大楼中的物理区域和实体复制为数字对象。You'll learn how to replicate the physical areas and entities in the building as digital objects by using the Azure Digital Twins service. 可以使用另一控制台应用程序模拟设备事件。You'll simulate device events by using another console application. 然后,教程会介绍如何以近实时的方式监视来自这些物理区域和实体的事件。Then, you'll learn how to monitor the events that come from these physical areas and entities in near real time.

办公室主任可以根据此信息帮助在此大楼工作的员工预订理想化条件的会议室。An office administrator can use this information to help an employee working in this building to book meeting rooms with optimal conditions. 办公设备管理员可以根据你的设置了解房间的使用趋势,并监视进行维护所需的工作条件。An office facilities manager can use your setup to get usage trends of the rooms, and to monitor working conditions for maintenance purposes.

本系列的第一个教程介绍如何执行以下操作:In the first tutorial of this series, you learn how to:

  • 部署数字孪生。Deploy Digital Twins.
  • 向应用授权。Grant permissions to your app.
  • 修改数字孪生示例应用。Modify a Digital Twins sample app.
  • 预配大楼。Provision your building.

这些教程使用和修改介绍如何查找可用房间的快速入门所使用的示例,目的是更详细且更深入地探讨相关概念。These tutorials use and modify the same samples that the quickstart to find available rooms uses, for a more detailed and in-depth coverage of the concepts.


  • Azure 订阅。An Azure subscription. 如果没有 Azure 帐户,请创建一个免费帐户If you don’t have an Azure account, create a free account.

  • .NET Core SDK。The .NET Core SDK. 在这些教程中使用的 Azure 数字孪生示例以 C# 编写。The Azure Digital Twins samples used in these tutorials are written in C#. 请确保在用于生成和运行示例的开发计算机上安装 .NET Core SDK 2.1.403 或更高版本Make sure to install .NET Core SDK version 2.1.403 or later on your development machine to build and run the sample. 在命令窗口中运行 dotnet --version 即可检查计算机上是否已安装正确的版本。Check that the right version is installed on your machine by running dotnet --version in a command window.

  • Visual Studio Code,用于探索示例代码。Visual Studio Code to explore the sample code.

部署数字孪生Deploy Digital Twins

请使用此部分的步骤创建 Azure 数字孪生服务的新实例。Use the steps in this section to create a new instance of the Azure Digital Twins service. 每个订阅只能创建一个实例。Only one instance can be created per subscription. 如果已经有一个实例在运行,请跳至下一部分。Skip to the next section if you already have one running.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 在左窗格中,选择“创建资源”。From the left pane, select Create a resource. 搜索“数字孪生”,选择“数字孪生(预览版)”。Search for digital twins, and select Digital Twins (preview). 选择“创建”,启动部署过程。Select Create to start the deployment process.


  3. 在“数字孪生”窗格中,输入以下信息:In the Digital Twins pane, enter the following information:

    • 资源名称:为数字孪生实例创建一个唯一名称。Resource Name: Create a unique name for your Digital Twins instance.

    • 订阅:选择需要将其用于创建此数字孪生实例的订阅。Subscription: Choose the subscription that you want to use to create this Digital Twins instance.

    • 资源组:为数字孪生实例选择或创建资源组Resource group: Select or create a resource group for the Digital Twins instance.

    • 位置:选择离你的设备最近的位置。Location: Select the closest location to your devices.


  4. 查看数字孪生信息,然后选择“创建”。Review your Digital Twins information, and then select Create. 创建数字孪生实例可能需要数分钟。Your Digital Twins instance might take a few minutes to be created. 可在“通知”窗格中监视进度。You can monitor the progress in the Notifications pane.

  5. 打开数字孪生实例的“概览”窗格。Open the Overview pane of your Digital Twins instance. 记下“管理 API”下的链接。Note the link under Management API.

    管理 API URL 的格式为:https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/swaggerThe Management API URL is formatted as https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/swagger. 此 URL 将引导你到适用于实例的 Azure 数字孪生 REST API 文档。This URL takes you to the Azure Digital Twins REST API documentation that applies to your instance. 阅读如何使用 Azure 数字孪生 Swagger,了解如何阅读和使用此 API 文档。Read How to use Azure Digital Twins Swagger to learn how to read and use this API documentation.

    管理 API URL 修改成此格式:https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/api/v1.0/Modify the Management API URL to this format https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/api/v1.0/. 应用程序将使用此修改过的 URL 作为基 URL 来访问实例。Your application will use the modified URL as the base URL to access your instance. 将此修改过的 URL 复制到一个临时文件。Copy this modified URL to a temporary file. 下一部分将需要此 URL。You'll need this in the next section.

    管理 API

向应用授权Grant permissions to your app

数字孪生使用 Azure Active Directory (Azure AD) 来控制对服务的读/写访问权限Digital Twins uses Azure Active Directory (Azure AD) to control read/write access to the service. 任何需要与数字孪生实例连接的应用程序都必须注册到 Azure AD。Any application that needs to connect with your Digital Twins instance must be registered with Azure AD. 本部分的步骤介绍如何注册示例应用。The steps in this section show how to register your sample app.

如果已经进行了应用注册,可以将其重用于示例。If you already have an app registration, you can reuse it for your sample. 但是,请浏览本部分,确保应用注册已正确配置。However, browse through this section to make sure your app registration is configured correctly.

  1. Azure 门户中,从左窗格打开 Azure Active Directory,然后打开“属性”窗格。In the Azure portal, open Azure Active Directory from the left pane, and then open the Properties pane. 将“目录 ID”复制到一个临时文件。Copy the Directory ID to a temporary file. 将在下一部分使用此值来配置示例应用程序。You'll use this value to configure a sample application in the next section.

    Azure Active Directory 目录 ID

  2. 打开“应用注册”窗格,然后选择“新建应用程序注册”按钮。Open the App registrations pane, and then select the New application registration button.


  3. 在“名称”框中,为此应用注册提供一个友好名称。Give a friendly name for this app registration in the Name box. 选择“本机”作为“应用程序类型”,然后选择 https://microsoft.com 作为“重定向 URI”。Choose Application type as Native, and Redirect URI as https://microsoft.com. 选择“创建”。Select Create.


  4. 打开注册的应用,将“应用程序 ID”字段的值复制到一个临时文件中。Open the registered app, and copy the value of the Application ID field to a temporary file. 该值用于标识 Azure Active Directory 应用。This value identifies your Azure Active Directory app. 将在下一部分使用此应用程序 ID 来配置示例应用程序。You'll use the application ID to configure your sample application in the following sections.

    Azure Active Directory 应用程序 ID

  5. 打开应用注册窗格。Open your app registration pane. 选择“设置” > “所需权限”,然后执行以下操作:Select Settings > Required permissions, and then:

    a.在“解决方案资源管理器”中,右键单击项目文件夹下的“引用”文件夹,并单击“添加引用”。a. 在左上角选择“添加”,打开“添加 API 访问权限”窗格。Select Add on the upper left to open the Add API access pane.

    b.b. 选择“选择 API”,搜索“Azure 数字孪生”。Select Select an API and search for Azure Digital Twins. 如果搜索没有找到该 API,请改为搜索“Azure 智能空间”。If your search doesn't locate the API, search for Azure Smart Spaces instead.

    c.c. 选择“Azure 数字孪生(Azure 智能空间服务)”选项,然后选择“选择”。Select the Azure Digital Twins (Azure Smart Spaces Service) option and choose Select.

    d.d. 选择“选择权限”。Choose Select permissions. 选中“读/写访问权限”委托权限复选框,然后选择“选择”。Select the Read/Write Access delegated permissions check box, and choose Select.

    e.e. 在“添加 API 访问权限”窗格中,选择“完成”。Select Done in the Add API access pane.

    f.f. 在“所需的权限”窗格中选择“授予权限”按钮,接受显示的确认。In the Required permissions pane, select the Grant permissions button, and accept the acknowledgement that appears.


配置数字孪生示例Configure the Digital Twins sample

本部分详细介绍一个可以与数字孪生 REST API 通信的 Azure 数字孪生应用程序。This section walks you through an Azure Digital Twins application that communicates with the Digital Twins REST APIs.

下载示例Download the sample

如果已下载适用于介绍如何查找可用房间的快速入门的示例,可以跳过这些步骤。If you already have the samples downloaded for the quickstart to find available rooms, you can skip these steps.

  1. 下载数字孪生 .NET 示例Download the Digital Twins .NET samples.
  2. 解压缩计算机上的 zip 文件夹的内容。Extract the contents of the zip folder on your machine.

探索示例Explore the sample

在解压缩后的示例文件夹中,通过 Visual Studio Code 打开 digital-twins-samples-csharp\digital-twins-samples.code-workspace 文件。In the extracted sample folder, open the file digital-twins-samples-csharp\digital-twins-samples.code-workspace in Visual Studio Code. 该文件包含两个项目:It contains two projects:

  • 可以通过预配示例 occupancy-quickstart 配置和预配空间智能图You can use the provisioning sample occupancy-quickstart to configure and provision a spatial intelligence graph. 该图是你的物理空间以及其中的资源的数字化图像。This graph is the digitized image of your physical spaces and the resources in them. 它使用对象模型来定义智能大楼的对象。It uses an object model, which defines objects for a smart building. 如需数字孪生对象和 REST API 的完整列表,请访问此 REST API 文档或者为你的实例创建的管理 API URL。For a complete list of Digital Twins objects and REST APIs, visit this REST API documentation or the Management API URL that was created for your instance.

    若要通过示例来了解它与数字孪生实例的通信方式,可以从 src\actions 文件夹开始。To explore the sample to see how it communicates with your Digital Twins instance, you can start with the src\actions folder. 该文件夹中的文件实现的命令是将要在这些教程中使用的命令:The files in this folder implement the commands that you'll use in these tutorials:

    • provisionSample.cs 文件说明如何预配空间图。The provisionSample.cs file shows how to provision your spatial graph.
    • getSpaces.cs 文件获取已预配空间的相关信息。The getSpaces.cs file gets information about the provisioned spaces.
    • getAvailableAndFreshSpaces.cs 文件获取名为“用户定义函数”的自定义函数的结果。The getAvailableAndFreshSpaces.cs file gets the results of a custom function called a user-defined function.
    • createEndpoints.cs 文件创建与其他服务交互的终结点。The createEndpoints.cs file creates endpoints to interact with other services.
  • 模拟示例 device-connectivity 模拟传感器数据并将其发送到为数字孪生实例预配的 IoT 中心。The simulation sample device-connectivity simulates sensor data and sends it to the IoT hub that's provisioned for your Digital Twins instance. 将在预配空间图后的下一教程中使用此示例。You'll use this sample in the next tutorial after you provision your spatial graph. 用于配置此示例的传感器和设备标识符应该与用于预配图形的相同。The sensor and device identifiers that you use to configure this sample should be the same as what you'll use to provision your graph.

配置预配示例Configure the provisioning sample

  1. 打开一个命令窗口,转到已下载的示例。Open a command window and go to the downloaded sample. 运行以下命令:Run the following command:

    cd occupancy-quickstart/src
  2. 通过运行以下命令将依赖项还原到示例项目:Restore dependencies to the sample project by running this command:

    dotnet restore
  3. 在 Visual Studio Code 中打开 occupancy-quickstart 项目中的 appSettings.json 文件。In Visual Studio Code, open the appSettings.json file in the occupancy-quickstart project. 更新以下值:Update the following values:

    • ClientId:输入 Azure AD 应用注册的应用程序 ID。ClientId: Enter the application ID of your Azure AD app registration. 已在设置应用权限的部分记下此 ID。You noted this ID in the section where you set app permissions.
    • 租户:输入 Azure AD 租户的目录 ID。Tenant: Enter the directory ID of your Azure AD tenant. 也已在设置应用权限的部分记下此 ID。You also noted this ID in the section where you set app permissions.
    • BaseUrl:输入数字孪生实例的 URL。BaseUrl: Enter the URL of your Digital Twins instance. 若要获取此 URL,请将其中的占位符替换为适用于你的实例的值:https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/api/v1.0/To get this URL, replace the placeholders in this URL with values for your instance: https://yourDigitalTwinsName.yourLocation.azuresmartspaces.net/management/api/v1.0/. 也可通过修改部署部分的管理 API URL 来获取此 URL。You can also get this URL by modifying the Management API URL from the deployment section. swagger/ 替换为 api/v1.0/Replace swagger/ with api/v1.0/.
  4. 查看数字孪生功能的列表,这些功能可以通过示例来探索。See a list of Digital Twins features that you can explore by using the sample. 运行以下命令:Run the following command:

    dotnet run

了解预配过程Understand the provisioning process

此部分介绍示例如何预配大楼的空间图。This section shows how the sample provisions a spatial graph of a building.

在 Visual Studio Code 中浏览到 occupancy-quickstart\src\actions 文件夹,打开 provisionSample.cs 文件。In Visual Studio Code, browse to the occupancy-quickstart\src\actions folder and open the file provisionSample.cs. 注意以下函数:Note the following function:

public static async Task<IEnumerable<ProvisionResults.Space>> ProvisionSample(HttpClient httpClient, ILogger logger)
    IEnumerable<SpaceDescription> spaceCreateDescriptions;
    using (var r = new StreamReader("actions/provisionSample.yaml"))
        spaceCreateDescriptions = await GetProvisionSampleTopology(r);

    var results = await CreateSpaces(httpClient, logger, spaceCreateDescriptions, Guid.Empty);

    Console.WriteLine($"Completed Provisioning: {JsonConvert.SerializeObject(results, Formatting.Indented)}");

    return results;

此函数使用同一文件夹中的 provisionSample.yamlThis function uses provisionSample.yaml in the same folder. 打开此文件,注意办公大楼的层次结构:地点、楼层、区域和房间。Open this file, and note the hierarchy of an office building: Venue, Floor, Area, and Rooms. 任何一个这样的物理空间都可能包含设备和传感器。Any of these physical spaces can contain devices and sensors. 每个条目都有预定义的 type—例如楼层和房间。Each entry has a predefined type—for example, Floor, Room.

示例 yaml 文件显示一个使用 Default 数字孪生对象模型的空间图。The sample yaml file shows a spatial graph that uses the Default Digital Twins object model. 该模型提供适用于大多数类型的通用名称。This model provides generic names for most types. 通用名称对于大楼来说已足够。Generic names are sufficient for a building. 例如,使用“温度”作为 SensorDataType,使用“地图”作为 SpaceBlobType。Examples are Temperature for SensorDataType, and Map for SpaceBlobType. 例如,子类型为 FocusRoom、ConferenceRoom 等的房间为空间类型。An example space type is Room with subtypes FocusRoom, ConferenceRoom, and so on.

如果必须为另一类型的地点(例如工厂)创建空间图,则可能需要另一对象模型。If you had to create a spatial graph for a different type venue, such as a factory, you might need a different object model. 若要找出可供使用的具体模型,可在适用于预配示例的命令行中运行 dotnet run GetOntologies 命令。You can find out which models are available to use by running the command dotnet run GetOntologies on the command line for the provisioning sample.

若要详细了解空间图和对象模型,请阅读了解数字孪生对象模型和空间智能图For more information on spatial graphs and object models, read Understanding Digital Twins object models and spatial intelligence graph.

修改示例空间图Modify the sample spatial graph

provisionSample.yaml 文件包含以下节点:The provisionSample.yaml file contains the following nodes:

  • resourcesresources 节点创建一个 Azure IoT 中心资源,用于与设置中的设备通信。resources: The resources node creates an Azure IoT Hub resource to communicate with the devices in your setup. 在图形根节点处的 IoT 中心可以与图形中的所有设备和传感器通信。An IoT hub at the root node of your graph can communicate with all the devices and sensors in your graph.

  • spaces:在数字孪生对象模型中,spaces 表示物理位置。spaces: In the Digital Twins object model, spaces represent the physical locations. 每个空间都有一个 Type(例如区域、地点或客户),以及一个友好 NameEach space has a Type—for example, Region, Venue, or Customer—and a friendly Name. 一些空间可能属于另一些空间,形成一个层次结构。Spaces can belong to other spaces, creating a hierarchical structure. provisionSample.yaml 文件有一个虚构大楼的空间图。The provisionSample.yaml file has a spatial graph of an imaginary building. 注意 Venue 中有 Floor 类型,楼层中有 Area,区域中有 Room 节点,这样就形成了空间的逻辑嵌套。Note the logical nesting of spaces of type Floor within Venue, Area in a floor, and Room nodes in an area.

  • devices:空间可能包含 devices,这是物理或虚拟实体,用于管理大量传感器。devices: Spaces can contain devices, which are physical or virtual entities that manage a number of sensors. 例如,设备可能是用户的手机、Raspberry Pi 传感器 Pod 或网关。For example, a device might be a user’s phone, a Raspberry Pi sensor pod, or a gateway. 在示例的虚构大楼中,注意名为“专注室”的房间包含一个 Raspberry Pi 3 A1 设备。In the imaginary building in your sample, note how the room named Focus Room contains a Raspberry Pi 3 A1 device. 每个设备节点均由已硬编码到示例中的唯一 hardwareId 进行标识。Each device node is identified by a unique hardwareId, which is hardcoded in the sample. 若要针对实际生产来配置此示例,请将这些项替换为你设置中的值。To configure this sample for an actual production, replace these with values from your setup.

  • sensors:一个设备可能包含多个 sensorssensors: A device can contain multiple sensors. 用于检测和记录物理变化,例如温度、移动和电池剩余电量的变化。They can detect and record physical changes like temperature, motion, and battery level. 每个传感器节点都通过此处硬编码的 hardwareId 进行唯一标识。Each sensor node is uniquely identified by a hardwareId, hardcoded here. 对于实际的应用程序,请将这些项替换为设置中传感器的唯一标识符。For an actual application, replace these by using the unique identifiers of the sensors in your setup. provisionSample.yaml 文件有两个传感器,用于记录移动和二氧化碳情况。The provisionSample.yaml file has two sensors to record Motion and CarbonDioxide. 请添加另一传感器来记录温度,方法是将以下行添加到二氧化碳传感器对应的行下面。Add another sensor to record Temperature, by adding the following lines, below the lines for the CarbonDioxide sensor. 请注意,这些都是在 provisionSample.yaml 中作为注释掉的行提供的。Note that these are provided in provisionSample.yaml as commented-out lines. 可以取消注释这些行,方法是删除每一行前面的 # 字符。You can uncomment them by removing the # character in the front of each line.

            - dataType: Temperature
              hardwareId: SAMPLE_SENSOR_TEMPERATURE


    请确保 dataTypehardwareId 键与此代码片段上面的语句对齐。Make sure the dataType and hardwareId keys align with the statements above this snippet. 另请确保编辑器不将空格替换为制表符。Also make sure that your editor does not replace spaces with tabs.

保存并关闭 provisionSample.yaml 文件。Save and close the provisionSample.yaml file. 在下一教程中,将向此文件添加更多的信息,然后预配 Azure 数字孪生示例大楼。In the next tutorial, you'll add more information to this file, and then provision your Azure Digital Twins sample building.


可以使用 Azure 数字孪生图形查看器查看和修改空间图。You can view and modify your spatial graph using the Azure Digital Twins Graph Viewer.

清理资源Clean up resources

如果不希望继续探索 Azure 数字孪生,可以删除本教程中创建的资源:If you want to stop exploring Azure Digital Twins at this point, feel free to delete resources created in this tutorial:

  1. Azure 门户的左菜单中依次选择“所有资源”、数字孪生资源组、“删除”。From the left menu in the Azure portal, select All resources, select your Digital Twins resource group, and select Delete.


    如果在删除数字孪生实例时遇到麻烦,请使用已推出的包含修补程序的服务更新。If you experienced trouble deleting your Digital Twins instance, a service update has been rolled out with the fix. 请重新尝试删除实例。Please retry deleting your instance.

  2. 可以根据需要删除工作计算机上的示例应用程序。If necessary, delete the sample application on your work machine.

后续步骤Next steps

若要了解如何实现一个用于监视示例大楼中条件的自定义逻辑,请继续学习此系列中的下一教程:To learn how to implement a custom logic to monitor conditions in your sample building, go to the next tutorial in the series: