教程:开发适用于 Windows 设备的 IoT Edge 模块Tutorial: Develop IoT Edge modules for Windows devices

使用 Visual Studio 开发代码并将其部署到运行 IoT Edge 的 Windows 设备。Use Visual Studio to develop and deploy code to Windows devices running IoT Edge.

在快速入门中,使用 Windows 虚拟机创建了 IoT Edge 设备,并部署了来自 Azure 市场的预构建模块。In the quickstart, you created an IoT Edge device using a Windows virtual machine and deployed a pre-built module from the Azure Marketplace. 本教程详细介绍如何才能开发自己的代码并将其部署到 IoT Edge 设备。This tutorial walks through what it takes to develop and deploy your own code to an IoT Edge device. 本教程是学习其他教程的有用先决条件,其他教程将更详细地介绍特定编程语言或 Azure 服务。This tutorial is a useful prerequisite for the other tutorials, which go into more detail about specific programming languages or Azure services.

本教程使用将 C# 模块部署到 Windows 设备的示例。This tutorial uses the example of deploying a C# module to a Windows device. 之所以选择了此示例,原因在于它是最常见的开发方案。This example was chosen because it's the most common development scenario. 如果你希望使用不同的语言进行开发,或者计划将 Azure 服务作为模块来部署,本教程还有助于了解开发工具。If you're interested in developing in a different language, or plan on deploying Azure services as modules, this tutorial will still be helpful to learn about the development tools. 了解开发概念后,即可选择首选语言或 Azure 服务来深入了解详细信息。Once you understand the development concepts, then you can choose your preferred language or Azure service to dive into the details.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 设置开发计算机。Set up your development machine.
  • 使用适用于 Visual Studio 的 IoT Edge Tools 创建新项目。Use the IoT Edge tools for Visual Studio to create a new project.
  • 将项目作为容器生成并将其存储在 Azure 容器注册表中。Build your project as a container and store it in an Azure container registry.
  • 将代码部署到 IoT Edge 设备。Deploy your code to an IoT Edge device.

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

关键概念Key concepts

本教程详细介绍如何开发 IoT Edge 模块。This tutorial walks through the development of an IoT Edge module. IoT Edge 模块有时简称模块,它是一个包含可执行代码的容器。An IoT Edge module, or sometimes just module for short, is a container that contains executable code. 可以将一个或多个模块部署到 IoT Edge 设备。You can deploy one or more modules to an IoT Edge device. 模块可执行特定任务,例如从传感器引入数据、执行数据分析或数据清理操作,或将消息发送到 IoT 中心。Modules perform specific tasks like ingesting data from sensors, performing data analytics or data cleaning operations, or sending messages to an IoT hub. 有关详细信息,请参阅了解 Azure IoT Edge 模块For more information, see Understand Azure IoT Edge modules.

开发 IoT Edge 模块时,了解开发计算机和最终将部署模块的目标 IoT Edge 设备之间的差异非常重要。When developing IoT Edge modules, it's important to understand the difference between the development machine and the target IoT Edge device where the module will eventually be deployed. 为保存模块代码而生成的容器必须与目标设备的操作系统 (OS) 匹配。The container that you build to hold your module code must match the operating system (OS) of the target device. 对于 Windows 容器开发,此概念更为简单,因为 Windows 容器仅在 Windows 操作系统上运行。For Windows container development, this concept is simpler because Windows containers only run on Windows operating systems. 但是,可以使用 Windows 开发计算机生成适用于 Linux IoT Edge 设备的模块。But you could, for example, use your Windows development machine to build modules for Linux IoT Edge devices. 在该方案中,必须确保开发计算机运行 Linux 容器。In that scenario, you'd have to make sure that your development machine was running Linux containers. 在学习本教程的过程中,请记住开发计算机 OS容器 OS 之间的差异。As you go through this tutorial, keep in mind the difference between development machine OS and the container OS.

本教程针对运行 IoT Edge 的 Windows 设备。This tutorial targets Windows devices running IoT Edge. Windows IoT Edge 设备使用 Windows 容器。Windows IoT Edge devices use Windows containers. 我们建议使用 Visual Studio 进行 Windows 设备开发,这也是本教程将使用的工具。We recommend using Visual Studio to develop for Windows devices, so that's what this tutorial will use. 还可以使用 Visual Studio Code,但两个工具提供的支持存在差异。You can use Visual Studio Code as well, although there are differences in support between the two tools.

下表列出 Visual Studio Code 和 Visual Studio 支持的 Windows 容器开发方案。The following table lists the supported development scenarios for Windows containers in Visual Studio Code and Visual Studio.

Visual Studio CodeVisual Studio Code Visual Studio 2017/2019Visual Studio 2017/2019
Azure 服务Azure services Azure FunctionsAzure Functions
Azure 流分析Azure Stream Analytics
语言Languages C#(不支持调试)C# (debugging not supported) CC
C#C#
详细信息More information 适用于 Visual Studio Code 的 Azure IoT EdgeAzure IoT Edge for Visual Studio Code 适用于 Visual Studio 2017 的 Azure IoT Edge ToolsAzure IoT Edge Tools for Visual Studio 2017
适用于 Visual Studio 2019 的 Azure IoT Edge 工具Azure IoT Edge Tools for Visual Studio 2019

