コンポーネントを作成する
タスク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 coreコンストラクトを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
必須
このチュートリアルで触れるファイル:
Directorypackages
Directorytelemetry
Directorygreengrass
Directorypulse
- main.py コンポーネントのエントリーポイント
- recipe.yaml コンポーネントのレシピ
Directorytests
Directorygreengrass
- test_pulse.py コンポーネントのユニットテスト
- project.json
pulse-vendor、pulse-artifact、pulse-deploy-local、pulse-logsターゲット
Directorycommon
Directoryconstructs
Directorysrc
- core/greengrass アーティファクトバケット、コンポーネントバージョン、デプロイメント、バージョンリゾルバーコンストラクト
- app/greengrass/pulse.ts
Pulseコンストラクト
Directoryinfra
Directorysrc
Directorystacks
- application-stack.ts モジュール3でデプロイメントを構成する場所
タスク3: ローカルpub/subの代わりにAWS IoT Coreに公開する
Section titled “タスク3: ローカルpub/subの代わりにAWS IoT Coreに公開する”生成された 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"(少なくとも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 です。リソースは正確なトピックです。この認可はデバイス上のnucleusによって強制されます。デバイス証明書に添付された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 をパッケージ化し、解決されたレシピを書き込みます:
Directorydist/packages/telemetry/greengrass/pulse/greengrass-build
Directoryrecipes
- com.example.Pulse-NEXT_PATCH.yaml mqttproxy認可を含むレシピ
Directoryartifacts
Directorycom.example.Pulse
DirectoryNEXT_PATCH
- pulse.zip
コアデバイスをプロビジョニングするに進みます。