教程:为 Linux 设备开发并部署 Python IoT Edge 模块Tutorial: Develop and deploy a Python IoT Edge module for Linux devices

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

可以使用 Azure IoT Edge 模块部署代码,直接将业务逻辑实现到 IoT Edge 设备。You can use Azure IoT Edge modules to deploy code that implements your business logic directly to your IoT Edge devices. 本教程将引导你在 IoT Edge 设备(已在快速入门中设置)上创建和部署用于筛选传感器数据的 IoT Edge 模块。This tutorial walks you through creating and deploying an IoT Edge module that filters sensor data on the IoT Edge device that you set up in the quickstart. 本教程介绍如何执行下列操作:In this tutorial, you learn how to:

  • 使用 Visual Studio Code 创建 IoT Edge Python 模块。Use Visual Studio Code to create an IoT Edge Python module.
  • 使用 Visual Studio Code 和 Docker 创建 Docker 映像并将其发布到注册表。Use Visual Studio Code and Docker to create a Docker image and publish it to your registry.
  • 将模块部署到 IoT Edge 设备。Deploy the module to your IoT Edge device.
  • 查看生成的数据。View generated data.

在本教程中创建的 IoT Edge 模块可以筛选由设备生成的温度数据。The IoT Edge module that you create in this tutorial filters the temperature data that's generated by your device. 它只在温度高于指定阈值的情况下,向上游发送消息。It only sends messages upstream if the temperature is above a specified threshold. 在边缘进行的此类分析适用于减少传递到云中和存储在云中的数据量。This type of analysis at the edge is useful for reducing the amount of data that's communicated to and stored in the cloud.

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

解决方案范围Solution scope

本教程演示如何使用 Visual Studio CodePython 开发模块,以及如何将其部署到 Linux 设备This tutorial demonstrates how to develop a module in Python using Visual Studio Code, and how to deploy it to a Linux device. IoT Edge 不支持 Windows 设备的 Python 模块。IoT Edge does not support Python modules for Windows devices.

使用下表了解用于开发 Python 模块并将其部署到 Linux 的选项:Use the following table to understand your options for developing and deploying Python modules to Linux:

PythonPython Visual Studio CodeVisual Studio Code Visual Studio 2017/2019Visual Studio 2017/2019
Linux AMD64Linux AMD64 将 VS Code 用于 Linux AMD64 上的 Python 模块
Linux ARM32Linux ARM32 将 VS Code 用于 Linux ARM32 上的 Python 模块


在开始学习本教程之前,应已完成上一篇教程来设置用于开发 Linux 容器的开发环境:开发适用于 Linux 设备的 IoT Edge 模块Before beginning this tutorial, you should have gone through the previous tutorial to set up your development environment for Linux container development: Develop IoT Edge modules for Linux devices. 完成该教程后,已应准备好以下必备组件:By completing that tutorial, you should have the following prerequisites in place:

若要开发以 Python 编写的 IoT Edge 模块,请在开发计算机上安装下述额外的必备组件:To develop an IoT Edge module in Python, install the following additional prerequisites on your development machine:

  • 适用于 Visual Studio Code 的 Python 扩展Python extension for Visual Studio Code.
  • PythonPython.
  • Pip 用于安装 Python 包(通常包含在 Python 安装中)。Pip for installing Python packages (typically included with your Python installation).


确保 bin 文件夹在平台的路径中。Ensure that your bin folder is on your path for your platform. 通常为 ~/.local/(针对 UNIX 和 macOS)或 %APPDATA%\Python(针对 Windows)。Typically ~/.local/ for UNIX and macOS, or %APPDATA%\Python on Windows.

创建模块项目Create a module project

以下步骤使用 Visual Studio Code 和 Azure IoT 工具创建 IoT Edge Python 模块。The following steps create an IoT Edge Python module by using Visual Studio Code and the Azure IoT Tools.

创建新项目Create a new project

使用 VS Code 创建一个 Python 解决方案模板,以便在其上生成项目。Use the VS Code to create a Python solution template that you can build on top of.

  1. 在 Visual Studio Code 中选择“视图” > “终端”,打开 VS Code 集成终端。In Visual Studio Code, select View > Terminal to open the VS Code integrated terminal.

  2. 选择“视图” > “命令面板”,打开 VS Code 命令面板。Select View > Command Palette to open the VS Code command palette.

  3. 在命令面板中,输入并运行命令“Azure: Sign in 命令并按照说明登录到 Azure 帐户。In the command palette, enter and run the command Azure: Sign in and follow the instructions to sign in your Azure account. 如果已登录,则可跳过此步骤。If you're already signed in, you can skip this step.

  4. 在“命令面板”中,输入并运行 Azure IoT Edge:New IoT Edge solution 命令。In the command palette, enter and run the command Azure IoT Edge: New IoT Edge solution. 按提示操作,提供以下信息,以便创建解决方案:Follow the prompts and provide the following information to create your solution:

    字段Field ValueValue
    选择文件夹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 选择“Python 模块”。 Choose Python Module.
    提供模块名称Provide a module name 将模块命名为 PythonModuleName your module PythonModule.
    为模块提供 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/pythonmodule。The final image repository looks like <registry name>.azurecr.cn/pythonmodule.

    提供 Docker 映像存储库

添加注册表凭据Add your registry credentials

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

  1. 在 VS Code 资源管理器中,打开 .env 文件。In the VS Code explorer, open the .env file.
  2. 使用从 Azure 容器注册表复制的 usernamepassword 值更新相关字段。Update the fields with the username and password values that you copied from your Azure container registry.
  3. 保存 .env 文件。Save the .env file.

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

目前,Visual Studio Code 可以为 Linux AMD64 和 Linux ARM32v7 设备开发 Python 模块。Currently, Visual Studio Code can develop Python modules for Linux AMD64 and Linux ARM32v7 devices. 需要选择面向每个解决方案的体系结构,因为每种体系结构类型的容器的生成和运行方式均不相同。You need to select which architecture you're targeting with each solution, because the container is built and run differently for each architecture type. 默认设置为 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.

使用自定义代码更新模块Update the module with custom code

每个模板都包含示例代码,该代码从 SimulatedTemperatureSensor 模块提取模拟传感器数据并将其路由到 IoT 中心。Each template includes sample code, which takes simulated sensor data from the SimulatedTemperatureSensor module and routes it to the IoT hub. 在此节中,请添加代码,以便扩展用于分析消息的 PythonModule,然后再发送它们。In this section, add the code that expands the PythonModule to analyze the messages before sending them.

  1. 在 VS Code 资源管理器中,打开 modules > PythonModule > main.pyIn the VS Code explorer, open modules > PythonModule > main.py.

  2. main.py 文件顶部导入 json 库。At the top of the main.py file, import the json library:

    import json
  3. 在全局计数器下添加 TEMPERATURE_THRESHOLDTWIN_CALLBACKS 变量。Add the TEMPERATURE_THRESHOLD and TWIN_CALLBACKS variables under the global counters. 温度阈值设置一个值,若要向 IoT 中心发送数据,测量的计算机温度必须超出该值。The temperature threshold sets the value that the measured machine temperature must exceed for the data to be sent to the IoT hub.

    # global counters
  4. input1_listener 函数替换为以下代码:Replace the input1_listener function with the following code:

        # Define behavior for receiving an input message on input1
        # Because this is a filter module, we forward this message to the "output1" queue.
        async def input1_listener(module_client):
            global RECEIVED_MESSAGES
            global TEMPERATURE_THRESHOLD
            while True:
                    input_message = await module_client.receive_message_on_input("input1")  # blocking call
                    message = input_message.data
                    size = len(message)
                    message_text = message.decode('utf-8')
                    print ( "    Data: <<<%s>>> & Size=%d" % (message_text, size) )
                    custom_properties = input_message.custom_properties
                    print ( "    Properties: %s" % custom_properties )
                    RECEIVED_MESSAGES += 1
                    print ( "    Total messages received: %d" % RECEIVED_MESSAGES )
                    data = json.loads(message_text)
                    if "machine" in data and "temperature" in data["machine"] and data["machine"]["temperature"] > TEMPERATURE_THRESHOLD:
                        custom_properties["MessageType"] = "Alert"
                        print ( "Machine temperature %s exceeds threshold %s" % (data["machine"]["temperature"], TEMPERATURE_THRESHOLD))
                        await module_client.send_message_to_output(input_message, "output1")
                except Exception as ex:
                    print ( "Unexpected error in input1_listener: %s" % ex )
        # twin_patch_listener is invoked when the module twin's desired properties are updated.
        async def twin_patch_listener(module_client):
            global TWIN_CALLBACKS
            global TEMPERATURE_THRESHOLD
            while True:
                    data = await module_client.receive_twin_desired_properties_patch()  # blocking call
                    print( "The data in the desired properties patch was: %s" % data)
                    if "TemperatureThreshold" in data:
                        TEMPERATURE_THRESHOLD = data["TemperatureThreshold"]
                    TWIN_CALLBACKS += 1
                    print ( "Total calls confirmed: %d\n" % TWIN_CALLBACKS )
                except Exception as ex:
                    print ( "Unexpected error in twin_patch_listener: %s" % ex )
  5. 更新侦听器以同时侦听孪生更新。Update the listeners to also listen twin updates.

        # Schedule task for C2D Listener
        listeners = asyncio.gather(input1_listener(module_client), twin_patch_listener(module_client))
        print ( "The sample is now waiting for messages. ")
  6. 保存 main.py 文件。Save the main.py file.

  7. 在 VS Code 资源管理器的 IoT Edge 解决方案工作区中打开 deployment.template.json 文件。In the VS Code explorer, open the deployment.template.json file in your IoT Edge solution workspace.

  8. PythonModule 模块孪生添加到部署清单。Add the PythonModule module twin to the deployment manifest. moduleContent 节底部的 $edgeHub 模块孪生后面插入以下 JSON 内容:Insert the following JSON content at the bottom of the moduleContent section, after the $edgeHub module twin:

        "PythonModule": {


  9. 保存 deployment.template.json 文件。Save the deployment.template.json file.

生成并推送模块Build and push your module

在上一部分,你已经创建了一个 IoT Edge 解决方案并将代码添加到了 PythonModule,该函数会筛选出其中报告的计算机温度处于可接受范围内的消息。In the previous section, you created an IoT Edge solution and added code to the PythonModule that will filter out messages where the reported machine temperature is within the acceptable limits. 现在需将解决方案生成为容器映像并将其推送到容器注册表。Now you need to build the solution as a container image and push it to your container registry.

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

  2. 在终端中输入以下命令,以登录到 Docker。Sign in to Docker by entering the following command in the terminal. 使用 Azure 容器注册表中的用户名、密码和登录服务器登录。Sign in with the username, password, and login server from your Azure container registry. 可以在 Azure 门户中从注册表的“访问密钥”部分检索这些值。 You can retrieve these values from the Access keys section of your registry in the Azure portal.

    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.

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

    “生成并推送”命令会启动三项操作。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.

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

使用 Visual Studio Code 资源管理器和 Azure IoT Tools 扩展将模块项目部署到 IoT Edge 设备。Use the Visual Studio Code explorer and the Azure IoT Tools extension to deploy the module project to your IoT Edge device. 你已经为方案准备了部署清单,即 config 文件夹中的 deployment.json 文件。You already have a deployment manifest prepared for your scenario, the deployment.json file in the config folder. 现在需要做的就是选择一个设备来接收部署。All you need to do now is select a device to receive the deployment.

请确保 IoT Edge 设备已启动并正在运行。Make sure that your IoT Edge device is up and running.

  1. 在 Visual Studio Code 资源管理器中展开“Azure IoT 中心设备”部分,查看 IoT 设备的列表。 In the Visual Studio Code explorer, expand the Azure IoT Hub Devices section to see your list of IoT devices.

  2. 右键单击 IoT Edge 设备的名称,然后选择“为单个设备创建部署”。 Right-click the name of your IoT Edge device, then select Create Deployment for Single Device.

  3. 选择 config 文件夹中的 deployment.json 文件,然后单击“选择 Edge 部署清单”。 Select the deployment.json file in the config folder and then click Select Edge Deployment Manifest. 不要使用 deployment.template.json 文件。Do not use the deployment.template.json file.

  4. 单击“刷新”按钮。Click the refresh button. 此时应看到新的 PythonModuleSimulatedTemperatureSensor 模块以及 $edgeAgent$edgeHub 一起运行。You should see the new PythonModule running along with the SimulatedTemperatureSensor module and the $edgeAgent and $edgeHub.

查看生成的数据View The generated data

将部署清单应用到 IoT Edge 设备以后,设备上的 IoT Edge 运行时就会收集新的部署信息并开始在其上执行操作。Once you apply the deployment manifest to your IoT Edge device, the IoT Edge runtime on the device collects the new deployment information and starts executing on it. 在设备上运行的未包括在部署清单中的任何模块都会停止。Any modules running on the device that aren't included in the deployment manifest are stopped. 设备中缺失的任何模块都会启动。Any modules missing from the device are started.

可以通过 Visual Studio Code 资源管理器的“Azure IoT 中心设备”部分查看 IoT Edge 设备的状态 。You can view the status of your IoT Edge device using the Azure IoT Hub Devices section of the Visual Studio Code explorer. 展开设备的详细信息,可以看到已部署的正在运行的模块的列表。Expand the details of your device to see a list of deployed and running modules.

  1. 在 Visual Studio Code 资源管理器中右键单击 IoT Edge 设备的名称,选择“开始监视内置事件终结点”。 In the Visual Studio Code explorer, right-click the name of your IoT Edge device and select Start Monitoring Built-in Event Endpoint.

  2. 查看抵达 IoT 中心的消息。View the messages arriving at your IoT Hub. 消息到达可能需要一段时间。It may take a while for the messages to arrive. IoT Edge 设备必须接收其新部署并启动所有模块。The IoT Edge device has to receive its new deployment and start all the modules. 然后,在发送消息之前,我们对 PythonModule 代码所做的更改需等到机器温度达到 25 度才会生效。Then, the changes we made to the PythonModule code wait until the machine temperature reaches 25 degrees before sending messages. IoT 中心还会将消息类型“警报”添加到达到该温度阈值的任何消息。 It also adds the message type Alert to any messages that reach that temperature threshold.

编辑模块孪生Edit the module twin

我们已使用部署清单中的 PythonModule 模块孪生将温度阈值设置为 25 度。We used the PythonModule module twin in the deployment manifest to set the temperature threshold at 25 degrees. 可以使用模块孪生来更改功能,而无需更新模块代码。You can use the module twin to change the functionality without having to update the module code.

  1. 在 Visual Studio Code 中,展开 IoT Edge 设备下的详细信息即可查看运行的模块。In Visual Studio Code, expand the details under your IoT Edge device to see the running modules.

  2. 右键单击 PythonModule,然后选择“编辑模块孪生”。 Right-click PythonModule and select Edit module twin.

  3. 在所需属性中找到 TemperatureThresholdFind TemperatureThreshold in the desired properties. 将其值更改为比上次报告的温度高出 5 到 10 度的新温度。Change its value to a new temperature 5 degrees to 10 degrees higher than the latest reported temperature.

  4. 保存模块孪生文件。Save the module twin file.

  5. 右键单击模块孪生编辑窗格中的任意位置,然后选择“更新模块孪生”。 Right-click anywhere in the module twin editing pane and select Update module twin.

  6. 监视传入的设备到云消息。Monitor the incoming device-to-cloud messages. 应会看到,在达到新的温度阈值之前,消息会停止发送。You should see the messages stop until the new temperature threshold is reached.

清理资源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

在本教程中,创建了 IoT Edge 模块,其中包含用于筛选 IoT Edge 设备生成的原始数据的代码。In this tutorial, you created an IoT Edge module that contains code to filter raw data generated by your IoT Edge device. 准备好生成自己的模块时,可以详细了解如何开发自己的 IoT Edge 模块或如何使用 Visual Studio Code 开发模块When you're ready to build your own modules, you can learn more about developing your own IoT Edge modules or how to develop modules with Visual Studio Code. 有关 IoT Edge 模块的示例,包括模拟温度模块,请参阅 IoT Edge 模块示例IoT Python SDK 示例For examples of IoT Edge modules, including the simulated temperature module, see IoT Edge module samples and IoT Python SDK samples.

可以继续学习后续教程,了解 Azure IoT Edge 如何帮助你部署 Azure 云服务,以在边缘位置处理和分析数据。You can continue on to the next tutorials to learn how Azure IoT Edge can help you deploy Azure cloud services to process and analyze data at the edge.