先决条件Prerequisites

开发计算机:A development machine:

  • 具有 1809 更新或更高版本更新的 Windows 10。Windows 10 with 1809 update or newer.
  • 可以使用自己的计算机或虚拟机,具体取决于开发首选项。You can use your own computer or a virtual machine, depending on your development preferences.
    • 请确保开发计算机支持嵌套虚拟化。Make sure that your development machine supports nested virtualization. 此功能对于运行容器引擎是必需的,你将在下一部分中安装。This capability is necessary for running a container engine, which you install in the next section.
  • 安装 GitInstall Git.

Windows 上的 Azure IoT Edge 设备:An Azure IoT Edge device on Windows:

  • 我们建议不要在开发计算机上运行 IoT Edge,而应使用单独的设备。We recommend that you don't run IoT Edge on your development machine, but instead use a separate device. 开发计算机和 IoT Edge 设备之间的这一区分可更准确地反映真实部署方案,并有助于区分不同的概念。This distinction between development machine and IoT Edge device more accurately mirrors a true deployment scenario, and helps to keep the different concepts straight.
  • 如果没有第二台可用的设备,请按照快速入门文章的说明在 Azure 中使用 Windows 虚拟机创建 IoT Edge 设备。If you don't have a second device available, use the quickstart article to create an IoT Edge device in Azure with a Windows virtual machine.

云资源:Cloud resources:

  • Azure 中的免费或标准层 IoT 中心A free or standard-tier IoT hub in Azure.

安装容器引擎Install container engine

IoT Edge 模块被打包为容器,因此,需要在开发计算机上安装容器引擎来生成和管理容器。IoT Edge modules are packaged as containers, so you need a container engine on your development machine to build and manage the containers. 我们建议使用 Docker Desktop 进行开发,因为它作为容器引擎拥有许多功能且广受欢迎。We recommend using Docker Desktop for development because of its many features and popularity as a container engine. 借助 Windows 计算机上的 Docker Desktop,可在 Linux 容器和 Windows 容器之间切换,以便轻松地为不同类型的 IoT Edge 设备开发模块。With Docker Desktop on a Windows computer, you can switch between Linux containers and Windows containers so that you can easily develop modules for different types of IoT Edge devices.

按照 Docker 文档的说明在开发计算机上安装:Use the Docker documentation to install on your development machine:

设置 Visual Studio 和工具Set up Visual Studio and tools

适用于 Visual Studio 的 IoT 扩展有助于开发 IoT Edge 模块。The IoT extensions for Visual Studio help you to develop IoT Edge modules. 这些扩展提供项目模板、自动化部署清单的创建,并允许监视和管理 IoT Edge 设备。These extensions provide project templates, automate the creation of the deployment manifest, and allow you to monitor and manage IoT Edge devices. 本部分将安装 Visual Studio 和 IoT Edge 扩展,然后设置 Azure 帐户用于在 Visual Studio 中管理 IoT 中心资源。In this section, you install Visual Studio and the IoT Edge extension, then set up your Azure account to manage IoT Hub resources from within Visual Studio.

本教程讲解适用于 Visual Studio 2019 的开发步骤。This tutorial teaches the development steps for Visual Studio 2019. 如果使用 Visual Studio 2017(15.7 或更高版本),则步骤相似。If you are using Visual Studio 2017 (version 15.7 or higher), the steps are similar. 如果想要使用 Visual Studio Code,请参阅使用 Visual Studio Code 为 Azure IoT Edge 开发和调试模块中的说明。If you would rather use Visual Studio Code, refer to the instructions in Use Visual Studio Code to develop and debug modules for Azure IoT Edge.

  1. 在开发计算机上准备 Visual Studio 2019。Prepare Visual Studio 2019 on your development machine.

    • 如果开发计算机上尚未安装 Visual Studio,请安装 Visual Studio 2019 及以下工作负荷:If you don't already have Visual Studio on your development machine, Install Visual Studio 2019 with the following workloads:

      • Azure 开发Azure development
      • 使用 C++ 的桌面开发Desktop development with C++
      • .NET Core 跨平台开发.NET Core cross-platform development
    • 如果开发计算机上确实已有 Visual Studio 2019,请按照修改 Visual Studio 中的步骤添加所需的工作负荷。If you do already have Visual Studio 2019 on your development machine, follow the steps in Modify Visual Studio to add the required workloads.

  2. 下载并安装适用于 Visual Studio 2019 的 Azure IoT Edge Tools 扩展。Download and install the Azure IoT Edge Tools extension for Visual Studio 2019.

    如果使用的是 Visual Studio 2017(15.7 或更高版本),请下载并安装适用于 Visual Studio 2017 的 Azure IoT Edge 工具If you are using Visual Studio 2017 (version 15.7 or higher), download and install the Azure IoT Edge Tools for Visual Studio 2017.

  3. 安装完成后,打开 Visual Studio 2019 并选择“在没有代码的情况下继续”。When your installations are complete, open Visual Studio 2019 and select Continue without code.

  4. 选择“查看” > “Cloud Explorer” 。Select View > Cloud Explorer.

  5. 如果尚未登录,请在 Cloud Explorer 中选择配置文件图标并登录 Azure 帐户。Select the profile icon in the cloud explorer and sign in to your Azure account if you aren't signed in already.

  6. 登录后,系统会列出你的 Azure 订阅。Once you sign in, your Azure subscriptions are listed. 展开包含你的 IoT 中心的订阅。Expand the subscription that has your IoT hub.

  7. 在该订阅下,依次展开“IoT 中心”和你的 IoT 中心 。Under your subscription, expand IoT Hubs then your IoT hub. 应看到 IoT 设备列表,可使用此资源管理器来管理它们。You should see a list of your IoT devices, and can use this explorer to manage them.

    在 Cloud Explorer 中访问 IoT 中心资源

