Criar o componente
Tarefa 1: Criar o workspace
Seção intitulada “Tarefa 1: Criar o workspace”Do diretório que conterá o workspace, execute:
Crie seu 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=cdkOpções desta etapa2
Obrigatório
Depois entre nele:
cd greengrass-tutorialO nome do workspace define o escopo npm @greengrass-tutorial e o namespace Python greengrass_tutorial. Os nomes de projetos gerados carregam esses prefixos, e nx run precisa do nome completo, então o resto deste tutorial usa greengrass_tutorial.telemetry e @greengrass-tutorial/infra.
Tarefa 2: Gerar os projetos
Seção intitulada “Tarefa 2: Gerar os projetos”Crie o projeto Python que hospeda o componente:
Execute este gerador@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- Instale o Nx Console VSCode Plugin se ainda não o fez
- Abra o console Nx no VSCode
- Clique em
Generate (UI)na seção "Common Nx Commands" - Procure por
@aws/nx-plugin - py#project - Preencha os parâmetros obrigatórios
- name: telemetry
- Clique em
Generate
Opções desta etapa1
Obrigatório
Isso cria o projeto greengrass_tutorial.telemetry em packages/telemetry.
Adicione o componente Greengrass a ele:
Execute este gerador@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- Instale o Nx Console VSCode Plugin se ainda não o fez
- Abra o console Nx no VSCode
- Clique em
Generate (UI)na seção "Common Nx Commands" - Procure por
@aws/nx-plugin - greengrass#component - Preencha os parâmetros obrigatórios
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- Clique em
Generate
Opções desta etapa9
Obrigatório
Obrigatório
Cada valor importa mais tarde no tutorial:
platform: linux-amd64corresponde à instância x86_64 que você provisiona no módulo 2. O padrão élinux-arm64, e uma receita construída para uma arquitetura não executa na outra.componentVersion: NEXT_PATCHaloca a versão no momento do deploy. O primeiro deployment publica1.0.0; o módulo 3 publica1.0.1a partir de uma mudança no código-fonte sem editar a receita.ipc: trueé explícito porque este tutorial muda o componente para publicar através do Greengrass IPC.infra: component-versioncomiac: cdkadiciona os constructs reutilizáveis do núcleo Greengrass apackages/common/constructse um construct de aplicaçãoPulseque publica o artefato deste componente.
Crie a aplicação CDK que conterá o deployment:
Execute este gerador@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- Instale o Nx Console VSCode Plugin se ainda não o fez
- Abra o console Nx no VSCode
- Clique em
Generate (UI)na seção "Common Nx Commands" - Procure por
@aws/nx-plugin - ts#infra - Preencha os parâmetros obrigatórios
- name: infra
- Clique em
Generate
Opções desta etapa1
Obrigatório
Os arquivos que este tutorial toca:
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
Tarefa 3: Publicar no AWS IoT Core em vez de pub/sub local
Seção intitulada “Tarefa 3: Publicar no AWS IoT Core em vez de pub/sub local”O main.py gerado publica um heartbeat com publish_to_topic, que alcança outros componentes no mesmo dispositivo núcleo através do serviço local de pub/sub do Greengrass. Ele nunca sai do dispositivo. Para ver o heartbeat no AWS IoT Core, o componente deve usar publish_to_iot_core do cliente IPC, e tanto a receita quanto a política IoT do dispositivo devem permitir isso.
Substitua o packages/telemetry/greengrass/pulse/main.py gerado:
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 recebe o nome do tópico, um QoS de "1" (pelo menos uma vez), e um payload de bytes. O tópico tutorial/greengrass/heartbeat aparece novamente na receita, na política IoT do dispositivo que o módulo 2 cria, e na assinatura do cliente de teste MQTT no módulo 3.
Substitua o bloco de controle de acesso em 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.pyO serviço IPC para AWS IoT Core MQTT é aws.greengrass.ipc.mqttproxy, e publicar é a operação aws.greengrass#PublishToIoTCore. O recurso é o tópico exato. Esta autorização é aplicada pelo núcleo no dispositivo. A política IoT anexada ao certificado do dispositivo é aplicada pelo AWS IoT Core, e ela precisa de iot:Publish no mesmo tópico. O módulo 2 cria essa política.
Atualize o teste gerado, porque o build do projeto hospedeiro o executa e o build dos constructs compartilhados depende do build do hospedeiro:
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}Tarefa 4: Construir o artefato
Seção intitulada “Tarefa 4: Construir o artefato”Execute o teste e construa o artefato do 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 as dependências Python para x86_64-manylinux_2_28, empacota pulse.zip, e escreve a receita resolvida:
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
Continue com Provisionar o dispositivo núcleo.