跳转到内容

创建组件

从将要保存工作区的目录运行:

创建工作区@aws/nx-workspace

pnpm create @aws/nx-workspace greengrass-tutorial --iac=cdk
此步骤的选项2

必需

然后进入该目录:

终端窗口
cd greengrass-tutorial

工作区名称设置了 npm 作用域 @greengrass-tutorial 和 Python 命名空间 greengrass_tutorial。生成的项目名称带有这些前缀,nx run 需要完整名称,因此本教程的其余部分使用 greengrass_tutorial.telemetry 和 @greengrass-tutorial/infra。

创建托管组件的 Python 项目:

运行此生成器@aws/nx-plugin:py#project

pnpm nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive
此步骤的选项1

必需

这将在 packages/telemetry 创建项目 greengrass_tutorial.telemetry。

向其添加 Greengrass 组件:

运行此生成器@aws/nx-plugin:greengrass#component

pnpm nx g @aws/nx-plugin:greengrass#component --project=telemetry --name=pulse --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.Pulse --componentVersion=NEXT_PATCH --ipc=true --no-interactive
此步骤的选项9

必需

必需

每个值在教程后面都很重要:

  • platform: linux-amd64 与您在模块 2 中配置的 x86_64 实例匹配。默认值是 linux-arm64,为一种架构构建的配方无法在另一种架构上运行。
  • componentVersion: NEXT_PATCH 在部署时分配版本。第一次部署发布 1.0.0;模块 3 从源代码更改发布 1.0.1,无需编辑配方。
  • ipc: true 是显式的,因为本教程将组件更改为通过 Greengrass IPC 发布。
  • infra: component-version 与 iac: cdk 将可重用的 Greengrass 核心构造添加到 packages/common/constructs,并添加一个发布此组件工件的 Pulse 应用程序构造。

创建将保存部署的 CDK 应用程序:

运行此生成器@aws/nx-plugin:ts#infra

pnpm nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
此步骤的选项1

必需

本教程涉及的文件:

  • 文件夹packages
    • 文件夹telemetry
      • 文件夹greengrass
        • 文件夹pulse
          • main.py the component entrypoint
          • recipe.yaml the component recipe
      • 文件夹tests
        • 文件夹greengrass
          • test_pulse.py the component’s unit test
      • project.json pulse-vendor, pulse-artifact, pulse-deploy-local and pulse-logs targets
    • 文件夹common
      • 文件夹constructs
        • 文件夹src
          • core/greengrass artifact bucket, component version, deployment and version resolver constructs
          • app/greengrass/pulse.ts the Pulse construct
    • 文件夹infra
      • 文件夹src
        • 文件夹stacks
          • application-stack.ts where module 3 composes the deployment

任务 3:发布到 AWS IoT Core 而不是本地 pub/sub

Section titled “任务 3:发布到 AWS IoT Core 而不是本地 pub/sub”

生成的 main.py 使用 publish_to_topic 发布心跳,它通过本地 Greengrass pub/sub 服务到达同一核心设备上的其他组件。它永远不会离开设备。要在 AWS IoT Core 中查看心跳,组件必须使用 IPC 客户端的 publish_to_iot_core,并且配方和设备的 IoT 策略都必须允许它。

替换生成的 packages/telemetry/greengrass/pulse/main.py:

import json
import logging
import time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("com.example.Pulse")
TOPIC = "tutorial/greengrass/heartbeat"
PUBLISH_INTERVAL_SECONDS = 30
GREETING = "hello from pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None:
payload = json.dumps({"sequence": sequence, "greeting": GREETING}).encode("utf-8")
client.publish_to_iot_core(topic_name=TOPIC, qos="1", payload=payload)
logger.info("Published heartbeat %s to %s", sequence, TOPIC)
def main() -> None:
client = GreengrassCoreIPCClientV2()
sequence = 0
while True:
publish_heartbeat(client, sequence)
sequence += 1
time.sleep(PUBLISH_INTERVAL_SECONDS)
if __name__ == "__main__":
main()

publish_to_iot_core 接受主题名称、QoS 为 "1"(至少一次)和字节负载。主题 tutorial/greengrass/heartbeat 再次出现在配方中、模块 2 创建的设备 IoT 策略中以及模块 3 中的 MQTT 测试客户端订阅中。

替换 packages/telemetry/greengrass/pulse/recipe.yaml 中的访问控制块:

RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.Pulse
ComponentVersion: NEXT_PATCH
ComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.
ComponentPublisher: greengrass-tutorial
ComponentConfiguration:
DefaultConfiguration:
accessControl:
aws.greengrass.ipc.mqttproxy:
com.example.Pulse:mqttproxy:1:
policyDescription: Allow publishing tutorial heartbeats to AWS IoT Core.
operations:
- aws.greengrass#PublishToIoTCore
resources:
- tutorial/greengrass/heartbeat
Manifests:
- Platform:
os: linux
architecture: amd64
Artifacts:
# Placeholders are substituted at publish time. The basename must stay
# pulse.zip, which is what the Run script below unarchives to.
- Uri: s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/pulse.zip
Unarchive: ZIP
Lifecycle:
Run: python3.14 {artifacts:decompressedPath}/pulse/main.py

AWS IoT Core MQTT 的 IPC 服务是 aws.greengrass.ipc.mqttproxy,发布是操作 aws.greengrass#PublishToIoTCore。资源是确切的主题。此授权由设备上的核心强制执行。附加到设备证书的 IoT 策略由 AWS IoT Core 强制执行,它需要在同一主题上具有 iot:Publish。模块 2 创建该策略。

更新生成的测试,因为宿主项目的 build 会运行它,并且共享构造构建依赖于宿主构建:

import importlib.util
import json
from pathlib import Path
# main.py lives beside recipe.yaml under greengrass/<component>/, outside this
# project's importable package, so it is loaded directly by file path.
PROJECT_ROOT = Path(__file__).resolve().parents[2]
MAIN_PATH = PROJECT_ROOT / "greengrass" / "pulse" / "main.py"
def _load_main():
spec = importlib.util.spec_from_file_location("pulse_main", MAIN_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_publish_heartbeat_publishes_to_iot_core():
module = _load_main()
calls = []
class FakeClient:
def publish_to_iot_core(self, **kwargs):
calls.append(kwargs)
module.publish_heartbeat(FakeClient(), 1)
assert len(calls) == 1
assert calls[0]["topic_name"] == "tutorial/greengrass/heartbeat"
assert calls[0]["qos"] == "1"
assert json.loads(calls[0]["payload"]) == {"sequence": 1, "greeting": module.GREETING}

运行测试并构建组件工件:

Terminal window
pnpm nx run greengrass_tutorial.telemetry:test
pnpm nx run greengrass_tutorial.telemetry:pulse-artifact

pulse-artifact 为 x86_64-manylinux_2_28 打包 Python 依赖项,打包 pulse.zip,并写入解析的配方:

  • 文件夹dist/packages/telemetry/greengrass/pulse/greengrass-build
    • 文件夹recipes
      • com.example.Pulse-NEXT_PATCH.yaml the recipe with the mqttproxy authorization
    • 文件夹artifacts
      • 文件夹com.example.Pulse
        • 文件夹NEXT_PATCH
          • pulse.zip

继续 配置核心设备。