教程:开发可推迟组件更新的 Greengrass 组件 - Amazon IoT Greengrass
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

教程:开发可推迟组件更新的 Greengrass 组件

你可以完成本教程来开发一个推迟的组件over-the-air部署更新。在向设备部署更新时,您可能需要根据以下条件延迟更新:

  • 该设备的电池电量不足。

  • 设备正在运行无法中断的进程或作业。

  • 该设备的互联网连接有限或昂贵。

注意

一个组件是一个运行在上的软件模块Amazon IoT Greengrass核心设备。组件使您能够将复杂的应用程序作为离散的构建块来创建和管理,您可以将其从一个 Greengrass 核心设备重复使用到另一个。

在本教程中,您将执行以下操作:

  1. 在您的开发计算机上安装 Greengrass 开发套件 CLI (GDK CLI)。GDK CLI 提供的功能可帮助您开发自定义 Greengrass 组件。

  2. 开发 Hello World 组件,该组件可在核心设备的电池电量低于阈值时推迟组件更新。此组件使用订阅更新通知SubscribeToComponentUpdatesIPC 操作。当它收到通知时,它会检查电池电量是否低于可自定义的阈值。如果电池电量低于阈值,则会使用以下方法将更新推迟 30 秒DeferComponentUpdateIPC 操作。您可以使用 GDK CLI 在开发计算机上开发此组件。

    注意

    该组件从您在核心设备上创建的文件中读取电池电量以模仿真实电池,因此您可以在没有电池的核心设备上完成本教程。

  3. 将该组件发布到Amazon IoT Greengrass服务。

  4. 从中部署该组件Amazon Web Services 云到 Greengrass 核心设备上进行测试。然后,您修改核心设备上的虚拟电池电量,并创建其他部署以查看在电池电量不足时核心设备如何推迟更新。

您可以期望在本教程上花费 20—30 分钟。

先决条件

要完成本教程,您需要:

  • 一个 Amazon Web Services 账户。如果没有,请参阅设置一个Amazon Web Services 账户

  • 一个Amazon Identity and Access Management(IAM) 具有管理员权限的用户。

  • 具有互联网连接的 Greengrass 核心设备。有关如何设置核心设备的更多信息,请参阅设置Amazon IoT Greengrass核心设备

    • 巨蛇为核心设备上的所有用户安装了 3.6 或更高版本并已添加到PATH环境变量。在 Windows 上,还必须为所有用户安装适用于 Windows 的 Python 启动器。

      重要

      在 Windows 中,默认情况下不会为所有用户安装 Python。安装 Python 时,必须自定义安装才能将其配置为Amazon IoT Greengrass运行 Python 脚本的核心软件。例如,如果您使用图形化 Python 安装程序,请执行以下操作:

      1. 选择为所有用户安装启动器(推荐)

      2. 选择 Customize installation

      3. 选择 Next

      4. Select Install for all users

      5. Select Add Python to environment variables

      6. 选择安装

      有关更多信息,请参见在 Windows 上使用 Py在里面Python 3 文档

  • 具有互联网连接的 Windows、macOS 或类似 Unix 的开发计算机。

    • 巨蛇3.6 或更高版本安装在您的开发计算机上。

    • 饭桶已安装在您的开发计算机上。

    • Amazon Command Line Interface(Amazon CLI) 在您的开发计算机上安装和配置了凭据。有关更多信息,请参见安装、更新和卸载Amazon CLI正在配置Amazon CLI在里面Amazon Command Line Interface《用户指南》

      注意

      如果你使用 Raspberry Pi 或其他 32 位 ARM 设备,请安装Amazon CLIV1。Amazon CLIV2 不适用于 32 位 ARM 设备。有关更多信息,请参见安装、更新和卸载Amazon CLI版本 1

步骤 1:安装 Greengrass 开发套件 CLI

这个Greengrass 开发套件 CLI (GDK CLI)提供的功能可帮助您开发自定义 Greengrass 组件。您可以使用 GDK CLI 创建、构建和发布自定义组件。

如果您尚未在开发计算机上安装 GDK CLI,请完成以下步骤进行安装。

