Creare il componente
Task 1: Creare il workspace
Sezione intitolata “Task 1: Creare il workspace”Dalla directory che conterrà il workspace, eseguire:
Crea il tuo workspace@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=cdkOpzioni di questo passaggio2
Obbligatorio
Quindi accedervi:
cd greengrass-tutorialIl nome del workspace imposta lo scope npm @greengrass-tutorial e il namespace Python greengrass_tutorial. I nomi dei progetti generati portano questi prefissi, e nx run richiede il nome completo, quindi il resto di questo tutorial utilizza greengrass_tutorial.telemetry e @greengrass-tutorial/infra.
Task 2: Generare i progetti
Sezione intitolata “Task 2: Generare i progetti”Creare il progetto Python che ospita il componente:
Esegui questo generatore@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- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - py#project - Compila i parametri richiesti
- name: telemetry
- Clicca su
Generate
Opzioni di questo passaggio1
Obbligatorio
Questo crea il progetto greengrass_tutorial.telemetry in packages/telemetry.
Aggiungervi il componente Greengrass:
Esegui questo generatore@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- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - greengrass#component - Compila i parametri richiesti
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- Clicca su
Generate
Opzioni di questo passaggio9
Obbligatorio
Obbligatorio
Ogni valore è importante più avanti nel tutorial:
platform: linux-amd64corrisponde all’istanza x86_64 che si provisiona nel modulo 2. Il valore predefinito èlinux-arm64, e una ricetta costruita per un’architettura non viene eseguita sull’altra.componentVersion: NEXT_PATCHalloca la versione al momento del deploy. Il primo deployment pubblica1.0.0; il modulo 3 pubblica1.0.1da una modifica del sorgente senza modificare la ricetta.ipc: trueè esplicito perché questo tutorial modifica il componente per pubblicare attraverso Greengrass IPC.infra: component-versionconiac: cdkaggiunge i costrutti core Greengrass riutilizzabili apackages/common/constructse un costrutto appPulseche pubblica l’artefatto di questo componente.
Creare l’applicazione CDK che conterrà il deployment:
Esegui questo generatore@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- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - ts#infra - Compila i parametri richiesti
- name: infra
- Clicca su
Generate
Opzioni di questo passaggio1
Obbligatorio
I file che questo tutorial tocca:
Directorypackages
Directorytelemetry
Directorygreengrass
Directorypulse
- main.py the component entrypoint
- recipe.yaml the component recipe
Directorytests
Directorygreengrass
- test_pulse.py the component’s unit test
- project.json
pulse-vendor,pulse-artifact,pulse-deploy-localandpulse-logstargets
Directorycommon
Directoryconstructs
Directorysrc
- core/greengrass artifact bucket, component version, deployment and version resolver constructs
- app/greengrass/pulse.ts the
Pulseconstruct
Directoryinfra
Directorysrc
Directorystacks
- application-stack.ts where module 3 composes the deployment
Task 3: Pubblicare su AWS IoT Core invece di pub/sub locale
Sezione intitolata “Task 3: Pubblicare su AWS IoT Core invece di pub/sub locale”Il main.py generato pubblica un heartbeat con publish_to_topic, che raggiunge altri componenti sullo stesso core device attraverso il servizio pub/sub locale di Greengrass. Non lascia mai il dispositivo. Per vedere l’heartbeat in AWS IoT Core, il componente deve utilizzare publish_to_iot_core dal client IPC, e sia la ricetta che la policy IoT del dispositivo devono consentirlo.
Sostituire il packages/telemetry/greengrass/pulse/main.py generato:
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 accetta il nome del topic, un QoS di "1" (almeno una volta) e un payload di byte. Il topic tutorial/greengrass/heartbeat appare di nuovo nella ricetta, nella policy IoT del dispositivo che il modulo 2 crea e nella sottoscrizione del client di test MQTT nel modulo 3.
Sostituire il blocco access-control in 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.pyIl servizio IPC per AWS IoT Core MQTT è aws.greengrass.ipc.mqttproxy, e la pubblicazione è l’operazione aws.greengrass#PublishToIoTCore. La risorsa è il topic esatto. Questa autorizzazione è applicata dal nucleus sul dispositivo. La policy IoT collegata al certificato del dispositivo è applicata da AWS IoT Core, e richiede iot:Publish sullo stesso topic. Il modulo 2 crea quella policy.
Aggiornare il test generato, perché il build del progetto host lo esegue e la build dei costrutti condivisi dipende dalla build dell’host:
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}Task 4: Costruire l’artefatto
Sezione intitolata “Task 4: Costruire l’artefatto”Eseguire il test e costruire l’artefatto del componente:
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 vende le dipendenze Python per x86_64-manylinux_2_28, impacchetta pulse.zip e scrive la ricetta risolta:
Directorydist/packages/telemetry/greengrass/pulse/greengrass-build
Directoryrecipes
- com.example.Pulse-NEXT_PATCH.yaml the recipe with the mqttproxy authorization
Directoryartifacts
Directorycom.example.Pulse
DirectoryNEXT_PATCH
- pulse.zip
Continuare con Provisionare il core device.