콘텐츠로 이동

컴포넌트 생성

워크스페이스를 보관할 디렉터리에서 다음을 실행합니다:

워크스페이스 생성@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 컴포넌트 진입점
          • recipe.yaml 컴포넌트 레시피
      • 디렉터리tests
        • 디렉터리greengrass
          • test_pulse.py 컴포넌트의 단위 테스트
      • project.json pulse-vendor, pulse-artifact, pulse-deploy-local 및 pulse-logs 타겟
    • 디렉터리common
      • 디렉터리constructs
        • 디렉터리src
          • core/greengrass 아티팩트 버킷, 컴포넌트 버전, 배포 및 버전 리졸버 구성
          • app/greengrass/pulse.ts Pulse 구성
    • 디렉터리infra
      • 디렉터리src
        • 디렉터리stacks
          • application-stack.ts 모듈 3에서 배포를 구성하는 곳

작업 3: 로컬 pub/sub 대신 AWS IoT Core에 게시

섹션 제목: “작업 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 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는 토픽 이름, "1"의 QoS(최소 한 번), 그리고 바이트 페이로드를 받습니다. 토픽 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 작업입니다. 리소스는 정확한 토픽입니다. 이 권한 부여는 디바이스의 nucleus에 의해 시행됩니다. 디바이스 인증서에 연결된 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 mqttproxy 권한 부여가 포함된 레시피
    • 디렉터리artifacts
      • 디렉터리com.example.Pulse
        • 디렉터리NEXT_PATCH
          • pulse.zip

코어 디바이스 프로비저닝으로 계속 진행합니다.