安装最新版本的 GDK CLI
  1. 在您的开发计算机上,运行以下命令从其安装最新版本的 GDK CLIGitHub知识库

    python3 -m pip install -U git+https://github.com/aws-greengrass/aws-greengrass-gdk-cli.git@v1.3.0
  2. 运行以下命令以验证 GDK CLI 是否已成功安装。

    gdk --help

    如果gdk找不到命令,将其文件夹添加到 PATH。

    • 在 Linux 设备上,添加/home/MyUser/.local/bin到 PATH,然后替换MyUser使用您的用户名。

    • 在 Windows 设备上,添加PythonPath\Scripts到 PATH,然后替换PythonPath包含设备上 Python 文件夹的路径。

步骤 2:开发推迟更新的组件

在本节中,您将在 Python 中开发一个 Hello World 组件,当核心设备的电池电量低于您在部署该组件时配置的阈值时,该组件会推迟组件更新。在此组件中,您可以使用进程间通信 (IPC) 接口在里面Amazon IoT Device SDK适用于 Python 的 v2。你使用SubscribeToComponentUpdatesIPC 操作用于在核心设备收到部署时接收通知。然后,你使用DeferComponentUpdateIPC 操作可根据设备的电池电量推迟或确认更新。

开发推迟更新的 Hello World 组件
  1. 在开发计算机上,为组件源代码创建一个文件夹。

    mkdir com.example.BatteryAwareHelloWorld cd com.example.BatteryAwareHelloWorld
  2. 使用文本编辑器创建名为的文件gdk-config.json。GDK CLI 从GDK CLI 配置文件,被命名为gdk-config.json,用于构建和发布组件。此配置文件存在于组件文件夹的根目录中。

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    nano gdk-config.json

    将以下 JSON 复制到文件中。

    • 替换亚马逊用你的名字。

    • 替换us-west-2和Amazon Web Services 区域您的核心设备在哪里运行。GDK CLI 在此发布组件Amazon Web Services 区域。

    • 替换greengrass-component-artifacts使用 S3 存储桶前缀。当您使用 GDK CLI 发布组件时,GDK CLI 会将组件的构件上传到名称由此值构成的 S3 存储桶Amazon Web Services 区域,还有你的Amazon Web Services 账户ID 使用以下格式:bucketPrefix-region-accountId

      例如,如果您指定greengrass-component-artifactsus-west-2,还有你的Amazon Web Services 账户身份证是123456789012,GDK CLI 使用名为的 S3 存储桶greengrass-component-artifacts-us-west-2-123456789012

    { "component": { "com.example.BatteryAwareHelloWorld": { "author": "Amazon", "version": "NEXT_PATCH", "build": { "build_system" : "zip" }, "publish": { "region": "us-west-2", "bucket": "greengrass-component-artifacts" } } }, "gdk_version": "1.0.0" }

    配置文件指定了以下内容:

    • GDK CLI 将 Greengrass 组件发布到 Greengrass 组件时使用的版本Amazon IoT Greengrass云服务。NEXT_PATCH指定在提供的最新版本之后选择下一个补丁版本Amazon IoT Greengrass云服务。如果组件中没有版本Amazon IoT Greengrass云服务还没有,GDK CLI 使用的是1.0.0

    • 组件的构建系统。当你使用zip构建系统,GDK CLI 将组件的源代码打包成一个 ZIP 文件,该文件成为该组件的单一构件。

    • 这个Amazon Web Services 区域GDK CLI 在其中发布了 Greengrass 组件。

    • GDK CLI 上传组件工件的 S3 存储桶的前缀。

  3. 使用文本编辑器在名为的文件中创建组件源代码main.py

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    nano main.py

    将以下 Python 代码复制到文件中。

    import json import os import sys import time import traceback from pathlib import Path from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2 HELLO_WORLD_PRINT_INTERVAL = 15 # Seconds DEFER_COMPONENT_UPDATE_INTERVAL = 30 * 1000 # Milliseconds class BatteryAwareHelloWorldPrinter(): def __init__(self, ipc_client: GreengrassCoreIPCClientV2, battery_file_path: Path, battery_threshold: float): self.battery_file_path = battery_file_path self.battery_threshold = battery_threshold self.ipc_client = ipc_client self.subscription_operation = None def on_component_update_event(self, event): try: if event.pre_update_event is not None: if self.is_battery_below_threshold(): self.defer_update(event.pre_update_event.deployment_id) print('Deferred update for deployment %s' % event.pre_update_event.deployment_id) else: self.acknowledge_update( event.pre_update_event.deployment_id) print('Acknowledged update for deployment %s' % event.pre_update_event.deployment_id) elif event.post_update_event is not None: print('Applied update for deployment') except: traceback.print_exc() def subscribe_to_component_updates(self): if self.subscription_operation == None: # SubscribeToComponentUpdates returns a tuple with the response and the operation. _, self.subscription_operation = self.ipc_client.subscribe_to_component_updates( on_stream_event=self.on_component_update_event) def close_subscription(self): if self.subscription_operation is not None: self.subscription_operation.close() self.subscription_operation = None def defer_update(self, deployment_id): self.ipc_client.defer_component_update( deployment_id=deployment_id, recheck_after_ms=DEFER_COMPONENT_UPDATE_INTERVAL) def acknowledge_update(self, deployment_id): # Specify recheck_after_ms=0 to acknowledge a component update. self.ipc_client.defer_component_update( deployment_id=deployment_id, recheck_after_ms=0) def is_battery_below_threshold(self): return self.get_battery_level() < self.battery_threshold def get_battery_level(self): # Read the battery level from the virtual battery level file. with self.battery_file_path.open('r') as f: data = json.load(f) return float(data['battery_level']) def print_message(self): message = 'Hello, World!' if self.is_battery_below_threshold(): message += ' Battery level (%d) is below threshold (%d), so the component will defer updates' % ( self.get_battery_level(), self.battery_threshold) else: message += ' Battery level (%d) is above threshold (%d), so the component will acknowledge updates' % ( self.get_battery_level(), self.battery_threshold) print(message) def main(): # Read the battery threshold and virtual battery file path from command-line args. args = sys.argv[1:] battery_threshold = float(args[0]) battery_file_path = Path(args[1]) print('Reading battery level from %s and deferring updates when below %d' % ( str(battery_file_path), battery_threshold)) try: # Create an IPC client and a Hello World printer that defers component updates. ipc_client = GreengrassCoreIPCClientV2() hello_world_printer = BatteryAwareHelloWorldPrinter( ipc_client, battery_file_path, battery_threshold) hello_world_printer.subscribe_to_component_updates() try: # Keep the main thread alive, or the process will exit. while True: hello_world_printer.print_message() time.sleep(HELLO_WORLD_PRINT_INTERVAL) except InterruptedError: print('Subscription interrupted') hello_world_printer.close_subscription() except Exception: print('Exception occurred', file=sys.stderr) traceback.print_exc() exit(1) if __name__ == '__main__': main()

    此 Python 应用程序执行以下操作:

    • 从稍后将在核心设备上创建的虚拟电池电量文件中读取核心设备的电池电量。这个虚拟电池电量文件模仿了真实的电池,因此你可以在没有电池的核心设备上完成本教程。

    • 读取电池阈值的命令行参数和虚拟电池电量文件的路径。组件配方根据配置参数设置这些命令行参数,因此您可以在部署组件时自定义这些值。

    • 在中使用 IPC 客户端 V2Amazon IoT Device SDKPython 的 v2与... 沟通Amazon IoT Greengrass核心软件。与最初的 IPC 客户端相比,IPC 客户端 V2 减少了在自定义组件中使用 IPC 所需的代码量。

    • 使用订阅更新通知SubscribeToComponentUpdatesIPC 操作。这个Amazon IoT Greengrass核心软件在每次部署之前和之后发送通知。该组件每次收到通知时都会调用以下函数。如果通知是针对即将进行的部署,则组件会检查电池电量是否低于阈值。如果电池电量低于阈值,则组件使用以下方法将更新推迟 30 秒DeferComponentUpdateIPC 操作。否则,如果电池电量不低于阈值,则组件会确认更新,因此更新可以继续。

      def on_component_update_event(self, event): try: if event.pre_update_event is not None: if self.is_battery_below_threshold(): self.defer_update(event.pre_update_event.deployment_id) print('Deferred update for deployment %s' % event.pre_update_event.deployment_id) else: self.acknowledge_update( event.pre_update_event.deployment_id) print('Acknowledged update for deployment %s' % event.pre_update_event.deployment_id) elif event.post_update_event is not None: print('Applied update for deployment') except: traceback.print_exc()
      注意

      这个Amazon IoT Greengrass核心软件不会发送本地部署的更新通知,因此您可以使用Amazon IoT Greengrass云服务对其进行测试。

  4. 使用文本编辑器在名为的文件中创建组件配方recipe.json要么recipe.yaml。该组件食谱定义组件的元数据、默认配置参数和特定于平台的生命周期脚本。

    JSON

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    nano recipe.json

    将以下 JSON 复制到文件中。

    { "RecipeFormatVersion": "2020-01-25", "ComponentName": "COMPONENT_NAME", "ComponentVersion": "COMPONENT_VERSION", "ComponentDescription": "This Hello World component defers updates when the battery level is below a threshold.", "ComponentPublisher": "COMPONENT_AUTHOR", "ComponentConfiguration": { "DefaultConfiguration": { "BatteryThreshold": 50, "LinuxBatteryFilePath": "/home/ggc_user/virtual_battery.json", "WindowsBatteryFilePath": "C:\\Users\\ggc_user\\virtual_battery.json" } }, "Manifests": [ { "Platform": { "os": "linux" }, "Lifecycle": { "install": "python3 -m pip install --user awsiotsdk --upgrade", "run": "python3 -u {artifacts:decompressedPath}/com.example.BatteryAwareHelloWorld/main.py \"{configuration:/BatteryThreshold}\" \"{configuration:/LinuxBatteryFilePath}\"" }, "Artifacts": [ { "Uri": "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/com.example.BatteryAwareHelloWorld.zip", "Unarchive": "ZIP" } ] }, { "Platform": { "os": "windows" }, "Lifecycle": { "install": "py -3 -m pip install --user awsiotsdk --upgrade", "run": "py -3 -u {artifacts:decompressedPath}/com.example.BatteryAwareHelloWorld/main.py \"{configuration:/BatteryThreshold}\" \"{configuration:/WindowsBatteryFilePath}\"" }, "Artifacts": [ { "Uri": "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/com.example.BatteryAwareHelloWorld.zip", "Unarchive": "ZIP" } ] } ] }
    YAML

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    nano recipe.yaml

    将以下 YAML 复制到文件中。

    --- RecipeFormatVersion: "2020-01-25" ComponentName: "COMPONENT_NAME" ComponentVersion: "COMPONENT_VERSION" ComponentDescription: "This Hello World component defers updates when the battery level is below a threshold." ComponentPublisher: "COMPONENT_AUTHOR" ComponentConfiguration: DefaultConfiguration: BatteryThreshold: 50 LinuxBatteryFilePath: "/home/ggc_user/virtual_battery.json" WindowsBatteryFilePath: "C:\\Users\\ggc_user\\virtual_battery.json" Manifests: - Platform: os: linux Lifecycle: install: python3 -m pip install --user awsiotsdk --upgrade run: python3 -u {artifacts:decompressedPath}/com.example.BatteryAwareHelloWorld/main.py "{configuration:/BatteryThreshold}" "{configuration:/LinuxBatteryFilePath}" Artifacts: - Uri: "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/com.example.BatteryAwareHelloWorld.zip" Unarchive: ZIP - Platform: os: windows Lifecycle: install: py -3 -m pip install --user awsiotsdk --upgrade run: py -3 -u {artifacts:decompressedPath}/com.example.BatteryAwareHelloWorld/main.py "{configuration:/BatteryThreshold}" "{configuration:/WindowsBatteryFilePath}" Artifacts: - Uri: "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/com.example.BatteryAwareHelloWorld.zip" Unarchive: ZIP

    此食谱指定了以下内容:

    • 电池阈值、Linux 核心设备上的虚拟电池文件路径以及 Windows 核心设备上的虚拟电池文件路径的默认配置参数。

    • 一个install安装最新版本的生命周期Amazon IoT Device SDK适用于 Python 的 v2。

    • 一个run运行 Python 应用程序的生命周期main.py

    • 占位符,例如COMPONENT_NAMECOMPONENT_VERSION,其中 GDK CLI 在构建组件配方时会替换信息。

    有关组件配方的更多信息,请参阅Amazon IoT Greengrass组件配方参考

步骤 3:将组件发布到Amazon IoT Greengrass服务

在本节中,您将 Hello World 组件发布到Amazon IoT Greengrass云服务。在组件可用后Amazon IoT Greengrass云服务,你可以将其部署到核心设备。您可以使用 GDK CLI 将组件从开发计算机发布到Amazon IoT Greengrass云服务。GDK CLI 为您上传组件的配方和构件。

将 Hello World 组件发布到Amazon IoT Greengrass服务
  1. 运行以下命令使用 GDK CLI 构建组件。这个组件构建命令基于 GDK CLI 配置文件创建配方和构件。在此过程中,GDK CLI 会创建一个包含组件源代码的 ZIP 文件。

    gdk component build

    您应该看到与以下示例类似的消息。

    [2022-04-28 11:20:16] INFO - Getting project configuration from gdk-config.json [2022-04-28 11:20:16] INFO - Found component recipe file 'recipe.yaml' in the project directory. [2022-04-28 11:20:16] INFO - Building the component 'com.example.BatteryAwareHelloWorld' with the given project configuration. [2022-04-28 11:20:16] INFO - Using 'zip' build system to build the component. [2022-04-28 11:20:16] WARNING - This component is identified as using 'zip' build system. If this is incorrect, please exit and specify custom build command in the 'gdk-config.json'. [2022-04-28 11:20:16] INFO - Zipping source code files of the component. [2022-04-28 11:20:16] INFO - Copying over the build artifacts to the greengrass component artifacts build folder. [2022-04-28 11:20:16] INFO - Updating artifact URIs in the recipe. [2022-04-28 11:20:16] INFO - Creating component recipe in 'C:\Users\finthomp\greengrassv2\com.example.BatteryAwareHelloWorld\greengrass-build\recipes'.
  2. 运行以下命令将组件发布到Amazon IoT Greengrass云服务。这个组件发布命令将组件的 ZIP 文件构件上传到 S3 存储桶。然后,它在组件配方中更新 ZIP 文件的 S3 URI 并将配方上传到Amazon IoT Greengrass服务。在此过程中,GDK CLI 会检查 Hello World 组件已在哪个版本中可用Amazon IoT Greengrass云服务,因此它可以选择该版本之后的下一个补丁版本。如果该组件尚不存在,则 GDK CLI 使用版本1.0.0

    gdk component publish

    您应该看到与以下示例类似的消息。输出告诉你 GDK CLI 创建的组件的版本。

    [2022-04-28 11:20:29] INFO - Getting project configuration from gdk-config.json [2022-04-28 11:20:29] INFO - Found component recipe file 'recipe.yaml' in the project directory. [2022-04-28 11:20:29] INFO - Found credentials in shared credentials file: ~/.aws/credentials [2022-04-28 11:20:30] INFO - No private version of the component 'com.example.BatteryAwareHelloWorld' exist in the account. Using '1.0.0' as the next version to create. [2022-04-28 11:20:30] INFO - Publishing the component 'com.example.BatteryAwareHelloWorld' with the given project configuration. [2022-04-28 11:20:30] INFO - Uploading the component built artifacts to s3 bucket. [2022-04-28 11:20:30] INFO - Uploading component artifacts to S3 bucket: greengrass-component-artifacts-us-west-2-123456789012. If this is your first time using this bucket, add the 's3:GetObject' permission to each core device's token exchange role to allow it to download the component artifacts. For more information, see https://docs.aws.amazon.com/greengrass/v2/developerguide/device-service-role.html. [2022-04-28 11:20:30] INFO - Not creating an artifacts bucket as it already exists. [2022-04-28 11:20:30] INFO - Updating the component recipe com.example.BatteryAwareHelloWorld-1.0.0. [2022-04-28 11:20:31] INFO - Creating a new greengrass component com.example.BatteryAwareHelloWorld-1.0.0 [2022-04-28 11:20:31] INFO - Created private version '1.0.0' of the component in the account.'com.example.BatteryAwareHelloWorld'.
  3. 从输出中复制 S3 存储桶名称。稍后您可以使用存储桶名称来允许核心设备从该存储桶下载组件构件。

  4. (可选)在中查看组件Amazon IoT Greengrass控制台验证它是否成功上传。执行以下操作:

    1. Amazon IoT Greengrass控制台导航菜单,选择组件

    2. 组件页面,选择我的组件选项卡,然后选择com.example.BatteryAwareHelloWorld

      在此页面上,您可以看到组件的配方以及有关该组件的其他信息。

  5. 允许核心设备访问 S3 存储桶中的组件项目。

    每个核心设备都有一个核心设备 IAM 角色这允许它与之互动Amazon IoT并将日志发送到Amazon云。默认情况下,此设备角色不允许访问 S3 存储桶,因此您必须创建并附加允许核心设备从 S3 存储桶检索组件构件的策略。

    如果您的设备角色已经允许访问 S3 存储桶,则可以跳过此步骤。否则,创建允许访问的 IAM 策略并将其附加到角色,如下所示:

    1. IAM 控制台导航菜单,选择政策,然后选择创建策略

    2. JSON 选项卡中,将占位符内容替换为以下策略。替换greengrass-component-artifacts-us-west-2-123456789012使用 GDK CLI 上传组件工件的 S3 存储桶的名称。

      例如,如果你指定了greengrass-component-artifactsus-west-2在 GDK CLI 配置文件中,而你的Amazon Web Services 账户身份证是123456789012,GDK CLI 使用名为的 S3 存储桶greengrass-component-artifacts-us-west-2-123456789012

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::greengrass-component-artifacts-us-west-2-123456789012/*" } ] }
    3. 选择下一步

    4. 政策详情部分,对于姓名,输入MyGreengrassV2ComponentArtifactPolicy

    5. 选择 Create policy(创建策略)

    6. IAM 控制台导航菜单,选择角色,然后为核心设备选择角色的名称。您在安装时指定了此角色名称Amazon IoT Greengrass核心软件。如果您未指定名称,则默认为GreengrassV2TokenExchangeRole

    7. 权限,选择添加权限,然后选择附加政策

    8. 添加权限页面,选中旁边的复选框MyGreengrassV2ComponentArtifactPolicy您创建的策略,然后选择添加权限

步骤 4:在核心设备上部署和测试组件

在本节中,您将组件部署到核心设备以测试其功能。在核心设备上,您可以创建虚拟电池电量文件来模仿真实电池。然后,您创建其他部署并观察核心设备上的组件日志文件,以查看组件延迟和确认更新。

部署和测试推迟更新的 Hello World 组件
  1. 使用文本编辑器创建虚拟电池电量文件。这个文件模仿了真正的电池。

    • 在 Linux 核心设备上,创建一个名为的文件/home/ggc_user/virtual_battery.json。使用以下命令运行文本编辑器sudo权限。

    • 在 Windows 核心设备上,创建一个名为的文件C:\Users\ggc_user\virtual_battery.json。以管理员身份运行文本编辑器。

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    sudo nano /home/ggc_user/virtual_battery.json

    将以下 JSON 复制到文件中。

    { "battery_level": 50 }
  2. 将 Hello World 组件部署到核心设备。执行以下操作:

    1. Amazon IoT Greengrass控制台导航菜单,选择组件

    2. 组件页面,选择我的组件选项卡,然后选择com.example.BatteryAwareHelloWorld

    3. com.example.BatteryAwareHelloWorld页面,选择部署

    4. 来自添加到部署,选择要修改的现有部署,或者选择创建新部署,然后选择下一步

    5. 如果您选择创建新部署,请为部署选择目标核心设备或事物组。在指定目标页面,下方部署目标,选择核心设备或事物组,然后选择下一步

    6. 选择组件页面,验证com.example.BatteryAwareHelloWorld组件被选中,选择下一步

    7. 配置组件页面,选择com.example.BatteryAwareHelloWorld,然后执行以下操作:

      1. 选择配置组件

      2. 配置com.example.BatteryAwareHelloWorld模态,低于配置更新,在要合并的配置,输入以下配置更新。

        { "BatteryThreshold": 70 }
      3. 选择确认关闭模态,然后选择下一步

    8. 确认高级设置页面,在部署策略部分,下方组件更新政策,确认通知组件被选中。通知组件创建新部署时默认处于选中状态。

    9. Review(检查)页上,选择 Deploy(部署)。

      部署最多可能需要一分钟才能完成。

  3. 这个Amazon IoT Greengrass核心软件将 stdout 从组件进程保存到日志文件中logs文件夹。运行以下命令以验证 Hello World 组件是否运行并打印状态消息。

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.BatteryAwareHelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log
    PowerShell
    gc C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log -Tail 10 -Wait

    您应该看到与以下示例类似的消息。

    Hello, World! Battery level (50) is below threshold (70), so the component will defer updates.
    注意

    如果文件不存在,则部署可能尚未完成。如果该文件在 30 秒内不存在,则部署可能失败。例如,如果核心设备无权从 S3 存储桶下载组件的构件,则可能会发生这种情况。运行以下命令查看Amazon IoT Greengrass核心软件日志文件。此文件包含来自 Greengrass 核心设备部署服务的日志。

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/greengrass.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\greengrass.log

    这个type命令将文件内容写入终端。多次运行此命令以观察文件中的变化。

    PowerShell
    gc C:\greengrass\v2\logs\greengrass.log -Tail 10 -Wait
  4. 为核心设备创建新的部署,以验证该组件是否推迟更新。执行以下操作:

    1. Amazon IoT Greengrass控制台导航菜单,选择部署

    2. 选择您之前创建或修改的部署。

    3. 在部署页面上,选择修改

    4. 修改部署模态,选择修改部署

    5. 选择下一步在每一步中,然后选择部署

  5. 运行以下命令以再次查看组件的日志,并验证其是否推迟更新。

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.BatteryAwareHelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log
    PowerShell
    gc C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log -Tail 10 -Wait

    您应该看到与以下示例类似的消息。该组件将更新推迟 30 秒,因此该组件会重复打印此消息。

    Deferred update for deployment 50722a95-a05f-4e2a-9414-da80103269aa.
  6. 使用文本编辑器编辑虚拟电池电量文件并将电池电量更改为高于阈值的值,这样部署就可以继续了。

    • 在 Linux 核心设备上,编辑名为的文件/home/ggc_user/virtual_battery.json。使用以下命令运行文本编辑器sudo权限。

    • 在 Windows 核心设备上,编辑名为的文件C:\Users\ggc_user\virtual_battery.json。以管理员身份运行文本编辑器。

    例如,在基于 Linux 的系统上,你可以运行以下命令来使用 GNU nano 来创建文件。

    sudo nano /home/ggc_user/virtual_battery.json

    将电池电量更改为80

    { "battery_level": 80 }
  7. 运行以下命令再次查看组件的日志,并验证其是否确认更新。

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.BatteryAwareHelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log
    PowerShell
    gc C:\greengrass\v2\logs\com.example.BatteryAwareHelloWorld.log -Tail 10 -Wait

    您应该看到与以下示例类似的消息。

    Hello, World! Battery level (80) is above threshold (70), so the component will acknowledge updates. Acknowledged update for deployment f9499eb2-4a40-40a7-86c1-c89887d859f1.

你已经完成了本教程。Hello World 组件根据核心设备的电池电量推迟或确认更新。有关本教程探讨的主题的更多信息,请参阅以下内容: