Tạo component
Nhiệm vụ 1: Tạo workspace
Phần tiêu đề “Nhiệm vụ 1: Tạo workspace”Từ thư mục sẽ chứa workspace, chạy:
Tạo workspace của bạn@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=cdkTùy chọn cho bước này2
Bắt buộc
Sau đó chuyển vào đó:
cd greengrass-tutorialTên workspace đặt npm scope @greengrass-tutorial và Python namespace greengrass_tutorial. Tên dự án được tạo mang các tiền tố này, và nx run cần tên đầy đủ, vì vậy phần còn lại của hướng dẫn này sử dụng greengrass_tutorial.telemetry và @greengrass-tutorial/infra.
Nhiệm vụ 2: Tạo các dự án
Phần tiêu đề “Nhiệm vụ 2: Tạo các dự án”Tạo dự án Python chứa component:
Chạy generator này@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- Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
- Mở Nx Console trong VSCode
- Nhấp
Generate (UI)trong phần "Common Nx Commands" - Tìm kiếm
@aws/nx-plugin - py#project - Điền các tham số bắt buộc
- name: telemetry
- Nhấp
Generate
Tùy chọn cho bước này1
Bắt buộc
Điều này tạo dự án greengrass_tutorial.telemetry tại packages/telemetry.
Thêm component Greengrass vào đó:
Chạy generator này@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- Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
- Mở Nx Console trong VSCode
- Nhấp
Generate (UI)trong phần "Common Nx Commands" - Tìm kiếm
@aws/nx-plugin - greengrass#component - Điền các tham số bắt buộc
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- Nhấp
Generate
Tùy chọn cho bước này9
Bắt buộc
Bắt buộc
Mỗi giá trị đều quan trọng trong hướng dẫn sau này:
platform: linux-amd64khớp với instance x86_64 mà bạn cung cấp trong module 2. Mặc định làlinux-arm64, và một recipe được xây dựng cho một kiến trúc sẽ không chạy trên kiến trúc khác.componentVersion: NEXT_PATCHphân bổ phiên bản tại thời điểm triển khai. Lần triển khai đầu tiên xuất bản1.0.0; module 3 xuất bản1.0.1từ thay đổi nguồn mà không cần chỉnh sửa recipe.ipc: trueđược chỉ định rõ ràng vì hướng dẫn này thay đổi component để xuất bản thông qua Greengrass IPC.infra: component-versionvớiiac: cdkthêm các construct Greengrass core có thể tái sử dụng vàopackages/common/constructsvà một construct ứng dụngPulsexuất bản artifact của component này.
Tạo ứng dụng CDK sẽ chứa deployment:
Chạy generator này@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- Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
- Mở Nx Console trong VSCode
- Nhấp
Generate (UI)trong phần "Common Nx Commands" - Tìm kiếm
@aws/nx-plugin - ts#infra - Điền các tham số bắt buộc
- name: infra
- Nhấp
Generate
Tùy chọn cho bước này1
Bắt buộc
Các tệp mà hướng dẫn này đề cập:
Thư mụcpackages
Thư mụctelemetry
Thư mụcgreengrass
Thư mụcpulse
- main.py the component entrypoint
- recipe.yaml the component recipe
Thư mụctests
Thư mụcgreengrass
- test_pulse.py the component’s unit test
- project.json
pulse-vendor,pulse-artifact,pulse-deploy-localandpulse-logstargets
Thư mụccommon
Thư mụcconstructs
Thư mụcsrc
- core/greengrass artifact bucket, component version, deployment and version resolver constructs
- app/greengrass/pulse.ts the
Pulseconstruct
Thư mụcinfra
Thư mụcsrc
Thư mụcstacks
- application-stack.ts where module 3 composes the deployment
Nhiệm vụ 3: Xuất bản lên AWS IoT Core thay vì pub/sub cục bộ
Phần tiêu đề “Nhiệm vụ 3: Xuất bản lên AWS IoT Core thay vì pub/sub cục bộ”main.py được tạo xuất bản một heartbeat với publish_to_topic, điều này đến các component khác trên cùng một core device thông qua dịch vụ Greengrass pub/sub cục bộ. Nó không bao giờ rời khỏi thiết bị. Để xem heartbeat trong AWS IoT Core, component phải sử dụng publish_to_iot_core từ IPC client, và cả recipe và IoT policy của thiết bị đều phải cho phép nó.
Thay thế packages/telemetry/greengrass/pulse/main.py được tạo:
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 nhận tên topic, một QoS là "1" (ít nhất một lần), và một byte payload. Topic tutorial/greengrass/heartbeat xuất hiện lại trong recipe, trong IoT policy của thiết bị mà module 2 tạo, và trong subscription MQTT test client trong module 3.
Thay thế khối access-control trong 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.pyDịch vụ IPC cho AWS IoT Core MQTT là aws.greengrass.ipc.mqttproxy, và xuất bản là operation aws.greengrass#PublishToIoTCore. Resource là topic chính xác. Ủy quyền này được thực thi bởi nucleus trên thiết bị. IoT policy được đính kèm với certificate thiết bị được thực thi bởi AWS IoT Core, và nó cần iot:Publish trên cùng một topic. Module 2 tạo policy đó.
Cập nhật test được tạo, vì build của dự án host chạy nó và shared constructs build phụ thuộc vào host 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}Nhiệm vụ 4: Xây dựng artifact
Phần tiêu đề “Nhiệm vụ 4: Xây dựng artifact”Chạy test và xây dựng component artifact:
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 vendor các dependency Python cho x86_64-manylinux_2_28, đóng gói pulse.zip, và ghi recipe đã được resolve:
Thư mụcdist/packages/telemetry/greengrass/pulse/greengrass-build
Thư mụcrecipes
- com.example.Pulse-NEXT_PATCH.yaml the recipe with the mqttproxy authorization
Thư mụcartifacts
Thư mụccom.example.Pulse
Thư mụcNEXT_PATCH
- pulse.zip
Tiếp tục với Cung cấp core device.