创建组件
任务 1:创建工作区
Section titled “任务 1:创建工作区”从将要保存工作区的目录运行:
创建工作区@aws/nx-workspace
pnpm create @aws/nx-workspace greengrass-tutorial --iac=cdk yarn create @aws/nx-workspace greengrass-tutorial --iac=cdk npm create @aws/nx-workspace -- greengrass-tutorial --iac=cdk bun 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。
任务 2:生成项目
Section titled “任务 2:生成项目”创建托管组件的 Python 项目:
运行此生成器@aws/nx-plugin:py#project
pnpm nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive yarn nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive npx nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive bunx nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - py#project - 填写必需参数
- name: telemetry
- 点击
Generate
此步骤的选项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 yarn 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 npx 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 bunx 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- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - greengrass#component - 填写必需参数
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- 点击
Generate
此步骤的选项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 yarn nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive npx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive bunx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - ts#infra - 填写必需参数
- name: infra
- 点击
Generate
此步骤的选项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-localandpulse-logstargets
文件夹common
文件夹constructs
文件夹src
- core/greengrass artifact bucket, component version, deployment and version resolver constructs
- app/greengrass/pulse.ts the
Pulseconstruct
文件夹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 jsonimport loggingimport 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 = 30GREETING = "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()import jsonimport loggingimport time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2from awsiot.greengrasscoreipc.model import JsonMessage, PublishMessage
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("com.example.Pulse")
TOPIC = "com.example.Pulse/heartbeat"TOPIC = "tutorial/greengrass/heartbeat"PUBLISH_INTERVAL_SECONDS = 30GREETING = "hello from pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None: client.publish_to_topic( topic=TOPIC, publish_message=PublishMessage(json_message=JsonMessage(message={"sequence": sequence})), ) 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.PulseComponentVersion: NEXT_PATCHComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.ComponentPublisher: greengrass-tutorialComponentConfiguration: 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/heartbeatManifests: - 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.pyRecipeFormatVersion: '2020-01-25'ComponentName: com.example.PulseComponentVersion: NEXT_PATCHComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.ComponentPublisher: greengrass-tutorialComponentConfiguration: DefaultConfiguration: accessControl: aws.greengrass.ipc.pubsub: com.example.Pulse:pubsub:1: policyDescription: Allow publishing heartbeat messages to this component's own topic. aws.greengrass.ipc.mqttproxy: com.example.Pulse:mqttproxy:1: policyDescription: Allow publishing tutorial heartbeats to AWS IoT Core. operations: - aws.greengrass#PublishToTopic - aws.greengrass#PublishToIoTCore resources: - com.example.Pulse/heartbeat - tutorial/greengrass/heartbeatManifests: - 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.pyAWS IoT Core MQTT 的 IPC 服务是 aws.greengrass.ipc.mqttproxy,发布是操作 aws.greengrass#PublishToIoTCore。资源是确切的主题。此授权由设备上的核心强制执行。附加到设备证书的 IoT 策略由 AWS IoT Core 强制执行,它需要在同一主题上具有 iot:Publish。模块 2 创建该策略。
更新生成的测试,因为宿主项目的 build 会运行它,并且共享构造构建依赖于宿主构建:
import importlib.utilimport jsonfrom 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}import importlib.utilimport jsonfrom 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_own_topic():def test_publish_heartbeat_publishes_to_iot_core(): module = _load_main() calls = []
class FakeClient: def publish_to_topic(self, **kwargs): def publish_to_iot_core(self, **kwargs): calls.append(kwargs)
module.publish_heartbeat(FakeClient(), 1)
assert len(calls) == 1 assert calls[0]["topic"] == module.TOPIC assert module.TOPIC == "com.example.Pulse/heartbeat" assert calls[0]["topic_name"] == "tutorial/greengrass/heartbeat" assert calls[0]["qos"] == "1" assert json.loads(calls[0]["payload"]) == {"sequence": 1, "greeting": module.GREETING}任务 4:构建工件
Section titled “任务 4:构建工件”运行测试并构建组件工件:
pnpm nx run greengrass_tutorial.telemetry:testpnpm nx run greengrass_tutorial.telemetry:pulse-artifactyarn nx run greengrass_tutorial.telemetry:testyarn nx run greengrass_tutorial.telemetry:pulse-artifactnpx nx run greengrass_tutorial.telemetry:testnpx nx run greengrass_tutorial.telemetry:pulse-artifactbunx nx run greengrass_tutorial.telemetry:testbunx nx run greengrass_tutorial.telemetry:pulse-artifactpulse-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
继续 配置核心设备。