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

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

在快速入门文章中,你已使用 Linux 虚拟机创建了一个 IoT Edge 设备,并通过 Azure 市场部署了一个预生成的模块。In the quickstart articles, you created an IoT Edge device using a Linux 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 all the other tutorials, which will go into more detail about specific programming languages or Azure services.

本教程使用将 C# 模块部署到 Linux 设备的示例。This tutorial uses the example of deploying a C# module to a Linux device. 之所以选择此示例是因为它是 IoT Edge 解决方案中最常见的开发人员方案。This example was chosen because it is the most common developer scenario for IoT Edge solutions. 即使你计划使用其他语言或部署 Azure 服务,本教程仍然有助于了解开发工具和概念。Even if you plan on using a different language or deploying an Azure service, this tutorial is still useful to learn about the development tools and concepts. 在阅读开发过程的介绍后,你可以选择喜欢的语言或 Azure 服务来深入了解细节。After completing this introduction to the development process, 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 Code 的 IoT Edge Tools 创建新项目。Use the IoT Edge tools for Visual Studio Code 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 计算机上开发面向运行 IoT Edge 的 Linux 设备的模块。For example, the most common scenario is someone developing a module on a Windows computer intending to target a Linux device running IoT Edge. 在这种情况下,容器操作系统将是 Linux。In that case, the container operating system would be Linux. 在学习本教程的过程中,请注意开发计算机 OS 与容器 OS 之间的差异。 As you go through this tutorial, keep in mind the difference between the development machine OS and the container OS.

本教程面向运行 IoT Edge 的 Linux 设备。This tutorial targets Linux devices running IoT Edge. 只要开发计算机可以运行 Linux 容器,就可以使用首选操作系统。You can use your preferred operating system, as long as your development machine can run Linux containers. 我们建议使用 Visual Studio Code 对 Linux 设备进行开发,而本教程也正是使用此工具。We recommend using Visual Studio Code to develop for Linux devices, so that's what this tutorial will use. 还可以使用 Visual Studio,但这两个工具提供的支持存在差异。You can use Visual Studio as well, although there are differences in support between the two tools.

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

Visual Studio CodeVisual Studio Code Visual Studio 2017/2019Visual Studio 2017/2019
Linux 设备体系结构Linux device architecture Linux AMD64Linux AMD64
Linux ARM32Linux ARM32
Linux AMD64Linux AMD64
Linux ARM32Linux ARM32
Azure 服务Azure services Azure FunctionsAzure Functions
Azure 流分析Azure Stream Analytics
Azure 机器学习Azure Machine Learning
语言Languages CC
C#C#
JavaJava
Node.jsNode.js
PythonPython
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

本教程将会讲解 Visual Studio Code 的开发步骤。This tutorial teaches the development steps for Visual Studio Code. 如果想要使用 Visual Studio,请参阅使用 Visual Studio 2019 为 Azure IoT Edge 开发和调试模块中的说明。If you would rather use Visual Studio, refer to the instructions in Use Visual Studio 2019 to develop and debug modules for Azure IoT Edge.

先决条件Prerequisites

一台开发计算机:A development machine:

  • 可以根据开发偏好,使用自己的计算机或虚拟机。You can use your own computer or a virtual machine, depending on your development preferences.
  • 大多数可以运行容器引擎的操作系统都可用于开发 Linux 设备的 IoT Edge 模块。Most operating systems that can run a container engine can be used to develop IoT Edge modules for Linux devices. 本教程使用 Windows 计算机,但会指出 MacOS 或 Linux 上的已知差异。This tutorial uses a Windows computer, but points out known differences on MacOS or Linux.
  • 安装 Git,用于稍后在本教程中提取模块模板包。Install Git, to pull module template packages later in this tutorial.
  • 适用于 Visual Studio Code 的 C# 扩展(由 OmniSharp 提供支持)C# for Visual Studio Code (powered by OmniSharp) extension.
  • .NET Core 2.1 SDK.NET Core 2.1 SDK.

Linux 上的一个 Azure IoT Edge 设备:An Azure IoT Edge device on Linux:

  • 我们建议不要在开发计算机上运行 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.
  • 如果没有另一个可用的设备,请参考快速入门文章使用 Linux 虚拟机在 Azure 中创建一个 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 Linux 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 device, 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:

设置 VS Code 和工具Set up VS Code and tools

使用适用于 Visual Studio Code 的 IoT 扩展来开发 IoT Edge 模块。Use the IoT extensions for Visual Studio Code 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 Code 和 IoT 扩展,然后设置 Azure 帐户以从 Visual Studio Code 内部管理 IoT 中心资源。In this section, you install Visual Studio Code and the IoT extension, then set up your Azure account to manage IoT Hub resources from within Visual Studio Code.

  1. 在开发计算机上安装 Visual Studio CodeInstall Visual Studio Code on your development machine.

  2. 安装完成后,选择“视图” > “扩展”。 Once the installation is finished, select View > Extensions.

  3. 搜索 Azure IoT Tools,它实际上是一系列的扩展,可帮助你与 IoT 中心和 IoT 设备交互,以及开发 IoT Edge 模块。Search for Azure IoT Tools, which is actually a collection of extensions that help you interact with IoT Hub and IoT devices, as well as developing IoT Edge modules.

  4. 选择“安装” 。Select Install. 包含的每个扩展会单独安装。Each included extension installs individually.

  5. 扩展安装完成后,选择“视图” > “命令面板”打开命令面板。 When the extensions are done installing, open the command palette by selecting View > Command Palette.

  6. 在命令面板中,搜索并选择 Azure:Sign in 命令。In the command palette, search for and select Azure: Sign in. 根据提示登录到 Azure 帐户。Follow the prompts to sign in to your Azure account.

  7. 返回命令面板,搜索并选择 Azure IoT Hub:Select IoT Hub 命令。In the command palette again, search for and select Azure IoT Hub: Select IoT Hub. 遵照提示选择 Azure 订阅和 IoT 中心。Follow the prompts to select your Azure subscription and IoT hub.

  8. 打开 Visual Studio Code 的“资源管理器”部分:在左侧的活动栏中选择相应的图标,或选择“视图” > “资源管理器”。 Open the explorer section of Visual Studio Code by either selecting the icon in the activity bar on the left, or by selecting View > Explorer.

  9. 在“资源管理器”部分的底部,展开已折叠的“Azure IoT 中心设备”菜单。 At the bottom of the explorer section, expand the collapsed Azure IoT Hub Devices menu. 应会看到上述设备,以及与通过命令面板选择的 IoT 中心相关联的 IoT Edge 设备。You should see the devices and IoT Edge devices associated with the IoT hub that you selected through the command palette.

    在 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 then select Access keys.

  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 Tools 扩展为 Visual Studio Code 中支持的所有 IoT Edge 模块语言提供项目模板。The Azure IoT Tools extension provides project templates for all supported IoT Edge module languages in Visual Studio Code. 这些模板包含将工作模块部署到测试 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.

本教程使用 C# 模块模板,因为它是最常用的模板。For this tutorial, we use the C# module template because it is the most commonly used template.

创建项目模板Create a project template

在 Visual Studio Code 命令面板中,搜索并选择 Azure IoT Edge: New IoT Edge Solution 命令。In the Visual Studio Code command palette, search for and select Azure IoT Edge: New IoT Edge Solution. 遵照提示操作,并使用以下值创建解决方案:Follow the prompts and use the following values to create your solution:

字段Field Value
选择文件夹Select folder 在适用于 VS Code 的开发计算机上选择用于创建解决方案文件的位置。Choose the location on your development machine for VS Code to create the solution files.
提供解决方案名称Provide a solution name 输入解决方案的描述性名称,或者接受默认的 EdgeSolutionEnter a descriptive name for your solution or accept the default EdgeSolution.
选择模块模板Select module template 选择“C# 模块”。 Choose C# Module.
提供模块名称Provide a module name 接受默认值“SampleModule”。 Accept the default SampleModule.
为模块提供 Docker 映像存储库Provide Docker image repository for the module 映像存储库包含容器注册表的名称和容器映像的名称。An image repository includes the name of your container registry and the name of your container image. 容器映像是基于你在上一步中提供的名称预先填充的。Your container image is prepopulated from the name you provided in the last step. localhost:5000 替换为 Azure 容器注册表中的登录服务器值。Replace localhost:5000 with the login server value from your Azure container registry. 可以在 Azure 门户的容器注册表的“概览”页中检索登录服务器。You can retrieve the login server from the Overview page of your container registry in the Azure portal.

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

提供 Docker 映像存储库

新解决方案载入到 Visual Studio Code 窗口中后,请花费片刻时间来熟悉它所创建的文件:Once your new solution loads in the Visual Studio Code window, take a moment to familiarize yourself with the files that it created:

  • .vscode 文件夹包含用于调试模块的名为 launch.json 的文件。The .vscode folder contains a file called launch.json, which is used for debugging modules.

  • modules 文件夹针对解决方案中的每个模块包含一个文件夹。The modules folder contains a folder for each module in your solution. 目前,应该只存在 SampleModule(或为模块指定的任何名称)文件夹。Right now, that should only be SampleModule, or whatever name you gave to the module. SampleModule 文件夹包含主要程序代码、模块元数据和多个 Docker 文件。The SampleModule folder contains the main program code, the module metadata, and several Docker files.

  • .env 文件保存容器注册表的凭据。The .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.debug.template.json 文件和 deployment.template.json 文件是帮助你创建部署清单的模板。The deployment.debug.template.json file and deployment.template.json file are templates that 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. 模板文件使用某些值的指针。The template files use pointers for some values. 将模板转换为真实的部署清单时,指针将替换为取自其他解决方案文件的值。When you transform the template into a true deployment manifest, the pointers are replaced with values taken from other solution files. 在部署模板中找到两个常见的占位符:Locate the two common placeholders in your deployment template:

    • 在注册表凭据节中,地址是根据你在创建解决方案时提供的信息自动填充的。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 the variables stored in the .env file. 这是出于安全目的,因为 git 会忽略 .env 文件,但不会忽略部署模板。This is for security, as the .env file is git ignored, but the deployment template is not.
    • 在 SampleModule 节中,即使创建解决方案时提供了映像存储库,也不会填充容器映像。In the SampleModule section, the container image isn't filled in even though you provided the image repository when you created the solution. 此占位符指向 SampleModule 文件夹中的 module.json 文件。This placeholder points to the module.json file inside the SampleModule folder. 如果转到该文件,将会看到映像字段中确实包含了存储库,但同时还有一个由容器版本和平台构成的标记值。If you go to that file, you'll see that the image field does contain the repository, but also a tag value that is made up of the version and the platform of the container. 可以在开发周期中手动迭代版本,并使用本部分稍后将会介绍的切换器来选择容器平台。You can iterate the version manually as part of your development cycle, and you select the container platform using a switcher that we introduce later in this section.

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

环境文件存储容器注册表的凭据,并将其与 IoT Edge 运行时共享。The environment file stores the credentials for your container registry and shares them with the IoT Edge runtime. 该运行时需要这些凭据才能将容器映像提取到 IoT Edge 设备中。The runtime needs these credentials to pull your container images onto the IoT Edge device.

IoT Edge 扩展尝试从 Azure 提取容器注册表凭据,并将其填充到环境文件中。The IoT Edge extension tries to pull your container registry credentials from Azure and populate them in the environment file. 请检查是否已包含你的凭据。Check to see if your credentials are already included. 如果未包含,现在请添加这些凭据:If not, add them now:

  1. 在模块解决方案中打开 .env 文件。Open the .env file in your module solution.
  2. 添加从 Azure 容器注册表复制的 usernamepassword 值。Add the username and password values that you copied from your Azure container registry.
  3. 保存对 .env 文件所做的更改。Save your changes to the .env file.

选择目标体系结构Select your target architecture

目前,Visual Studio Code 可以为 Linux AMD64 和 ARM32v7 设备开发 C# 模块。Currently, Visual Studio Code can develop C# modules for Linux AMD64 and ARM32v7 devices. 需要选择面向每个解决方案的体系结构,因为这会影响容器的生成和运行方式。You need to select which architecture you're targeting with each solution, because that affects how the container is built and runs. 默认设置为 Linux AMD64。The default is Linux AMD64.

  1. 打开命令面板并搜索 Azure IoT Edge:Set Default Target Platform for Edge Solution,或者选择窗口底部边栏中的快捷方式图标。Open the command palette and search for Azure IoT Edge: Set Default Target Platform for Edge Solution, or select the shortcut icon in the side bar at the bottom of the window.

    在边栏中选择体系结构图标

  2. 在命令面板中,从选项列表中选择目标体系结构。In the command palette, select the target architecture from the list of options. 本教程将使用 Ubuntu 虚拟机作为 IoT Edge 设备,因此将保留默认设置 amd64For this tutorial, we're using an Ubuntu virtual machine as the IoT Edge device, so will keep the default amd64.

查看示例代码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 language 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 Hub 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 文件,该文件位于 modules/SampleModule/ 文件夹中。Open the Program.cs file, which is inside the modules/SampleModule/ folder.

  2. 在 program.cs 中,找到 SetInputMessageHandlerAsync 方法。In program.cs, find the SetInputMessageHandlerAsync method.

  3. 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.

    在 SetInputMessageCallback 构造函数中查找输入名称

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

  5. 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.

    在 SendEventToOutputAsync 中查找输出名称

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

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

    此处应会列出两个模块。There should be two modules listed here. 第一个模块是 SimulatedTemperatureSensor,该模块默认包含在所有模板中,提供可用于测试模块的模拟温度数据。The first is SimulatedTemperatureSensor, which is included in all the templates by default to provide simulated temperature data that you can use to test your modules. 第二个模块是在创建此解决方案过程中创建的 SampleModule 模块。The second is the SampleModule module that you created as part of this solution.

  8. 在文件底部,找到 $edgeHub 模块的所需属性。At the bottom of the file, find the desired properties for the $edgeHub module.

    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. 第一个路由 SampleModuleToIoTHub 使用通配符 ( * ) 指示 SampleModule 模块中的任何输出队列传出的任何消息。The first route, SampleModuleToIoTHub, uses a wildcard character (*) to indicate any messages coming from any output queues in the SampleModule module. 这些消息进入 $upstream(用于指示 IoT 中心的保留名称)。These messages go into $upstream, which is a reserved name that indicates IoT Hub. 第二个路由 sensorToSampleModule 接收来自 SimulatedTemperatureSensor 模块的消息,并将它们路由到在 SampleModule 代码中初始化的 input1 输入队列。The second route, sensorToSampleModule, takes messages coming from the SimulatedTemperatureSensor module and routes them to the input1 input queue that you saw initialized in the SampleModule code.

    在 deployment.template.json 中查看路由

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

现已查看模块代码和部署模板,并了解了一些重要的部署概念。You've reviewed the module code and the deployment template to understand some key deployment concepts. 接下来,可以生成 SampleModule 容器映像并将其推送到容器注册表。Now, you're ready to build the SampleModule container image and push it to your container registry. 使用适用于 Visual Studio Code 的 IoT Tools 扩展时,此步骤还会基于模板文件中的信息以及解决方案文件中的模块信息生成部署清单。With the IoT tools extension for Visual Studio Code, 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 so that it can push your container image to be stored in the registry.

  1. 选择“视图” > “终端”,打开 Visual Studio Code 集成终端。 Open the Visual Studio Code integrated terminal by selecting View > Terminal.

  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