创建容器注册表Create a container registry

本教程将使用 Azure IoT Tools 扩展来生成模块并从文件创建容器映像In this tutorial, you use the Azure IoT Tools extension to build a module and create a container image from the files. 然后将该映像推送到用于存储和管理映像的注册表Then you push this image to a registry that stores and manages your images. 最后,从注册表部署在 IoT Edge 设备上运行的映像。Finally, you deploy your image from your registry to run on your IoT Edge device.

可以使用任意兼容 Docker 的注册表来保存容器映像。You can use any Docker-compatible registry to hold your container images. 两个常见 Docker 注册表服务分别是 Azure 容器注册表Docker 中心Two popular Docker registry services are Azure Container Registry and Docker Hub. 本教程使用 Azure 容器注册表。This tutorial uses Azure Container Registry.

如果还没有容器注册表,请执行以下步骤,以便在 Azure 中创建一个新的:If you don't already have a container registry, follow these steps to create a new one in Azure:

  1. Azure 门户中,选择“创建资源” > “容器” > “容器注册表”。In the Azure portal, select Create a resource > Containers > Container Registry.

  2. 提供以下值,以便创建容器注册表:Provide the following values to create your container registry:

    字段Field Value
    注册表名称Registry name 提供唯一名称。Provide a unique name.
    订阅Subscription 从下拉列表中选择“订阅”。Select a subscription from the drop-down list.
    资源组Resource group 建议对在 IoT Edge 快速入门和教程中创建的所有测试资源使用同一资源组。We recommend that you use the same resource group for all of the test resources that you create during the IoT Edge quickstarts and tutorials. 例如,IoTEdgeResourcesFor example, IoTEdgeResources.
    位置Location 选择靠近你的位置。Choose a location close to you.
    管理员用户Admin user 设置为“启用”。 Set to Enable.
    SKUSKU 选择“基本”。 Select Basic.
  3. 选择“创建” 。Select Create.

  4. 创建容器注册表后,浏览到它,然后从左窗格中,选择“设置”下菜单中的“访问密钥” 。After your container registry is created, browse to it, and from the left pane select Access keys from the menu located under Settings.

  5. 复制“登录服务器”、“用户名”和“密码”的值,并将其保存在方便的位置 。Copy the values for Login server, Username, and Password and save them somewhere convenient. 本教程将使用这些值来访问容器注册表。You use these values throughout this tutorial to provide access to the container registry.

    复制容器注册表的登录服务器、用户名和密码

创建新的模块项目Create a new module project

Azure IoT Edge Tools 扩展为 Visual Studio 中支持的所有 IoT Edge 模块语言提供项目模板。The Azure IoT Edge Tools extension provides project templates for all supported IoT Edge module languages in Visual Studio. 这些模板包含将工作模块部署到测试 IoT Edge 所需的所有文件和代码,或为你提供使用自己的业务逻辑自定义模板的起点。These templates have all the files and code that you need to deploy a working module to test IoT Edge, or give you a starting point to customize the template with your own business logic.

  1. 选择“文件” > “新建” > “项目...”Select File > New > Project...

  2. 在“新建项目”窗口中,搜索“IoT Edge” ,然后选择“Azure IoT Edge (Windows amd64)”项目 。In the new project window, search for IoT Edge and choose the Azure IoT Edge (Windows amd64) project. 单击“下一步”。Click Next.

    创建新的 Azure IoT Edge 项目

  3. 在“配置新项目”窗口中,重命名项目和解决方案,使名称具有描述性,例如 CSharpTutorialAppIn the configure your new project window, rename the project and solution to something descriptive like CSharpTutorialApp. 单击“创建”以创建项目。Click Create to create the project.

    配置新的 Azure IoT Edge 项目

  4. 在“添加模块”窗口中,使用下列值配置项目:In the Add Module window, configure your project with the following values:

    字段Field Value
    Visual Studio 模板Visual Studio Template 选择“C# 模块”。Select C# Module.
    模块名称Module Name 接受默认的 IotEdgeModule1Accept the default IotEdgeModule1.
    存储库 URLRepository Url 映像存储库包含容器注册表的名称和容器映像的名称。An image repository includes the name of your container registry and the name of your container image. 系统已基于模块项目名称值预先填充容器映像。Your container image is prepopulated from the module project name value. 将 localhost:5000 替换为 Azure 容器注册表中的“登录服务器”值。Replace localhost:5000 with the Login server value from your Azure container registry. 可以在 Azure 门户的容器注册表的“概述”页中检索“登录服务器”值。You can retrieve the Login server value from the Overview page of your container registry in the Azure portal.

    最终的映像存储库看起来类似于 <registry name>.azurecr.cn/iotedgemodule1。The final image repository looks like <registry name>.azurecr.cn/iotedgemodule1.

    针对目标设备、模块类型和容器注册表配置项目

  5. 选择“添加” 以创建模块。Select Add to create the module.

在 Visual Studio 窗口中加载新项目后,请花时间熟悉其创建的文件:Once your new project loads in the Visual Studio window, take a moment to familiarize yourself with the files that it created:

  • 一个名为 CSharpTutorialApp 的 IoT Edge 项目。An IoT Edge project called CSharpTutorialApp.
    • 包含指向项目所含模块的指针的 Modules 文件夹。The Modules folder contains pointers to the modules included in the project. 在本例中,应该只有 IotEdgeModule1。In this case, it should be just IotEdgeModule1.
    • 隐藏的 .env 文件保存容器注册表的凭据。The hidden .env file holds the credentials to your container registry. 这些凭据与 IoT Edge 设备共享,以便它可以访问并拉取容器映像。These credentials are shared with your IoT Edge device so that it has access to pull the container images.
    • deployment.template.json 文件是可帮助创建部署清单的模板。The deployment.template.json file is a template to help you create a deployment manifest. 部署清单是一个文件,可准确定义想要在设备上部署的模块、应如何配置它们以及它们如何相互通信及与云通信。A deployment manifest is a file that defines exactly which modules you want deployed on a device, how they should be configured, and how they can communicate with each other and the cloud.

      提示

      在“注册表凭据”部分中,将根据创建解决方案时提供的信息自动填充地址。In the registry credentials section, the address is autofilled from the information you provided when you created the solution. 但是,用户名和密码引用 .env 文件中存储的变量。However, the username and password reference variables stored in the .env file. 这是出于安全考量,因为 .env 文件被 Git 忽略,但部署模板未被忽略。This is for security, as the .env file is git ignored, but the deployment template is not.

  • 名为 IotEdgeModule1 的 IoT Edge 模块项目。An IoT Edge module project called IotEdgeModule1.
    • program.cs 文件中包含项目模板附带的默认 C# 模块代码。The program.cs file contains the default C# module code that comes with the project template. 默认模块从源获取输入并将其传递到 IoT 中心。The default module takes input from a source and passes it along to IoT Hub.
    • module.json 文件保存有关模块的详细信息,其中包括完整的映像存储库、映像版本以及用于每个受支持平台的 Dockerfile。The module.json file hold details about the module, including the full image repository, image version, and which Dockerfile to use for each supported platform.

向 IoT Edge 代理提供注册表凭据Provide your registry credentials to the IoT Edge agent

IoT Edge 运行时需要注册表凭据才能将容器映像拉取到 IoT Edge 设备中。The IoT Edge runtime needs your registry credentials to pull your container images onto the IoT Edge device. IoT Edge 扩展会尝试从 Azure 提取容器注册表信息,并将其填充到部署模板中。The IoT Edge extension tries to pull your container registry information from Azure and populate it in the deployment template.

  1. 在模块解决方案中打开 deployment.template.json 文件。Open the deployment.template.json file in your module solution.

  2. 在 $edgeAgent 所需属性中找到 registryCredentials 属性。Find the registryCredentials property in the $edgeAgent desired properties. 它应该会根据你在创建项目时提供的信息自动填写注册表地址,而用户名和密码字段应包含变量名称。It should have your registry address autofilled from the information you provided when creating the project, and then username and password fields should contain variable names. 例如:For example:

    "registryCredentials": {
      "<registry name>": {
        "username": "$CONTAINER_REGISTRY_USERNAME_<registry name>",
        "password": "$CONTAINER_REGISTRY_PASSWORD_<registry name>",
        "address": "<registry name>.azurecr.cn"
      }
    }
    
  3. 打开模块解决方案中的 .env 文件。Open the .env file in your module solution. (默认情况下,此文件会隐藏在解决方案资源管理器中,可能需要选择“显示所有文件”按钮才能显示它。)(It's hidden by default in the Solution Explorer, so you might need to select the Show All Files button to display it.)

  4. 添加从 Azure 容器注册表中复制的“用户名”和“密码”值。Add the Username and Password values that you copied from your Azure container registry.

  5. 将更改保存到 .env 文件。Save your changes to the .env file.

查看示例代码Review the sample code

创建的解决方案模板包含 IoT Edge 模块的示例代码。The solution template that you created includes sample code for an IoT Edge module. 此示例模块仅接收消息,然后传递消息。This sample module simply receives messages and then passes them on. 管道功能演示 IoT Edge 中的一个重要概念,即模块之间相互通信的方式。The pipeline functionality demonstrates an important concept in IoT Edge, which is how modules communicate with each other.

每个模块可以在其代码中声明多个输入输出队列。Each module can have multiple input and output queues declared in their code. 在设备上运行的 IoT Edge 中心将来自一个模块的输出的消息路由到一个或多个模块的输入。The IoT Edge hub running on the device routes messages from the output of one module into the input of one or more modules. 用于声明输入和输出的特定代码因语言而异,但所有模块的概念都相同。The specific code for declaring inputs and outputs varies between languages, but the concept is the same across all modules. 有关在模块之间路由的详细信息,请参阅声明路由For more information about routing between modules, see Declare routes.

项目模板附带的示例 C# 代码使用适用于 .NET 的 IoT 中心 SDK 中的 ModuleClient 类The sample C# code that comes with the project template uses the ModuleClient Class from the IoT Hub SDK for .NET.

  1. program.cs 文件中,找到 SetInputMessageHandlerAsync 方法。In the program.cs file, find the SetInputMessageHandlerAsync method.

  2. SetInputMessageHandlerAsync 方法会设置一个输入队列,用来接收传入消息。The SetInputMessageHandlerAsync method sets up an input queue to receive incoming messages. 查看此方法,并了解它如何初始化名为 input1 的输入队列。Review this method and see how it initializes an input queue called input1.

    在 SetInputMessageHandlserAsync 构造函数中找到输入名称

  3. 接下来,找到 SendEventAsync 方法。Next, find the SendEventAsync method.

  4. SendEventAsync 方法会处理收到的消息,并设置一个输出队列,用来传递这些消息。The SendEventAsync method processes received messages and sets up an output queue to pass them along. 查看此方法,可以看到它会初始化名为 output1 的输出队列。Review this method and see that it initializes an output queue called output1.

    在 SendEventAsync 构造函数中找到输出名称

  5. 打开 deployment.template.json 文件。Open the deployment.template.json file.

  6. 找到 $edgeAgent 所需属性的 modules 属性。Find the modules property of the $edgeAgent desired properties.

    此处应该列出两个模块。There should be two modules listed here. 一个模块是 SimulatedTemperatureSensor 模块,该模块默认包含在所有模板中,提供可用于测试模块的模拟温度数据。One is the SimulatedTemperatureSensor module, which is included in all the templates by default to provide simulated temperature data that you can use to test your modules. 另一个模块是作为此项目的一部分创建的 IotEdgeModule1 模块。The other is the IotEdgeModule1 module that you created as part of this project.

    此模块属性声明要将哪些模块包含到设备部署中。This modules property declares which modules should be included in the deployment to your device or devices.

  7. 找到 $edgeHub 所需属性的 routes 属性。Find the routes property of the $edgeHub desired properties.

    IoT Edge 中心模块的其中一个函数可在部署中的所有模块之间路由消息。One of the functions of the IoT Edge hub module is to route messages between all the modules in a deployment. 查看 routes 属性中的值。Review the values in the routes property. 一个路由 IotEdgeModule1ToIoTHub 使用通配符 (*) 将来自任何输出队列的任何消息包含到 IotEdgeModule1 模块中。One route, IotEdgeModule1ToIoTHub, uses a wildcard character (*) to include any message coming from any output queue in the IotEdgeModule1 module. 这些消息进入 $upstream,后者是指示 IoT 中心的保留名称。These messages go into $upstream, which is a reserved name that indicates IoT Hub. 第二个路由 sensorToIotEdgeModule1 接收来自 SimulatedTemperatureSensor 模块的消息,并将其路由到 IotEdgeModule1 模块的 input1 输入队列。The other route, sensorToIotEdgeModule1, takes messages coming from the SimulatedTemperatureSensor module and routes them to the input1 input queue of the IotEdgeModule1 module.

    查看 deployment.template.json 中的路由

生成并推送解决方案Build and push your solution

你已查看模块代码和部署模板来了解一些关键部署概念。You've reviewed the module code and the deployment template to understand some key deployment concepts. 现在,已准备好生成 IotEdgeModule1 容器映像并将其推送到容器注册表。Now, you're ready to build the IotEdgeModule1 container image and push it to your container registry. 借助适用于 Visual Studio 的 IoT Tools 扩展,此步骤还会根据模板文件中的信息和解决方案文件中的模块信息生成部署清单。With the IoT tools extension for Visual Studio, this step also generates the deployment manifest based on the information in the template file and the module information from the solution files.

登录 DockerSign in to Docker

向开发计算机上的 Docker 提供容器注册表凭据,以便它可以推送要存储在注册表中的容器映像。Provide your container registry credentials to Docker on your development machine so that it can push your container image to be stored in the registry.

  1. 打开 PowerShell 或命令提示符。Open PowerShell or a command prompt.

  2. 使用创建注册表后保存的 Azure 容器注册表凭据登录 Docker。Sign in to Docker with the Azure container registry credentials that you saved after creating the registry.

    docker login -u <ACR username> -p <ACR password> <ACR login server>
    

    可能会收到一条安全警告,推荐使用 --password-stdinYou may receive a security warning recommending the use of --password-stdin. 这条最佳做法是针对生产方案建议的,这超出了本教程的范畴。While that best practice is recommended for production scenarios, it's outside the scope of this tutorial. 有关详细信息,请参阅 docker login 参考。For more information, see the docker login reference.

生成并推送Build and push

开发计算机现在可以访问容器注册表,IoT Edge 设备也将拥有相应访问权限。Your development machine now has access to your container registry, and your IoT Edge devices will too. 现在可将项目代码转换为容器映像。It's time to turn the project code into a container image.

  1. 右键单击 CSharpTutorialApp 项目文件夹,然后选择“生成并推送 IoT Edge 模块” 。Right-click the CSharpTutorialApp project folder and select Build and Push IoT Edge Modules.

    生成并推送 IoT Edge 模块

    “生成并推送”命令会启动三项操作。The build and push command starts three operations. 首先,它在解决方案中创建名为 config 的新文件夹,用于保存基于部署模板和其他解决方案文件中的信息生成的完整部署清单。First, it creates a new folder in the solution called config that holds the full deployment manifest, built out of information in the deployment template and other solution files. 其次,它会运行 docker build,以基于目标体系结构的相应 dockerfile 生成容器映像。Second, it runs docker build to build the container image based on the appropriate dockerfile for your target architecture. 然后,它会运行 docker push,以将映像存储库推送到容器注册表。Then, it runs docker push to push the image repository to your container registry.

    首次执行此过程可能需要几分钟时间,但下次运行命令时速度会变快。This process may take several minutes the first time, but is faster the next time that you run the commands.

  2. 打开新建的 config 文件夹中的 deployment.windows-amd64.json 文件。Open the deployment.windows-amd64.json file in the newly created config folder. (config 文件夹可能不会在 Visual Studio 的解决方案资源管理器中显示。(The config folder may not appear in the Solution Explorer in Visual Studio. 如果遇到这种情况,请选择解决方案资源管理器任务栏中的显示所有文件图标。)If that's the case, select the Show all files icon in the Solution Explorer taskbar.)

  3. 找到 IotEdgeModule1 部分的 image 参数。Find the image parameter of the IotEdgeModule1 section. 请注意,该映像包含完整的映像存储库,以及 module.json 文件的名称、版本和体系结构标记。Notice that the image contains the full image repository with the name, version, and architecture tag from the module.json file.

  4. 打开 IotEdgeModule1 文件夹中的 module.json 文件。Open the module.json file in the IotEdgeModule1 folder.

  5. 更改模块映像的版本号。Change the version number for the module image. (版本,而不是 $schema-version。)例如,将补丁版本号递增为 0.0.2,就像我们对模块代码进行了小修补一样。(The version, not the $schema-version.) For example, increment the patch version number to 0.0.2 as though we had made a small fix in the module code.

    提示

    模块版本支持版本控制,允许在将更新部署到生产环境之前在少量设备上测试更改。Module versions enable version control, and allow you to test changes on a small set of devices before deploying updates to production. 如果在生成并推送之前未递增模块版本,则会替代容器注册表中的存储库。If you don't increment the module version before building and pushing, then you overwrite the repository in your container registry.

  6. 将更改保存到 module.json 文件。Save your changes to the module.json file.

  7. 再次右键单击“CSharpTutorialApp”项目文件夹,然后再次选择“生成并推送 IoT Edge 模块”。Right-click the CSharpTutorialApp project folder again, and select Build and Push IoT Edge Modules again.

  8. 再次打开 deployment.windows-amd64.json 文件。Open the deployment.windows-amd64.json file again. 请注意,再次运行“生成并推送”命令时未创建新文件,Notice that a new file wasn't created when you ran the build and push command again. 而是更新了同一文件以反映更改。Rather, the same file was updated to reflect the changes. IotEdgeModule1 映像现指向容器的 0.0.2 版。The IotEdgeModule1 image now points to the 0.0.2 version of the container. 部署清单中的此更改告知 IoT Edge 设备有要拉取的新模块版本。This change in the deployment manifest is how you tell the IoT Edge device that there's a new version of a module to pull.

  9. 若要进一步验证“生成并推送”命令执行的操作,请转到 Azure 门户并导航到容器注册表。To further verify what the build and push command did, go to the Azure portal and navigate to your container registry.

  10. 在容器注册表中,依次选择“存储库”和“iotedgemodule1” 。In your container registry, select Repositories then iotedgemodule1. 验证映像的两个版本是否都已推送到注册表。Verify that both versions of the image were pushed to the registry.

    在容器注册表中查看两个映像版本

疑难解答Troubleshoot

如果在生成并推送模块映像时遇到错误,这通常与开发计算机上的 Docker 配置有关。If you encounter errors when building and pushing your module image, it often has to do with Docker configuration on your development machine. 使用以下检查来检查配置:Use the following checks to review your configuration:

  • 是否使用从容器注册表复制的凭据运行 docker login 命令?Did you run the docker login command using the credentials that you copied from your container registry? 这些凭据与用于登录 Azure 的凭据不同。These credentials are different than the ones that you use to sign in to Azure.
  • 你的容器存储库是否正确?Is your container repository correct? 它是否拥有正确的容器注册表名称和正确的模块名称?Does it have your correct container registry name and your correct module name? 打开 IotEdgeModule1 文件夹中的 module.json 文件进行检查。Open the module.json file in the IotEdgeModule1 folder to check. 存储库值应类似于 <registry name>.azurecr.cn/iotedgemodule1。The repository value should look like <registry name>.azurecr.cn/iotedgemodule1.
  • 如果为模块使用的名称不是 IotEdgeModule1,那么使用的名称在整个解决方案中是否保持一致?If you used a different name than IotEdgeModule1 for your module, is that name consistent throughout the solution?
  • 计算机运行的容器类型与要生成的容器类型是否相同?Is your machine running the same type of containers that you're building? 本教程适用于 Windows IoT Edge 设备,因此,Visual Studio 文件应具有 windows-amd64 扩展名,且 Docker Desktop 应运行 Windows 容器。This tutorial is for Windows IoT Edge devices, so your Visual Studio files should have the windows-amd64 extension, and Docker Desktop should be running Windows containers.

将模块部署到设备Deploy modules to device

因为已确认生成的容器映像存储在容器注册表中,所以现在可将它们部署到设备中。You verified that the built container images are stored in your container registry, so it's time to deploy them to a device. 确保 IoT Edge 设备已启动并运行。Make sure that your IoT Edge device is up and running.

  1. 在 Visual Studio 中打开 Cloud Explorer 并展开 IoT 中心的详细信息。Open the Cloud Explorer in Visual Studio and expand the details for your IoT hub.

  2. 选择想要在其中部署的设备的名称。Select the name of the device that you want to deploy to. 在“操作”列表中,选择“创建部署” 。In the Actions list, select Create Deployment.

    为单个设备创建部署

  3. 在文件资源管理器中,导航到项目的 config 文件夹,然后选择 deployment.windows-amd64.json 文件。In the file explorer, navigate to the config folder of your project and select the deployment.windows-amd64.json file. 此文件通常位于 C:\Users\<username>\source\repos\CSharpTutorialApp\CSharpTutorialApp\config\deployment.windows-amd64.jsonThis file is often located at C:\Users\<username>\source\repos\CSharpTutorialApp\CSharpTutorialApp\config\deployment.windows-amd64.json

    不要使用 deployment.template.json 文件,该文件不包含完整的模块映像值。Do not use the deployment.template.json file, which doesn't have the full module image values in it.

  4. 在 Cloud Explorer 中展开 IoT Edge 设备的详细信息,以查看设备上的模块。Expand the details for your IoT Edge device in the Cloud Explorer to see the modules on your device.

  5. 使用“刷新”按钮更新设备状态,以查看 SimulatedTemperatureSensor 和 IotEdgeModule1 模块是否已部署到设备 。Use the Refresh button to update the device status to see that the SimulatedTemperatureSensor and IotEdgeModule1 modules are deployed your device.

    查看在 IoT Edge 设备上运行的模块

查看设备消息View messages from device

IotEdgeModule1 代码通过其输入队列接收消息,并通过其输出队列传递消息。The IotEdgeModule1 code receives messages through its input queue and passes them along through its output queue. 部署清单声明了将消息从 SimulatedTemperatureSensor 传递到 IotEdgeModule1,再将消息从 IotEdgeModule1 转发到 IoT 中心的路由。The deployment manifest declared routes that passed messages from SimulatedTemperatureSensor to IotEdgeModule1, and then forwarded messages from IotEdgeModule1 to IoT Hub. 适用于 Visual Studio 的 Azure IoT Edge Tools 允许查看从各个设备到达 IoT 中心的消息。The Azure IoT Edge tools for Visual Studio allow you to see messages as they arrive at IoT Hub from your individual devices.

  1. 在 Visual Studio Cloud Explorer 中,选择部署到其中的 IoT Edge 设备的名称。In the Visual Studio cloud explorer, select the name of the IoT Edge device that you deployed to.

  2. 在“操作”菜单中,选择“开始监视内置事件终结点”。In the Actions menu, select Start Monitoring Built-in Event Endpoint.

  3. 观察 Visual Studio 中的“输出”部分,以查看到达 IoT 中心的消息 。Watch the Output section in Visual Studio to see messages arriving at your IoT hub.

    启动两个模块可能需要数分钟时间。It may take a few minutes for both modules to start. IoT Edge 运行时需要接收其新的部署清单,从容器运行时下拉模块映像,然后启动每个新模块。The IoT Edge runtime needs to receive its new deployment manifest, pull down the module images from the container runtime, then start each new module.

    查看传入的设备到云消息

查看设备上的更改View changes on device

如果想要查看设备本身发生的情况,请使用本部分中的命令检查设备上运行的 IoT Edge 运行时和模块。If you want to see what's happening on your device itself, use the commands in this section to inspect the IoT Edge runtime and modules running on your device.

本部分中的命令适用于 IoT Edge 设备,而不适用于开发计算机。The commands in this section are for your IoT Edge device, not your development machine. 如果为 IoT Edge 设备使用虚拟机,请立即连接到虚拟机。If you're using a virtual machine for your IoT Edge device, connect to it now. 在 Azure 中,转到虚拟机的“概述”页,然后选择“连接”以访问远程桌面连接 。In Azure, go to the virtual machine's overview page and select Connect to access the remote desktop connection. 在设备上,打开命令或 PowerShell 窗口以运行 iotedge 命令。On the device, open a command or PowerShell window to run the iotedge commands.

  • 查看部署到设备的所有模块,并检查其状态:View all modules deployed to your device, and check their status:

    iotedge list
    

    应该看到四个模块:两个 IoT Edge 运行时模块、SimulatedTemperatureSensor 和 IotEdgeModule1。You should see four modules: the two IoT Edge runtime modules, SimulatedTemperatureSensor, and IotEdgeModule1. 全部四个模块都应列为“正在运行”。All four should be listed as running.

  • 检查特定模块的日志:Inspect the logs for a specific module:

    iotedge logs <module name>
    

    IoT Edge 模块区分大小写。IoT Edge modules are case-sensitive.

    SimulatedTemperatureSensor 和 IotEdgeModule1 日志应显示其正在处理的消息。The SimulatedTemperatureSensor and IotEdgeModule1 logs should show the messages they're processing. edgeAgent 模块负责启动其他模块,因此其日志将包含有关实施部署清单的信息。The edgeAgent module is responsible for starting the other modules, so its logs will have information about implementing the deployment manifest. 如果有任何模块未列出或未运行,则 edgeAgent 日志可能包含相关错误信息。If any module isn't listed or isn't running, the edgeAgent logs will probably have the errors. edgeHub 模块负责模块和 IoT 中心之间的通信。The edgeHub module is responsible for communications between the modules and IoT Hub. 如果模块已启动并运行,但消息未到达 IoT 中心,则 edgeHub 日志可能包含相关错误信息。If the modules are up and running, but the messages aren't arriving at your IoT hub, the edgeHub logs will probably have the errors.

清理资源Clean up resources

如果打算继续学习下一篇建议的文章,可以保留已创建的资源和配置,以便重复使用。If you plan to continue to the next recommended article, you can keep the resources and configurations that you created and reuse them. 还可以继续使用相同的 IoT Edge 设备作为测试设备。You can also keep using the same IoT Edge device as a test device.

否则,可以删除本文中使用的本地配置和 Azure 资源,以免产生费用。Otherwise, you can delete the local configurations and the Azure resources that you used in this article to avoid charges.

删除 Azure 资源Delete Azure resources

删除 Azure 资源和资源组的操作不可逆。Deleting Azure resources and resource groups is irreversible. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在现有的包含要保留资源的资源组中创建了 IoT 中心,请只删除 IoT 中心资源本身,而不要删除资源组。If you created the IoT hub inside an existing resource group that has resources that you want to keep, delete only the IoT hub resource itself, instead of deleting the resource group.

若要删除资源,请执行以下操作:To delete the resources:

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

  2. 选择包含 IoT Edge 测试资源的资源组的名称。Select the name of the resource group that contains your IoT Edge test resources.

  3. 查看包含在资源组中的资源的列表。Review the list of resources contained in your resource group. 若要删除这一切,可以选择“删除资源组”。 If you want to delete all of them, you can select Delete resource group. 如果只需删除部分内容,可以单击要单独删除的每个资源。If you want to delete only some of them, you can click into each resource to delete them individually.

后续步骤Next steps

在本教程中,在开发计算机上设置了 Visual Studio 2019 并从中部署了第一个 IoT Edge 模块。In this tutorial, you set up Visual Studio 2019 on your development machine and deployed your first IoT Edge module from it. 你已经了解基本概念,请尝试向模块添加功能,以便它可以分析通过它传递的数据。Now that you know the basic concepts, try adding functionality to a module so that it can analyze the data passing through it. 选择首选语言:Choose your preferred language:

C C#C C#