Visual Studio Code 现在有权访问你的容器注册表。接下来,可将解决方案代码转换为容器映像。Visual Studio Code now has access to your container registry, so it's time to turn the solution code into a container image.

  1. 在 Visual Studio Code 资源管理器中右键单击“deployment.template.json”文件,然后选择“生成并推送 IoT Edge 解决方案”。 In the Visual Studio Code explorer, right-click the deployment.template.json file and select Build and Push IoT Edge Solution.

    生成并推送 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.amd64.json 文件。Open the deployment.amd64.json file in newly created config folder. 文件名反映了目标体系结构,因此,如果选择了不同的体系结构,则文件名会不相同。The filename reflects the target architecture, so it will be different if you chose a different architecture.

  3. 请注意,两个参数的占位符现已填充了适当的值。Notice that the two parameters that had placeholders now are filled in with their proper values. registryCredentials 节包含从 .env 文件提取的注册表用户名和密码。The registryCredentials section has your registry username and password pulled from the .env file. SampleModule 包含完整的映像存储库,其中附带了来自 module.json 文件的名称、版本和体系结构标记。The SampleModule has the full image repository with the name, version, and architecture tag from the module.json file.

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

  5. 更改模块映像的版本号。Change the version number for the module image. (是 version 而不是 $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.

    Tip

    模块版本启用版本控制,并可让你在将更新部署到生产环境之前,在少量的设备上测试更改。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. 再次右键单击“deployment.template.json”文件,并选择“生成并推送 IoT Edge 解决方案”。 Right-click the deployment.template.json file again, and again select Build and Push IoT Edge Solution.

  8. 再次打开 deployment.amd64.json 文件。Open the deployment.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. SampleModule 映像现在指向容器的版本 0.0.2。The SampleModule image now points to the 0.0.2 version of the container.

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

  10. 在该容器注册表中,依次选择“存储库”、“samplemodule”。 In your container registry, select Repositories then samplemodule. 验证映像的两个版本是否已推送到注册表。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? 打开 SampleModule 文件夹中的 module.json 文件进行检查。Open the module.json file in the SampleModule folder to check. 存储库值应类似于 <注册表名称>.azurecr.cn/samplemoduleThe repository value should look like <registry name>.azurecr.cn/samplemodule.
  • 如果为模块使用的名称不是 SampleModule,使用的名称是否在整个解决方案中一致?If you used a different name than SampleModule for your module, is that name consistent throughout the solution?
  • 计算机运行的容器是否与正在生成的容器的类型相同?Is your machine running the same type of containers that you're building? 本教程适用于 Linux IoT Edge 设备,因此,Visual Studio Code 应会在边栏中显示 amd64arm32v7,并且 Docker Desktop 应运行 Linux 容器。This tutorial is for Linux IoT Edge devices, so Visual Studio Code should say amd64 or arm32v7 in the side bar, and Docker Desktop should be running Linux 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 Code 资源管理器中,展开“Azure IoT 中心设备”部分。In the Visual Studio Code explorer, expand the Azure IoT Hub Devices section.

  2. 右键单击要部署到的 IoT Edge 设备,然后选择“为单个设备创建部署”。 Right-click the IoT Edge device that you want to deploy to, then select Create Deployment for Single Device.

    为单个设备创建部署

  3. 在文件资源管理器,导航到 config 文件夹,然后选择 deployment.amd64.json 文件。In the file explorer, navigate into the config folder then select the deployment.amd64.json file.

    不要使用 deployment.template.json 文件,因为其中不包含容器注册表凭据或模块映像值。Do not use the deployment.template.json file, which doesn't have the container registry credentials or module image values in it. 如果面向 Linux ARM32 设备,则部署清单将命名为 deployment.arm32v7.json。If you're targeting a Linux ARM32 device, the deployment manifest will be named deployment.arm32v7.json.

  4. 展开 IoT Edge 设备的详细信息,然后展开设备的“模块”列表。 Expand the details for your IoT Edge device, then expand the Modules list for your device.

  5. 使用“刷新”按钮更新设备视图,直至看到设备上运行 SimulatedTemperatureSensor 和 SampleModule 模块。Use the refresh button to update the device view until you see the SimulatedTemperatureSensor and SampleModule modules running on your device.

    启动这两个模块可能需要几分钟时间。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.

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

查看来自设备的消息View messages from device

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

  1. 在 Visual Studio Code 资源管理器中,右键单击想要监视的 IoT Edge 设备,然后选择“开始监视内置事件终结点” 。In the Visual Studio Code explorer, right-click the IoT Edge device that you want to monitor, then select Start Monitoring Built-in Event Endpoint.

  2. 观察 Visual Studio Code 中的输出窗口,以查看抵达 IoT 中心的消息。Watch the output window in Visual Studio Code to see messages arriving at your IoT hub.

    查看传入的设备到云消息

查看设备上的更改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 secure shell connection.

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

    iotedge list
    

    应该看到四个模块:两个 IoT Edge 运行时模块、SimulatedTemperatureSensor 和 SampleModule。You should see four modules: the two IoT Edge runtime modules, SimulatedTemperatureSensor, and SampleModule. 所有四个模块应列为“正在运行”。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 和 SampleModule 日志应显示其正在处理的消息。The SimulatedTemperatureSensor and SampleModule 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.

后续步骤Next steps

在本教程中,你已在开发计算机上安装了 Visual Studio Code 并从中部署了第一个 IoT Edge 模块。In this tutorial, you set up Visual Studio Code 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: